From 105a6fe48ba31c794954b116ac80ec120f643f6a Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 20:03:25 +0300 Subject: [PATCH 01/85] feat: start 0.9.0 Spark and MLflow initiative with runtime tests Signed-off-by: flyingriverhorse --- .github/workflows/spark-tests.yml | 34 + .gitignore | 1 + CHANGELOG.md | 1 + changelog/0.9.x.md | 34 + docs/user_guide/spark.md | 87 +++ frontend/ml-canvas/package-lock.json | 4 +- frontend/ml-canvas/package.json | 2 +- .../spark_and_mlflow/01-core-spark-plan.md | 296 +++++++++ .../spark_and_mlflow/02-inference-plan.md | 184 ++++++ .../03-mlflow-batch-delivery-plan.md | 300 +++++++++ initiatives/spark_and_mlflow/ARCHITECTURE.md | 210 ++++++ initiatives/spark_and_mlflow/BASELINE.md | 110 ++++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 82 +++ initiatives/spark_and_mlflow/README.md | 68 ++ initiatives/spark_and_mlflow/VALIDATION.md | 88 +++ .../2026-09-21-spark-core-inventory.md | 597 ++++++++++++++++++ .../2026-09-21-spark-databricks-readiness.md | 360 +++++++++++ mkdocs.yml | 1 + pyproject.toml | 2 +- requirements-spark.txt | 10 + skyulf-core/setup.py | 7 +- skyulf-core/tests/spark/conftest.py | 42 ++ skyulf-core/tests/spark/test_runtime_smoke.py | 33 + uv.lock | 28 +- 24 files changed, 2573 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/spark-tests.yml create mode 100644 changelog/0.9.x.md create mode 100644 docs/user_guide/spark.md create mode 100644 initiatives/spark_and_mlflow/01-core-spark-plan.md create mode 100644 initiatives/spark_and_mlflow/02-inference-plan.md create mode 100644 initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md create mode 100644 initiatives/spark_and_mlflow/ARCHITECTURE.md create mode 100644 initiatives/spark_and_mlflow/BASELINE.md create mode 100644 initiatives/spark_and_mlflow/OPEN_QUEUE.md create mode 100644 initiatives/spark_and_mlflow/README.md create mode 100644 initiatives/spark_and_mlflow/VALIDATION.md create mode 100644 initiatives/spark_and_mlflow/reports/2026-09-21-spark-core-inventory.md create mode 100644 initiatives/spark_and_mlflow/reports/2026-09-21-spark-databricks-readiness.md create mode 100644 requirements-spark.txt create mode 100644 skyulf-core/tests/spark/conftest.py create mode 100644 skyulf-core/tests/spark/test_runtime_smoke.py diff --git a/.github/workflows/spark-tests.yml b/.github/workflows/spark-tests.yml new file mode 100644 index 000000000..8d445e8c9 --- /dev/null +++ b/.github/workflows/spark-tests.yml @@ -0,0 +1,34 @@ +name: Spark Runtime Tests + +on: + pull_request: + branches: [main, master] + paths: + - "skyulf-core/**" + - "requirements-spark.txt" + - ".github/workflows/spark-tests.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + spark: + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + SKYULF_REQUIRE_SPARK: "1" + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + - name: Install optional Spark test dependencies + run: uv pip install --system -r requirements-spark.txt + - name: Exercise Spark JVM and Python workers + run: python -m pytest skyulf-core/tests/spark -q -o addopts= diff --git a/.gitignore b/.gitignore index 746ba20a4..daebbdf86 100644 --- a/.gitignore +++ b/.gitignore @@ -163,6 +163,7 @@ site/ .github/instructions/codacy.instructions.md .worktrees/ +.venv-spark/ sast/architecture.md sast/final-report.md sast/hardcodedsecrets-results.md diff --git a/CHANGELOG.md b/CHANGELOG.md index ea65dc1f1..73441ffd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Each major/minor series has its own file in the [`changelog/`](changelog/) folde | Series | File | Status | Description | |--------|------|--------|-------------| +| **0.9.x** | [changelog/0.9.x.md](changelog/0.9.x.md) | Unreleased | Spark execution and optional MLflow integration — in development | | **0.8.x** | [changelog/0.8.x.md](changelog/0.8.x.md) | Active | (v0.8.0+) | | **0.7.x** | [changelog/0.7.x.md](changelog/0.7.x.md) | Stable | Model Explainability, Segmentation Models & Unified Training Pipeline (v0.7.0 — v0.7.9) | | **0.6.x** | [changelog/0.6.x.md](changelog/0.6.x.md) | Stable | Ensemble Models, Security Hardening & Codebase Audit Sweeps (v0.6.0 — v0.6.10) | diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md new file mode 100644 index 000000000..fe61b59d3 --- /dev/null +++ b/changelog/0.9.x.md @@ -0,0 +1,34 @@ +# Changelog — 0.9.x Series + +For the version index, see root [CHANGELOG.md](../CHANGELOG.md). + +## v0.9.0 — Unreleased + +Target: optional Spark execution and MLflow integration for Skyulf Core. +Development version: 0.9.0. This release has not been published; Spark node +execution and MLflow adapters remain under development. + +### Added + +- Spark/MLflow initiative: architecture, implementation plans, validation gates + and an ordered [task queue](../initiatives/spark_and_mlflow/OPEN_QUEUE.md). + Historical readiness reports are grouped with the initiative. +- Experimental Spark test foundation (SM-00): optional `spark` extra, separate + `requirements-spark.txt`, a Java 17/Python 3.12 CI lane and real JVM/Arrow + worker smoke tests. The dedicated lane fails if PySpark is missing; normal + core tests can skip the optional runtime. No Spark node capability is enabled. +- [Spark development guide](../docs/user_guide/spark.md) with isolated setup, + a runtime example, troubleshooting and explicit support boundaries. + +### Planned scope — not yet available + +- Native Spark feature engineering with explicit fit/apply capabilities and + portable fitted state for supported pandas/Polars/Spark operations. +- Distributed Python inference: native Spark preprocessing followed by Python + prediction, or a compatible Python preprocessing/model pipeline on workers. +- Optional MLflow tracking/model packaging and Unity Catalog model resolution. +- Scheduled batch inference with reproducible model versions and Delta outputs. + +Endpoint integrations and template/Databricks Bundle generation follow the +core and batch validation gates. Planned items are not shipped functionality; +verified delivery notes will be added as the tasks are completed. diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md new file mode 100644 index 000000000..115c33047 --- /dev/null +++ b/docs/user_guide/spark.md @@ -0,0 +1,87 @@ +# Spark: development setup and current support + +Spark support is under development for 0.9.0. The optional dependency and +runtime tests are available in the development checkout. **Skyulf's Spark +engine, native nodes and distributed model inference are not available yet.** +Installing the extra does not convert a pandas/Polars pipeline to Spark. + +## Why a separate environment? + +`.venv-spark` isolates PySpark and its dependencies from the web application's +existing `.venv`. It is a local development convention, not a runtime requirement +or a directory shipped with Skyulf. Both environments are excluded from Git. +Use your own environment name if preferred. + +The initial test target is Python 3.12, PySpark 4.0.3 and Java 17. Java must be +installed separately. `JAVA_HOME` should point to the JDK directory. Consult +the [Spark installation documentation](https://spark.apache.org/docs/4.0.3/api/python/getting_started/install.html) +for runtime requirements. Databricks Runtime and Connect require their own +validated dependency profiles; do not replace a managed runtime's PySpark +installation with this development environment. + +## Install from the repository + +Run these commands from the repository root. Create the environment only once. + +```powershell +uv venv .venv-spark --python 3.12 +uv pip install --python .venv-spark/Scripts/python.exe -r requirements-spark.txt +$env:JAVA_HOME = 'C:\path\to\jdk-17' +$env:SKYULF_REQUIRE_SPARK = '1' +.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark -q -o addopts= +``` + +On Linux/macOS: + +```bash +uv venv .venv-spark --python 3.12 +uv pip install --python .venv-spark/bin/python -r requirements-spark.txt +export JAVA_HOME=/path/to/jdk-17 +SKYULF_REQUIRE_SPARK=1 .venv-spark/bin/python -m pytest skyulf-core/tests/spark -q -o addopts= +``` + +The tests execute a distributed aggregate and an Arrow/Python worker transform. +The mandatory lane fails when PySpark is missing. In the ordinary core suite, +the optional runtime tests skip if PySpark is not installed. A skip does not +prove Spark compatibility. + +## Minimal runtime example + +This is a plain PySpark example, not a Skyulf feature-engineering pipeline. +Run it using the Spark environment's Python interpreter. + +```python +import os +import sys + +from pyspark.sql import SparkSession, functions as F + +os.environ["PYSPARK_PYTHON"] = sys.executable +spark = SparkSession.builder.master("local[2]").appName("spark-check").getOrCreate() +try: + frame = spark.range(100).repartition(2) + total = frame.agg(F.sum("id").alias("total")).first()["total"] + assert total == 4950 +finally: + spark.stop() +``` + +Only one aggregate row is returned to Python. Future native FE operations will +keep the dataset in Spark and transfer bounded learned state when supported. +Python model inference on Spark workers is a separate capability from native +Spark model training. + +## Troubleshooting and support boundaries + +- **Java gateway fails:** check Java 17 and the current shell's `JAVA_HOME`. +- **Worker cannot find Python:** use the same interpreter for driver and workers; + the test fixture sets `PYSPARK_PYTHON` explicitly. +- **Windows access denied at shutdown:** a process sandbox can prevent Spark's + child-process cleanup. A passing calculation does not prove clean shutdown; + use an environment that permits the owned JVM processes to terminate. +- **Engine not found:** this is expected before the Spark engine implementation + is delivered. Do not collect an entire distributed frame into pandas as a workaround. + +MLflow tracking, Unity Catalog registration, Databricks jobs, serving endpoints +and Bundle templates are separate integration stages. This page will gain +tested fit/apply and inference examples as those capabilities are implemented. diff --git a/frontend/ml-canvas/package-lock.json b/frontend/ml-canvas/package-lock.json index d34a4614d..786e5de87 100644 --- a/frontend/ml-canvas/package-lock.json +++ b/frontend/ml-canvas/package-lock.json @@ -1,12 +1,12 @@ { "name": "ml-canvas", - "version": "0.8.24", + "version": "0.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ml-canvas", - "version": "0.8.24", + "version": "0.9.0", "dependencies": { "@hookform/resolvers": "^3.3.4", "@radix-ui/react-accordion": "^1.1.2", diff --git a/frontend/ml-canvas/package.json b/frontend/ml-canvas/package.json index 8a433a483..efdfb2f1e 100644 --- a/frontend/ml-canvas/package.json +++ b/frontend/ml-canvas/package.json @@ -1,7 +1,7 @@ { "name": "ml-canvas", "private": true, - "version": "0.8.24", + "version": "0.9.0", "type": "module", "scripts": { "dev": "vite", diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md new file mode 100644 index 000000000..ad5c503ae --- /dev/null +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -0,0 +1,296 @@ +# Core Spark Implementation Plan + +> **For agentic workers:** Use the `executing-plans` skill to implement this +> plan task-by-task. Read the spec and queue first; do not start later tasks +> whose acceptance gates are incomplete. + +**Goal:** Gerçek Spark fit/apply ve küçük state'in engine'ler arası taşınması. +**Architecture:** Mevcut Calculator/Applier ve engine-keyed dispatcher korunur. +Spark lazy/distributed işlemleri local dataframe sözleşmesinden ayrılır. +**Tech Stack:** Python >=3.12, pandas, Polars, PySpark SQL, pytest. +**Spec:** [ARCHITECTURE.md](ARCHITECTURE.md). + +## Global constraints + +- Örtük ham veri collect yok; sınırlı aggregate state collection açıkça ölçülür. +- Spark için unsupported node'lar işlem başlamadan hata verir. +- Mevcut local API ve varsayılan değişmez; yeni yollar opt-in olur. +- Spark session artifact içinde bulunmaz; key/target kolonları feature değildir. +- Yeni dependency kurulumları `uv pip`; mevcut manifest/requirements eşlenir. +- Commit yalnız kullanıcı isteğiyle; her görev sonu kanıt queue'ya işlenir. + +Her görevde önce belirtilen davranış testi yazılır, fail nedeni incelenir, en dar +uygulama yapılır, aynı test ve ilgili eski local testler çalıştırılır. Örneklerde +yazılan yeni API isimleri bu planın teslim edeceği isimlerdir; bugün var sayılmaz. +Yeni test kökü: `skyulf-core/tests/spark/`; fixture dosyası `conftest.py`. + +## SM-00 — Baseline ve test ortamı + +**Bağımlılık:** Yok. **Mevcut:** `engines/registry.py`, `preprocessing/dispatcher.py`, +`skyulf-core/setup.py`, `skyulf-core/pyproject.toml`, mevcut requirements ve CI config. +**Oluştur:** `skyulf-core/tests/spark/conftest.py`, +`skyulf-core/tests/spark/test_runtime_smoke.py`, +`initiatives/spark_and_mlflow/BASELINE.md` (bu görev uygulanırken). +**Arayüz:** `spark` pytest fixture; local[2] session, UTC timezone; +SM-01–SM-11 bu fixture'ı tüketir. + +- [x] HEAD, working tree, Python/Java, paket sürümleri, registry default ve + mevcut fit/apply/save/load API'lerini BASELINE.md'ye kaydet. Tarihsel rapor + sayılarını yeni ölçüm gibi kopyalama; eşzamanlı değişiklikleri ayır. +- [x] Local regression için mevcut engine/pipeline/artifact testlerini çalıştır. + Önceden var olan failure'ları hata ve nedenleriyle kaydet. +- [x] Ayrı Spark test ortamı oluştur; Python >=3.12 ile uyumlu Spark/Java çiftini + resmî sürüm dokümanıyla sabitle. Base dependency'ye PySpark ekleme; `spark` + extra ve test dependencies'i aynı sürüm aralığına hizala. +- [x] Fixture session'ı teardown'da kapatsın. Base suite Spark yoksa skip edebilir; + Spark release job'ı import başarısızlığında fail etsin, toplu skip başarı sayılmasın. +- [x] Aşağıdaki testi yeni ortamda çalıştır ve environment bilgileriyle kaydet. + +```python +def test_spark_executes_multiple_partitions(spark): + """Prove that the Spark test lane executes an action on partitioned data.""" + from pyspark.sql import functions as F + frame = spark.range(100).repartition(2) + total = frame.agg(F.sum("id").alias("total")).first()["total"] + assert total == 4950 +``` + +**Komut:** `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_runtime_smoke.py -q` +**Kabul:** Spark action gerçekten çalışır; local baseline ve runtime sürümleri kayıtlı. + +## SM-01 — Execution ve capability sözleşmesi + +**Bağımlılık:** SM-00. **Oluştur:** `skyulf/core/execution.py`, +`skyulf/core/capabilities.py`, `tests/spark/test_capabilities.py` (ilk iki yol +`skyulf-core/` altında; bu planda tüm `skyulf/` ve `tests/` yolları aynı köke göre). +**Değiştir:** `skyulf/registry.py`, `skyulf/config_validation.py`. +**Tüketir:** Mevcut node registration anahtarları ve operation metadata. +**Üretir:** ARCHITECTURE'daki FrameSpec, ExecutionOptions, +`require_capability(...)`; `UnsupportedExecutionError(ValueError)`. + +- [ ] Mevcut registry anahtarlarını dolaşan testte Spark desteği ilan edilmemiş + bütün fit/apply kombinasyonlarının açıklayıcı hatayla reddedildiğini sabitle. +- [ ] Capability kaydına engine + operation + config strategy + row/context etkisi + ekle. Alias'lar canonical node ile aynı kararı vermeli; ikinci node registry yok. +- [ ] FrameSpec duplicate key isimlerini/target-key çakışmasını; options sıfır/negatif + limitleri ve bilinmeyen engine'i reddetsin. Frame içeriği kontrolü SM-03'te. +- [ ] Yeni runtime config'de yazım hatasının sessizce kabul edilmediğini test et. + Eski config davranışını topluca değiştirme. + +```python +def test_unimplemented_spark_fit_is_explicit(): + """An unsupported fit must not fall back to collecting a local frame.""" + import pytest + from skyulf.core.capabilities import require_capability, UnsupportedExecutionError + with pytest.raises(UnsupportedExecutionError, match="spark"): + require_capability("KNNImputer", "fit", "spark", config={}) +``` + +**Komut:** `python -m pytest skyulf-core/tests/spark/test_capabilities.py -q` +**Kabul:** Destek olmayan yol herhangi bir Spark action veya estimator fit çağırmaz. + +## SM-02 — Spark engine ve materialization sınırı + +**Bağımlılık:** SM-01. **Oluştur:** `skyulf/engines/spark_engine.py`, +`tests/spark/test_engine_contract.py`. **Değiştir:** +`skyulf/engines/{registry,protocol,__init__}.py`, `skyulf/engines/sklearn_bridge.py`. +**Üretir:** SparkEngine; `EngineName.SPARK`; açık distributed frame sözleşmesi. + +- [ ] Gerçek Spark frame'in `get_engine(frame)` sonucunu ve local default'un + değişmediğini test et. Paket yokken core importu başarılı kalmalı. +- [ ] Bilinen pyspark frame için engine kurulu/kayıtlı değilse erken dependency + hatası ekle; bilinmeyen local objelerin mevcut fallback davranışını ayrı koru. +- [ ] `len/shape/to_numpy/toPandas` gerektiren local protocol'ü Spark'a sahte + implement etme. Local-only materialization metodları açıklayıcı hata versin; + schema/columns/select gibi yetenekleri ayrı dar protocol üzerinden sağla. +- [ ] SklearnBridge Spark veriyi reddetsin. Session yaratma, session singleton + tutma veya RDD tabanlı wrapper ekleme. + +```python +def test_spark_engine_does_not_replace_local_default(spark): + """Input detection must leave unrelated local jobs on their existing engine.""" + from skyulf.engines import get_engine + before = get_engine().name + assert get_engine(spark.range(2)).name == "spark" + assert get_engine().name == before +``` + +**Komut:** `python -m pytest skyulf-core/tests/spark/test_engine_contract.py -q` +**Kabul:** Import isolation, gerçek frame detection, yasak materialization ve +local engine regression testleri geçer. + +## SM-03 — Dispatcher, schema ve key-aware FE girişi + +**Bağımlılık:** SM-02. **Oluştur:** `skyulf/preprocessing/_spark.py`, +`tests/spark/test_frame_contract.py`. **Değiştir:** +`skyulf/preprocessing/{dispatcher,base,pipeline}.py`, `skyulf/core/schema.py`, +`skyulf/utils.py`, `skyulf/data/dataset.py` (yalnız ilgili input sınırı). +**Tüketir:** FrameSpec, ExecutionOptions, SparkEngine. +**Üretir:** FeatureEngineer'ın opt-in `frame_spec`/`execution_options` desteği; +ayrı X/y Spark frame'i almayan, tek frame'de target/key koruyan fit/transform yolu. + +- [ ] Repartition edilmiş frame'de key/target'ın aynı satırda kaldığı testi yaz. + Duplicate/null key, eksik kolon ve nested/Decimal unsupported hata testleri ekle. +- [ ] Spark input hazırlığını engine-keyed dispatcher mapping'e ekle; local + tuple ve wrapper dönüşlerini değiştirme. Spark destek preflight bütün adımları + kontrol etsin; ilk node çalışıp sonraki unsupported node'da geç kalınmasın. +- [ ] Default istatistik toplama Spark'ta count/NumPy conversion başlatmasın. + İstenen distributed aggregate metrics ayrı seçilir; local RSS cluster belleği + gibi raporlanmaz. Satır sayısı bilinmiyorsa unknown kalır. +- [ ] Feature listesi key/target'ı dışlasın. Kolon adlarında nokta/backtick için + doğru quoting ve collision testleri yaz; uydurma internal key ekleme. + +```python +def test_frame_spec_rejects_duplicate_key_names(): + """Ambiguous key declarations must fail before Spark starts work.""" + import pytest + from skyulf.core.execution import FrameSpec + with pytest.raises(ValueError, match="row_keys"): + FrameSpec(row_keys=("event_id", "event_id")) +``` + +**Komut:** `python -m pytest skyulf-core/tests/spark/test_frame_contract.py -q` +**Kabul:** Identical keys/targets sonrası dönüşüm; preflight hatasında action yok; +local FeatureEngineer regression testleri geçer. + +## SM-04 — Versioned küçük state codec'i + +**Bağımlılık:** SM-03. **Oluştur:** `skyulf/core/portable_state.py`, +`tests/spark/test_portable_state.py`. **Değiştir:** +`skyulf/core/artifacts.py`, `skyulf/pipeline/seal.py` (gereken ortak canonicalization). +**Üretir:** `encode_state(node_type, params, *, max_bytes) -> bytes` ve +`decode_state(payload: bytes) -> tuple[str, dict]`; envelope v1. + +- [ ] StandardScaler ve SimpleImputer mevcut artifact dict fixture'larını + lossless round-trip test et; boş state/no-op davranışını ayrı kapsa. +- [ ] NaN/Infinity, integer/string kategori değerleri ve ordered_columns için + tagged representation; semantic hash'te repr/pickle fallback olmaması testi yaz. +- [ ] Bozuk payload, bilinmeyen version/node, duplicate columns ve aşırı büyük + payload'ı decode/worker yüklemesinden önce reddet. +- [ ] Eski pipeline pickle save/load testlerini değiştirmeden geçir. Bu codec + generic Python object serializer değildir; estimator nesnesi kabul etmez. + +```python +def test_state_rejects_future_version(): + """A newer artifact must not silently acquire older transformation semantics.""" + import pytest + from skyulf.core.portable_state import decode_state + with pytest.raises(ValueError, match="version"): + decode_state(b'{"format_version":999}') +``` + +**Komut:** `python -m pytest skyulf-core/tests/spark/test_portable_state.py -q` +**Kabul:** Round-trip değer/kolon sırası; limit/version reddi; eski persistence korunur. + +## SM-05 — SimpleImputer native Spark + +**Bağımlılık:** SM-04. **Değiştir:** `skyulf/preprocessing/imputation/simple.py`, +`skyulf/preprocessing/_spark.py`, capability kayıtları. +**Oluştur:** `tests/spark/test_simple_imputer.py`. +**Tüketir/üretir:** Mevcut SimpleImputer artifact anahtarları; mean/constant +Spark fit ve apply. Median/most_frequent Spark fit bu görevde unsupported kalır. + +- [ ] Local ve Spark mean/constant fixture'ları: train/test dağılımları farklı, + null/NaN, tamamen boş kolon, boş seçim ve geçersiz tip; öğrenme yalnız train'den. +- [ ] Mean fit için seçilen kolonlarda bounded aggregate; constant için veri + istatistiği gerekmiyorsa action yok. Missing counts gerekiyorsa aynı aggregate'e + birleştir. Mevcut local boş kolon politikasını baseline'dan aynen koru. +- [ ] Apply yalnız Spark expressions kullansın; keys/target'a dokunmasın. + Capability stratejiye göre karar versin; median'ı mean'e dönüştürme. +- [ ] Apply planında Python UDF olmadığını, row/key setinin korunduğunu doğrula. + +```python +def test_spark_mean_uses_only_training_data(spark): + """Held-out values must not influence the learned replacement value.""" + from skyulf.preprocessing.imputation.simple import SimpleImputerCalculator, SimpleImputerApplier + train = spark.createDataFrame([(1.0,), (None,), (3.0,)], "x double") + held_out = spark.createDataFrame([(1, 100.0), (2, None)], "id long, x double") + state = SimpleImputerCalculator().fit(train, {"columns": ["x"], "strategy": "mean"}) + output = SimpleImputerApplier().apply(held_out, state).orderBy("id").collect() + assert [row.x for row in output] == [100.0, 2.0] +``` + +Bu küçük node testi yanında key/target validation ve üç-engine parity +FeatureEngineer girişinden de test edilir. +**Komut:** `python -m pytest skyulf-core/tests/spark/test_simple_imputer.py -q` +**Kabul:** Üç engine'de aynı fill state ve key'le eşleşen sonuç; ham collect yok. + +## SM-06 — StandardScaler native Spark + +**Bağımlılık:** SM-05. **Değiştir:** `skyulf/preprocessing/scaling/standard.py`, +`skyulf/preprocessing/_spark.py`, capability kayıtları. +**Oluştur:** `tests/spark/test_standard_scaler.py`. +**Tüketir/üretir:** Mevcut mean/var/scale/columns/with_mean/with_std artifact'i. + +- [ ] Dört with_mean/with_std kombinasyonu, sabit kolon, null/NaN, boş veri, + tek satır, büyük offset/küçük varyans ve kolon sırası için parity testleri yaz. +- [ ] Dağıtık population variance ile ddof=0 semantiğini koru. NaN'ın aggregate + davranışını local node'la eşleştir. Spark ML StandardScaler'ı aynı isim diye + doğrudan kullanma. O(kolon) sonuç topla; stabil varyans kullan. +- [ ] Apply `(x - mean) / scale` ifadelerini flag'lere göre kur; sıfır scale + ve gerekli olmayan None state'i mevcut node davranışına göre ele al. +- [ ] Floating tolerance küçük normal fixture'da rtol=1e-10/atol=1e-12; + adversarial sayısal fixture'da gerekçeli ayrı tolerance, sonuç farkını gizleme. + +```python +def test_spark_scaler_uses_population_variance(spark): + """Sample variance would change every nonconstant scaled prediction.""" + import pytest + from skyulf.preprocessing.scaling.standard import StandardScalerCalculator, StandardScalerApplier + frame = spark.createDataFrame([(1, 1.0), (2, 3.0)], "id long, x double") + state = StandardScalerCalculator().fit(frame, {"columns": ["x"]}) + output = StandardScalerApplier().apply(frame, state).orderBy("id").collect() + assert state["var"] == pytest.approx([1.0]) + assert [row.x for row in output] == pytest.approx([-1.0, 1.0]) +``` + +Bu assertion'lar her engine ve çapraz state yoluna genişletilir; flag ve +adversarial numeric fixture'lar ayrıca uygulanır. +**Komut:** `python -m pytest skyulf-core/tests/spark/test_standard_scaler.py -q` +**Kabul:** Population variance semantiği ve flag/NaN parity; native apply planı. + +## SM-07 — İlk uçtan uca FE ve compatibility kapısı + +**Bağımlılık:** SM-06. **Oluştur:** `tests/spark/test_feature_pipeline.py`, +`skyulf-core/examples/spark_feature_engineering.py`. +**Değiştir:** `skyulf/preprocessing/pipeline.py`, +`skyulf/pipeline/_pipeline.py` yalnız public integration için gerekirse. +**Üretir:** Kolon seçimi + mean imputer + scaler; state export/import ile +yerel/Spark fit ve apply. Model training burada Spark-native ilan edilmez. +Public state API'si `FeatureEngineer.export_state() -> bytes` ve +`FeatureEngineer.from_state(payload, *, frame_spec=None, execution_options=None)` +olarak eklenir. Ordered step config + codec payload dizisi saklanır; keys ve +runtime tercihi yeni çağrıdan alınır, SparkSession kaydedilmez. + +- [ ] Frame projection ile key/target/feature listesini oluştur; yeni bir node + tipi gereksizse sırf demo için registry node'u ekleme. +- [ ] Her destekli node için pandas/Polars/Spark fit × üç apply engine'i test et; + sıralı output yerine key join ile karşılaştır. State kaydet/yüklemeyi araya koy. +- [ ] Repartition(1/2/7), ters girdi sırası ve ikinci transform çağrısında + öğrenilmiş state'in değişmemesini doğrula. +- [ ] Baseline local pipeline ve leakage suite'leri + Spark suite çalıştır. + Büyük veri testinde input collect yasak, sadece bounded aggregate izinli; + terminal test collect'i sınırlı fixture için ayrı işaretlenir. + +```python +def test_feature_state_applies_after_repartition(spark, fitted_feature_engineer): + """Saved state must preserve keyed features across partition boundaries.""" + import pytest + from skyulf.core.execution import FrameSpec, ExecutionOptions + from skyulf.preprocessing.pipeline import FeatureEngineer + restored = FeatureEngineer.from_state(fitted_feature_engineer.export_state(), + frame_spec=FrameSpec(row_keys=("id",)), + execution_options=ExecutionOptions(engine="spark")) + frame = spark.createDataFrame([("a", 1.0), ("b", 3.0)], "id string, x double") + first = {r.id: r.x for r in restored.transform(frame.repartition(1)).collect()} + second = {r.id: r.x for r in restored.transform(frame.repartition(7)).collect()} + assert first == pytest.approx({"a": -1.0, "b": 1.0}) + assert second == pytest.approx(first) +``` + +`fitted_feature_engineer` fixture'ı x=[1,3] eğitim verisinde gerçek mean imputer +ve scaler fit eder; bu görevde conftest'e eklenir. Aynı key karşılaştırması +pandas/Polars fit edilmiş state için de uygulanır. +**Komut:** `python -m pytest skyulf-core/tests/spark -q` +**Kabul:** G1: çalışan native FE, taşınabilir küçük state, local regresyon yok. +Sonraki dilim [inference](02-inference-plan.md); henüz endpoint veya template yok. diff --git a/initiatives/spark_and_mlflow/02-inference-plan.md b/initiatives/spark_and_mlflow/02-inference-plan.md new file mode 100644 index 000000000..aa0554b2a --- /dev/null +++ b/initiatives/spark_and_mlflow/02-inference-plan.md @@ -0,0 +1,184 @@ +# Distributed Python Inference Implementation Plan + +> **For agentic workers:** Use `executing-plans`; finish SM-07 and read +> [ARCHITECTURE.md](ARCHITECTURE.md) before executing these tasks. + +**Goal:** Native Spark FE + Python model ve uyumlu Python FE + model yolları. +**Architecture:** Aynı model bundle iki giriş aşamasını açıkça ayırır. Spark +veriyi dağıtır; Python modeli iterator batch'lerinde tahmin üretir. +**Tech Stack:** PySpark DataFrame/Arrow, pandas/NumPy, mevcut sklearn modelleri. +**Spec:** [ARCHITECTURE.md](ARCHITECTURE.md). + +## Global constraints + +- Model eğitimi mevcut local API'dedir; burada distributed training sözü yok. +- Worker'da SparkSession, credentials, tracking mutation veya tablo yazma yok. +- Sıra yerine row_keys; retry-safe saf tahmin; context-dependent pipeline erken ret. +- Core dependency yükü ve legacy artifact davranışı korunur; paketler versioned. +- Bütün yeni source/test yolları aşağıda `skyulf-core/` köküne göredir. + +## SM-08 — Ortak inference bundle + +**Bağımlılık:** SM-07. **Oluştur:** `skyulf/inference/__init__.py`, +`skyulf/inference/bundle.py`, `tests/spark/test_inference_bundle.py`. +**İncele/değiştir:** `skyulf/pipeline/_pipeline.py`, `skyulf/core/serialization.py`; +backend legacy artifact okuyucusuna bu görevde yeni format dayatma. +**Üretir:** + +```text +build_bundle(pipeline, *, input_stage, feature_order) -> InferenceBundle +save_bundle(bundle, path) -> None +load_bundle(path) -> InferenceBundle +predict_local(frame, bundle) -> pandas.DataFrame +``` + +`InferenceBundle`: format_version, input_stage(raw|features), feature_order, +input/output schema, FE state, estimator payload, classes/positive label, +threshold provenance, package/runtime requirements ve semantic digest. +`probability_columns` sınıf sırasıyla eşleşen ordered tuple alanıdır; +regression için boş tuple'dır. +`predict_local` sonucu regression için `prediction`; classification için +`prediction` ve sınıf sırası manifestte tanımlı probability kolonlarıdır. + +- [ ] Mevcut pipeline'dan bundle oluştur; raw ve features girişlerini ayrı + fixtures ile kaydet/yükle. `features` modunda scaler ikinci kez uygulanmamalı. +- [ ] İsim doğru ama kolon sırası farklı, eksik/ekstra kolon, dtype uyuşmazlığı, + bilinmeyen version ve model boyut sınırı için failure testleri yaz. +- [ ] Model payload ile manifest checksum'ını doğrula; dependency manifesti + credentials ve session taşımasın. Pickle tabanlı payload yalnız güvenilir + kaynaklardan yüklenir; manifest checksum'ı güvenilirlik kanıtı değildir. +- [ ] Eski standalone ve backend artifact formatları için explicit adapter + tasarla; ilk bundle yalnız doğrulanmış standalone girdiyi kabul etsin. + Legacy backend adapter SM-18'de mevcut threshold/label davranışıyla test edilir. + +```python +def test_bundle_round_trip_predictions(fitted_regression_pipeline, tmp_path, raw_frame): + """Packaging must preserve the prediction function, including preprocessing.""" + import numpy as np + from skyulf.inference.bundle import build_bundle, save_bundle, load_bundle, predict_local + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x",)) + before = predict_local(raw_frame, bundle)["prediction"] + save_bundle(bundle, tmp_path / "model") + after = predict_local(raw_frame, load_bundle(tmp_path / "model"))["prediction"] + np.testing.assert_allclose(after, before, rtol=1e-10, atol=1e-12) +``` + +Fixture'lar bu görevde `tests/spark/conftest.py` içine eklenir: `raw_frame` +id/x kolonları ve farklı scale içeren küçük pandas verisi; +`fitted_regression_pipeline` imputer + scaler + mevcut linear regression ile +local fit edilmiş gerçek SkyulfPipeline. Veri üretimi seed=17 ve held-out +satırlarla sabitlenir; mock estimator bu testin yerine geçmez. +**Komut:** `python -m pytest skyulf-core/tests/spark/test_inference_bundle.py -q` +**Kabul:** Kayıt/yükleme, feature sırası ve raw/features giriş ayrımı doğrulanmış. + +## SM-09 — Native Spark FE ardından Python model + +**Bağımlılık:** SM-08. **Oluştur:** `skyulf/inference/spark.py`, +`tests/spark/test_native_features_inference.py`. +**Üretir:** `predict_spark(frame, bundle, *, frame_spec, options, mode)`; +`mode="native_features"` ham girdiye önce native FE uygular, worker'a yalnız +model feature'ları + keys gönderir. Sonuç Spark DataFrame'dir. + +- [ ] Gerçek Spark action ve key-based karşılaştırma testi yaz. Model training + local fixture'da açıkça yapılsın; Spark fit çağrısı veya gizli conversion olmasın. +- [ ] Native FE'yi G1 yoluyla çalıştır; Python modelini mapInPandas iterator + başına bir kez yükle. Output schema önceden bundle'dan gelsin; key dtype korunsun. +- [ ] Feature order ve input_stage doğrulamasını driver'da yap. Geniş kolonları + gereksiz yere worker'a gönderme; session/connection closure capture etme. +- [ ] Repartition ve Arrow batch boyutu değişince aynı key için aynı tahmini, + boş partition ve boş dataframe'de doğru boş schema'yı doğrula. + +```python +def test_native_path_matches_local(spark, raw_frame, regression_bundle): + """Partitioning must not change a row-independent model's predictions.""" + import numpy as np + from skyulf.core.execution import FrameSpec, ExecutionOptions + from skyulf.inference.bundle import predict_local + from skyulf.inference.spark import predict_spark + frame = spark.createDataFrame(raw_frame).repartition(3) + actual = predict_spark(frame, regression_bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions(engine="spark", python_batch_rows=2), + mode="native_features").toPandas().sort_values("id") + expected = predict_local(raw_frame.sort_values("id"), regression_bundle) + np.testing.assert_allclose(actual["prediction"], expected["prediction"], rtol=1e-10) +``` + +`regression_bundle`, SM-08 pipeline'ından `build_bundle` ile üretilen fixture'dır. +Testteki toPandas yalnız küçük test sonucunu karşılaştırmak içindir; üretim +inference yolunda driver collection olmaması ayrıca denetlenir. +**Komut:** `python -m pytest skyulf-core/tests/spark/test_native_features_inference.py -q` +**Kabul:** G2a: Spark FE native, model dağıtık Python; FE bir kez uygulanır. + +## SM-10 — Worker'da Python FE + model + +**Bağımlılık:** SM-09. **Değiştir:** `skyulf/inference/spark.py`, bundle +capability preflight. **Oluştur:** `tests/spark/test_python_pipeline_inference.py`. +**Üretir:** Aynı fonksiyonda `mode="python_pipeline"`; sadece batch-independent +ve row-preserving fit edilmiş pipeline desteği. + +- [ ] Imputer/scaler modelinin SM-09 ile aynı tahmini verdiğini test et. + pandas/Polars training kaynağı farklı bundle'lar kullan. +- [ ] Rolling/lag, batch'ten yeniden group statistics hesaplayan custom step, + row drop ve resampling pipeline'larını action'dan önce reddet. +- [ ] FeatureEngineering fit worker'da çağrılmasın; yalnız frozen apply/predict. + Model/FE state mutation testi ve iki ardışık action sonucu kontrolü ekle. +- [ ] Custom step yalnız package import yolu + capability beyanı ile kabul + edilsin; bilinmeyen callable otomatik batch-safe sayılmasın. + +```python +def test_python_pipeline_rejects_window_context(spark, rolling_bundle): + """A rolling window must not reset invisibly at Arrow batch boundaries.""" + import pytest + from skyulf.core.execution import FrameSpec, ExecutionOptions + from skyulf.core.capabilities import UnsupportedExecutionError + from skyulf.inference.spark import predict_spark + with pytest.raises(UnsupportedExecutionError, match="context"): + predict_spark(spark.range(6), rolling_bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions(engine="spark"), mode="python_pipeline") +``` + +`rolling_bundle` fixture'ı mevcut rolling node ile fit edilmiş, window context +metadata'sı taşıyan geçerli bundle'dır; bozuk manifest ile ret üretme. +**Komut:** `python -m pytest skyulf-core/tests/spark/test_python_pipeline_inference.py -q` +**Kabul:** G2b: iki inference yolunda parity; temporal karşı örnek sessizce çalışmaz. + +## SM-11 — Classification ve dağıtık yürütme kapısı + +**Bağımlılık:** SM-10. **Oluştur:** `tests/spark/test_prediction_contract.py`, +`tests/spark/test_worker_isolation.py`, +`skyulf-core/examples/spark_batch_inference.py` (repo köküne göre). +**Değiştir:** Bundle/prediction output contract yalnız mevcut model semantiğiyle. + +- [ ] String binary labels, çok sınıf, positive label, probability sütun sırası, + saved threshold ve override precedence için local/Spark key parity testleri. +- [ ] Spark'ın lazy olması nedeniyle assertion'lar action çağırmalı. İki + repartition ve en az iki Arrow batch limitinde aynı tahmini doğrula. +- [ ] Worker'ın wheel'i kullanması ve eksik dependency'nin anlaşılır hatası için + ayrı-process testi ekle. Model her satır için yüklenmesin; iterator seviyesinde + yükleme helper'ını ölç. Task sayısına eşit tam bir global yükleme sayısı varsayma. +- [ ] Büyük sentetik veri üzerinde driver RSS, worker peak ve wall time ölç; + row count/feature width/partition sayısını kaydet. Driver belleğinin input + boyutuyla doğrusal büyümemesini araştır; sabit hızlanma oranı vaat etme. +- [ ] Güncel core suite ve optional-dependency import testini çalıştır; + bilinen failure varsa neden/izolasyon kanıtıyla release kararına yaz. + +```python +def test_probability_columns_follow_class_manifest(classification_bundle, raw_frame): + """A class-order mismatch would silently reverse business decisions.""" + import numpy as np + from skyulf.inference.bundle import predict_local + output = predict_local(raw_frame, classification_bundle) + columns = classification_bundle.probability_columns + assert list(output[columns].columns) == list(columns) + np.testing.assert_allclose(output[columns].sum(axis=1), 1.0, atol=1e-7) +``` + +Classification fixture SM-08 fixture'larına eklenir; manifest class sırası +estimator.classes_ ile karşılaştırılır. Sum testi tek başına yeterli değildir: +Spark probability değerleri local estimator.predict_proba ile sınıf bazında +karşılaştırılır; threshold label sonucu ayrıca assertion alır. +**Komut:** `python -m pytest skyulf-core/tests/spark -q` +**Kabul:** G2: iki yol, regression/classification ve worker packaging kanıtlı. +Endpoint yok; [MLflow/batch](03-mlflow-batch-delivery-plan.md) aşamasına geçilir. diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md new file mode 100644 index 000000000..2fe114134 --- /dev/null +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -0,0 +1,300 @@ +# MLflow, Batch ve Son Teslimatlar Implementation Plan + +> **For agentic workers:** Use `executing-plans`. Read +> [ARCHITECTURE.md](ARCHITECTURE.md) and [OPEN_QUEUE.md](OPEN_QUEUE.md). +> SM-18–SM-20 start only after the core and platform gates. + +**Goal:** Opsiyonel tracking/registry, aylık tablo çıktısı ve son aşamada ürünleştirme. +**Architecture:** Core sözleşmeleri platform I/O'dan ayrılır. MLflow pyfunc, +SM-08 bundle'ını yükler; Databricks runner aynı inference girişini kullanır. +**Tech Stack:** MLflow, Unity Catalog, Spark/Delta, Databricks Jobs; en son DAB. +**Spec:** [ARCHITECTURE.md](ARCHITECTURE.md). + +## Global constraints + +- Tracking ve registry kapalıyken core çalışır; implicit autolog/global callback yok. +- Tracking URI ve registry URI ayrı; local ortamda UC erişimi de mümkündür. +- Her run başlangıcında alias concrete version'a çözülür; batch boyunca değişmez. +- Kimlik doğrulama ortam/profile/secret provider üzerinden; artifact/config içine token yok. +- Endpoint ve template için önce çalışan runner; template iş mantığı içermez. +- Yeni source/test yolları `skyulf-core/` köküne göre; platform kaynakları repo köküne göre. + +## SM-12 — Açık kapsamlı opsiyonel MLflow tracking + +**Bağımlılık:** SM-11. **Oluştur:** +`skyulf/integrations/__init__.py`, `skyulf/integrations/mlflow/__init__.py`, +`skyulf/integrations/mlflow/tracking.py`, `tests/integrations/test_mlflow_tracking.py`. +**Değiştir:** `skyulf-core/setup.py` ve mevcut requirements eşleri (repo köküne göre). +**Üretir:** `TrackingConfig(enabled=False, tracking_uri=None, experiment_name=None, +failure_policy="raise")`; `track_run(config, *, run_name)` context manager. +Yield edilen run nesnesi `log_metrics`, `log_params`, `set_tags` sunar; +disabled durumda aynı arayüzle no-op ve network/import yok. + +- [ ] MLflow kurulu olmayan base ortamda import ve disabled eğitim testi yaz. +- [ ] URI/experiment seçimi açık client/run_id kapsamına bağlı olsun; eşzamanlı + iki çalışmanın run id'si karışmasın. Kullanıcının aktif run'ını sessizce kapatma. +- [ ] Exception'da run FAILED; başarıda FINISHED. Varsayılan `raise`; opt-in + `warn` durumunda model sonucu korunur ve tracking kaybı sonuç metadata'sında görünür. +- [ ] Explicit param/metric log; params limitinde tam config artifact + digest; + veri satırları ve secret içerebilen bütün config otomatik loglanmaz. + +```python +def test_disabled_tracking_never_constructs_client(monkeypatch): + """Local training must remain independent of the tracking service.""" + from skyulf.integrations.mlflow import tracking + def forbidden(*args, **kwargs): + raise AssertionError("MLflow client was constructed") + monkeypatch.setattr(tracking, "_make_client", forbidden) + with tracking.track_run(tracking.TrackingConfig(), run_name="offline") as run: + run.log_metrics({"rmse": 0.5}) + assert run.enabled is False +``` + +`_make_client` bu görevde lazy client fabrikası olarak oluşturulur. +**Komut:** `python -m pytest skyulf-core/tests/integrations/test_mlflow_tracking.py -q` +**Kabul:** Base dependency isolation; local geçici tracking store'da gerçek run lifecycle. + +## SM-13 — MLflow model flavor ve bağımsız yükleme + +**Bağımlılık:** SM-12. **Oluştur:** `skyulf/integrations/mlflow/model.py`, +`tests/integrations/test_mlflow_model.py`. +**Üretir:** `log_model(bundle, *, run_id, artifact_path) -> model_uri`; +`SkyulfPythonModel` pyfunc adapter; `load_context` bundle yükler, +`predict` SM-08 `predict_local` kullanır. + +- [ ] pyfunc save/load sonrası raw/features giriş sözleşmesi, class/threshold, + dtype ve feature order parity testi yaz. NumPy positional girdiye sessiz uyarlama yok. +- [ ] Signature/input example oluştur; küçük sentetik örnek kullan, üretim + verisini model example içine otomatik koyma. Wheel sürümü ve requirements kayıtlı. +- [ ] Model loglama açık run_id kullanır; track_run'ın run nesnesi bu kimliği + sunar. Süreç genelindeki active run durumuna dayanarak başka işe artifact yazma. +- [ ] Temiz subprocess/venv'de modeli yükle; çalışma dizinindeki repo importuna + güvenmediğini doğrula. Notebook closure veya SparkSession pickle etme. +- [ ] G2 runner ile registry URI'den indirilen aynı bundle'ı çalıştır. MLflow + spark_udf kullanılırsa adapter yine aynı prediction sözleşmesini uygulasın; + ikinci ayrı preprocessing implementation yazma. + +```python +def test_pyfunc_matches_bundle(logged_pyfunc, regression_bundle, raw_frame): + """MLflow packaging must not alter the established local prediction semantics.""" + import numpy as np + from skyulf.inference.bundle import predict_local + expected = predict_local(raw_frame, regression_bundle)["prediction"] + actual = logged_pyfunc.predict(raw_frame)["prediction"] + np.testing.assert_allclose(actual, expected, rtol=1e-10, atol=1e-12) +``` + +`logged_pyfunc` fixture geçici local MLflow store'da log_model + load_model yapar. +**Komut:** `python -m pytest skyulf-core/tests/integrations/test_mlflow_model.py -q` +**Kabul:** G3a: MLflow artifact bağımsız Python ortamında doğru tahmin verir. + +## SM-14 — Registry ve Unity Catalog adapter'ı + +**Bağımlılık:** SM-13. **Oluştur:** `skyulf/integrations/mlflow/registry.py`, +`tests/integrations/test_mlflow_registry.py`. +**İncele:** `skyulf/core/model_registry.py`; in-memory object-ref arayüzünü remote +URI çözümleme ile eşdeğer sayma, eski metotların return tipi değişmesin. +**Üretir:** `resolve_model(name, *, alias=None, version=None) -> ResolvedModel`; +ResolvedModel(name, version, model_uri, signature, digest). +`register_model(model_uri, name)` explicit publish işlemidir; tahmin sırasında çağrılmaz. + +- [ ] Alias/version aynı anda verilirse ve ikisi de yoksa açık config hatası; + missing model/permission failure ile dependency failure ayrı hatalar olsun. +- [ ] Alias'ı bir kez resolve et, concrete version URI'yi bütün iş boyunca taşı. + İlk local registry store testleri, sonra UC integration fixture'ı. +- [ ] UC için üç parçalı model ismi, signature ve ayrı registry URI doğrula; + local client'tan erişim de test senaryosuna dahil olsun. +- [ ] Alias değiştirme otomatik başarı yan etkisi olmasın; model kaydı ve + promotion ayrı explicit operasyonlar olsun. Testten sonra yalnız test-owned + kaynaklar temizlenir; var olan alias değiştirilmez. + +```python +def test_registry_rejects_ambiguous_reference(): + """A run must have exactly one model selection rule before resolving it.""" + import pytest + from skyulf.integrations.mlflow.registry import resolve_model + with pytest.raises(ValueError, match="alias.*version"): + resolve_model("catalog.schema.model", alias="champion", version="3") +``` + +**Komut:** `python -m pytest skyulf-core/tests/integrations/test_mlflow_registry.py -q` +**Kabul:** G3b: local registry gerçek test; UC smoke için SM-16 platform kanıtı gerekir. + +## SM-15 — Aylık batch ve Delta yayınlama + +**Bağımlılık:** SM-14. **Oluştur:** +`skyulf/integrations/databricks/{__init__,batch,delta}.py`, +`tests/integrations/test_batch_contract.py`, `tests/integrations/test_delta_publish.py`. +**Üretir:** `BatchSpec(period_start, period_end, as_of, row_keys, output_table, +model_name, model_version, publish_mode="replace_period")`; +`run_batch(spark, spec, *, source, bundle, options) -> BatchResult`. + +- [ ] UTC yarı açık `[start,end)` dönem, business timezone dönüşümü ve explicit + `as_of` doğrulansın. Scheduler saati otomatik data cutoff sayılmasın. +- [ ] Kaynak tablo sürümü/snapshot, concrete model version, code wheel sürümü, + input/output counts ve run_id manifestte kaydedilsin. `as_of` point-in-time + veri yoksa tarihsel doğruluk garantisi vermez; job açıklayıcı hata üretir. +- [ ] İlk sink `replace_period`: yalnız hedef dönem için atomic Delta replace; + boş sonuçta dönem silme explicit `allow_empty=True` gerektirir. Nonmatching + period satırları yazma öncesi reddedilir. Dönem dışı satır korunur. +- [ ] Aynı logical run retry mükerrer satır oluşturmasın. Aynı döneme eşzamanlı + farklı run için tek-writer admission + Delta conflict handling gerekir; + conflict sessiz last-writer-wins olmaz. Sonuç başarılı ancak commit sonrası. +- [ ] Append ve key MERGE ilk release'te unsupported; sonraki genişletmede + merge key `(row_keys, period, model_version)` veya business overwrite politikası + explicit seçilir. Backfill geçmiş model/current model seçimini zorunlu alır. + +```python +def test_retry_preserves_other_periods(delta_batch_harness): + """Rerunning one month must neither duplicate it nor erase another month.""" + h = delta_batch_harness + h.seed_previous_period() + first = h.run_current_period() + second = h.run_current_period() + assert h.current_keys_are_unique() + assert first.output_count == second.output_count + assert h.previous_period_matches_seed() +``` + +`delta_batch_harness` bu görevde geçici Delta tablolarına gerçek read/write yapan +fixture'dır; mock sink testin yerine geçmez. Yetkisiz/çakışan publish ayrıca test edilir. +**Komut:** `python -m pytest skyulf-core/tests/integrations/test_batch_contract.py skyulf-core/tests/integrations/test_delta_publish.py -q` +**Kabul:** G4 local/uyumlu Delta ortamında dönem izolasyonu, retry ve conflict kanıtı. + +## SM-16 — Gerçek Databricks doğrulaması + +**Bağımlılık:** SM-15. **Oluştur:** `skyulf-core/examples/databricks_batch_smoke.py`, +`initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md` (uygulama sırasında). +**Üretir:** Bir wheel ile gerçek FE → registry load → Spark inference → test Delta table. + +- [ ] Kullanılan DBR/Python/Spark/MLflow/Arrow, compute türü, izinli catalog/schema + ve test resource isimlerini kaydet. Workspace bilgisi yoksa yalnız bu görev WAIT + olur; local testler Databricks geçti sayılmaz. +- [ ] Wheel'i build et; temiz job ortamında kur. DBR'ın Spark'ını körlemesine + pip extra ile değiştirme. OSS Spark, DBR ve Connect ayrı dependency profilleri. +- [ ] Native FE ve Python pipeline yollarını aynı küçük gold dataset ile + karşılaştır; büyük sentetik dataset'te bellek/runtime ölç. UC alias pinning + ve monthly retry testini test catalog'unda çalıştır. +- [ ] İlk doğrulama job/script ile; DAB template üretme. Serverless/Connect ancak + ayrıca test edilirse supported ilan edilir; classic başarılarını genelleme. + +```python +def test_platform_evidence_has_concrete_versions(platform_evidence): + """A successful job without runtime and model identity is not reproducible.""" + assert platform_evidence["model_version"] + assert platform_evidence["wheel_version"] + assert platform_evidence["input_snapshot"] + assert platform_evidence["job_run_id"] + assert platform_evidence["prediction_parity_passed"] is True +``` + +Bu kontrol gerçek job çıktısına uygulanır; elle doldurulmuş dict platform testi değildir. +**Kabul:** G4 platform kapısı: run URL/id, sürümler, parity ve tekrar yazma kanıtı. + +## SM-17 — Kalan node aileleri ve context desteği + +**Bağımlılık:** SM-16. **Kaynak:** rapordaki aile matrisi; +`skyulf/preprocessing/{encoding,feature_selection,vectorization,transformations}` +ve diğer ailelerin mevcut modülleri; capability tablosu. +**Oluştur:** `NODE_SUPPORT.md`, `tests/spark/test_node_support_matrix.py`; +her kabul edilen aile için `tests/spark/test__parity.py`. + +- [ ] İlk genişletme: column/cast/date/arithmetic, minmax/maxabs ve selection apply. + Fit local-only olsa da seçilmiş kolonları Spark apply destekleyebilir. +- [ ] İkinci genişletme: median/quantile ve kategorik encode. Exact/approximate + algoritma ayrı config; category order, unseen/null, büyük state tablo lookup + ve hash algoritması korunmadan native etiketi verme. +- [ ] Üçüncü: group fitted lookup, rolling/lag ve custom FE. Group/order/tie-break, + history cutoff, geçmiş veri erişimi ve partition boundary testleri zorunlu. +- [ ] Dördüncü: OOF target/WOE. Her fold'da train-only fit ve out-of-fold train + representation testleri. Dataset split/hash kuralı engine değişince değişmesin. +- [ ] SMOTE, yüksek boyutlu vectorizer/embedding, SHAP/CV/tuning ve native model + training için native/explicit bounded local/unsupported kararlarını kaydet. + Bağımsız algoritma portları aile bazlı ayrı testli alt görevler olur; SM-17 + bütün node'ların desteklendiği iddiasıyla kapatılamaz. + +```python +def test_declared_support_has_evidence(support_matrix): + """An advertised engine-operation pair must point to a passing parity case.""" + for entry in support_matrix: + if entry["status"] == "supported": + assert entry["fit_test"] or entry["operation"] == "apply" + assert entry["apply_test"] or entry["operation"] == "fit" + assert entry["runtime_evidence"] +``` + +`support_matrix` fixture registry/capability anahtarlarını NODE_SUPPORT ile +eşleştirir; eski tarihli test yolu tek başına evidence değildir. Her alt aile +uygulanmadan exact dosya/test/API dilimine ayrılır; unsupported aileler kullanıcıya +açıkça gösterilir. İlk release için tüm ailelerin native olması şart değildir. +**Kabul:** G5: ilan edilen support matrix gerçek testlerle tutarlı, diğerleri açık ret. + +## SM-18 — Backend/Canvas ve custom feature kullanımı + +**Bağımlılık:** SM-17. **Mevcut:** +`backend/ml_pipeline/_execution/engine/{__init__,_feature_eng,_artifacts,_node_runners}.py`, +`backend/deployment/service.py`, +`frontend/ml-canvas/src/core/registry/init.ts`, +`frontend/ml-canvas/src/core/utils/pipelineConverter.ts`. +**Oluştur:** `tests/integration/test_spark_pipeline_capabilities.py`; +ilgili frontend registry/config testleri. + +- [ ] Core capability'yi API metadata'sına aktar; UI desteklenmeyen node/engine + bağlantısını neden göstererek engellesin. Backend aynı kontrolü bağımsız yapsın. +- [ ] Core sequential pipeline ile Canvas DAG ayrı: branch merge key/cardinality, + intermediate artifact policy ve executor lifecycle için entegrasyon testi yaz. + Bütün ara Spark frame'lerini joblib'e koyma; lineage/ref ve bounded preview kullan. +- [ ] Legacy backend model+feature_engineer artifact adapter'ını threshold/label + testleriyle ekle. Eski deployment davranışı değişmesin. +- [ ] Config-driven FE ve paketlenmiş custom module referansını destekle; + generated config/editable Python ayrımı anlaşılır olsun. Arbitrary kod sandbox'ı + veya kod editörü bu görevin gereği değildir. + +**Örnek assertion:** API'ye unsupported Spark node gönderildiğinde 4xx + +node/operation/reason alınır ve job submission çağrısı yapılmaz; frontend aynı +node için disabled nedeni gösterir. Bunlar backend integration ve UI testlerinde +gerçek request/render ile doğrulanır. +**Kabul:** G6: SDK/Canvas supported yollar tutarlı; ilgili pytest, tsc/vitest/lint +ve `npm run build` kanıtı kayıtlı. + +## SM-19 — En son inference erişim biçimleri + +**Bağımlılık:** SM-18. **Oluştur:** +`skyulf-core/examples/serving_prediction.py`, +`skyulf-core/examples/sql_batch_prediction.sql` (repo köküne göre). +**Mevcut:** `backend/deployment/service.py`, bundle/MLflow model adapter'ları. + +- [ ] Önce HTTP serving: tek satır/microbatch schema, label/proba/threshold, + local model ile parity ve dependencies ortamını doğrula. Serving'de SparkSession + var sayma; context gerektiren model history olmadan kabul edilmez. +- [ ] Sonra SQL ai_query: uygun endpoint/signature ile tablodan çağrı; hata + davranışı, maliyet/rate limit ve batch'e uygunluk hedef platformda test edilir. + ai_query ayrı eğitim engine'i veya zorunlu yeni endpoint değildir. +- [ ] Streaming isteğe bağlı alt teslimat: checkpoint, watermark/state, retry, + model version değişimi ve sink idempotency tasarım/testi tamamlanmadan advertise etme. + +**Örnek assertion:** Aynı gold dataset için HTTP ve SQL sonucu, key + model version +üzerinden G2 batch sonucuyla eşleşir; missing feature 4xx/schema hatasıdır. +**Kabul:** G7: yalnız doğrulanmış erişim biçimleri supported; streaming ayrı durum. + +## SM-20 — Template ve Databricks Bundle + +**Bağımlılık:** SM-19. **Oluştur:** repo kökünde `templates/databricks/` ve +`tests/templates/test_databricks_template.py`; template dosyaları +`databricks.yml`, `resources/batch_job.yml`, `README.md`, `src/run_batch.py`. + +- [ ] Sorular: platform, FE engine, tracking, registry, batch/HTTP/SQL; birbirinden + bağımsız ve capability validation ile. Local + MLflow/UC geçerli; Databricks + + pandas/Polars küçük veri yolu geçerli. Unsupported kombinasyon açıklanır. +- [ ] Generated run_batch yalnız test edilmiş runner'ı çağırır; FE config ve + custom feature module açık düzenleme noktalarıdır. İş mantığı kopyalanmaz. +- [ ] Aylık schedule timezone, period/as_of parametreleri ve dev hedefi üret; + secret value üretme. Schedule ile backfill data period'ünü karıştırma. +- [ ] İki fixture üret: local+Polars+tracking off ve Databricks+Spark+MLflow/UC. + Config syntax, import smoke ve bundle validate çalıştır; kullanıcıya ait ortamda + deploy/run ayrıca gerçek smoke ve yetkilendirme sınırıyla yapılır. + +**Örnek assertion:** Generate → config load → runner preflight; engine seçimi +manifestte korunur, endpoint seçilmediyse endpoint resource üretilmez. +**Kabul:** G8: template çalışan core/runner'ları paketler; endpoint/batch seçimi +isteğe bağlı; gerçek deployment kanıtı config validation'dan ayrı yazılır. diff --git a/initiatives/spark_and_mlflow/ARCHITECTURE.md b/initiatives/spark_and_mlflow/ARCHITECTURE.md new file mode 100644 index 000000000..493979e2b --- /dev/null +++ b/initiatives/spark_and_mlflow/ARCHITECTURE.md @@ -0,0 +1,210 @@ +# Mimari ve kapsam sözleşmesi + +Durum: uygulama için önerilen tasarım, 2026-09-21. Yeni dosya ve API adları +bu belgede **planlanan** arayüzlerdir; mevcut destek beyanı değildir. + +## 1. Birbirinden bağımsız seçimler + +| Boyut | İlk destek hedefi | Kural | +| --- | --- | --- | +| Ortam | local, Databricks | Spark local testte de çalışabilir | +| FE engine | pandas, Polars, Spark | Veri tipinden çözümleme; açık tercihle çelişirse hata | +| Model eğitimi | mevcut local estimator'lar | Spark girdisi örtük olarak local'e çevrilmez | +| Inference | local Python, Spark üzerinde Python | Spark-native model eğitimi ayrı kapsam | +| Tracking | off, MLflow | Core importunda MLflow zorunlu değil | +| Registry | mevcut local yol, MLflow/UC | Tracking URI ile registry URI ayrı | +| Çalıştırma | ad hoc, zamanlanmış batch | Aylık çalıştırma engine değildir | +| Giriş biçimi | SDK/job; daha sonra HTTP/SQL | Endpoint son aşama | + +İleride wizard local için Polars, Databricks için Spark önerebilir; pandas ve +Databricks üzerinde küçük local veri seçimi açık kalır. Bu öneri mevcut SDK'nın +varsayılanını sessizce değiştirmez. `cloud` isimli bir engine eklenmez. + +## 2. Korunacak kurallar + +1. Calculator fit yalnız eğitim verisinden state öğrenir; Applier tekrar fit etmez. +2. Spark girdisi native işlemlerde Spark'ta kalır. Ham veri için örtük + `collect`, `toPandas`, `to_numpy`, driver iteration yok. +3. Küçük aggregate sonuçlarını driver'a almak mümkündür: scaler için O(kolon), + önceden belirlenmiş state boyutu sınırıyla. Bu, ham veri collect etmek değildir. +4. Engine'ler arası taşınabilirlik node ve operation bazındadır; zorunlu ortak + payda değildir. Spark'a özgü yetenek Spark-only olarak kalabilir. +5. Bilinmeyen veya desteklenmeyen engine/operation, action başlamadan reddedilir. +6. Mevcut local pipeline/save/load çağrıları korunur. Yeni state formatı opt-in + eklenir; eski pickle dosyaları otomatik yeniden yazılmaz. +7. Config bilinmeyen yeni anahtarları sessizce yutmaz. Yeni runtime config kendi + katı doğrulamasına sahiptir; eski node config'lerinin toplu daraltılması ayrı iş. +8. Core'da Databricks credentials, endpoint provisioning veya tablo yazma yan + etkisi olmaz. Harici I/O opsiyonel integration katmanında olur. +9. Dtype, kategori sırası, null/NaN, feature sırası, label/probability sırası ve + threshold metadata'sı model paketinin sözleşmesidir. +10. Spark performans iddiası için gerçek action, plan ve bellek ölçümü gerekir; + lazy frame oluşturmak başarılı distributed execution kanıtı değildir. + +## 3. Veri ve satır kimliği + +İlk Spark teslimatı flat tabular veri içindir. Nested array/map/struct ve Decimal +otomatik float'a çevrilmez; operation desteklemiyorsa açık hata alınır. Tarihler +ve timestamp timezone dönüşümleri yalnız ilgili node teslimatında etkinleşir. + +Spark inference girdisinde kullanıcının seçtiği benzersiz, null olmayan `row_keys` +zorunludur. Entity tek başına benzersiz değilse entity + event_id gibi birleşik +anahtar kullanılır. Anahtarlar modele feature olarak kendiliğinden verilmez. +Çıktı sırası garanti edilmez; sonuç anahtarla eşleştirilir. `monotonically_increasing_id` +veya partition numarası kalıcı iş anahtarı yerine kullanılamaz. + +Training için target aynı Spark frame'de isimli kolondur. Ayrı Spark X/y frame'leri +pozisyonla birleştirilmez. Local X/y API'si korunur; Spark sınırında `FrameSpec` +ile target ve keys ayrılır. Başlangıçta row-preserving işlemler desteklenir. +Row drop/resampling ve DAG branch merge yetenekleri açık ret verir. + +Doğrulama, duplicate/null key için distributed action gerektirebilir; bu maliyet +runner girişinde bir kez ölçülür. Her node'da tekrar count yapılmaz. Lazy source +değişebiliyorsa giriş snapshot/persist politikası runner sorumluluğundadır. + +Planlanan küçük tipler (`skyulf/core/execution.py`): + +```python +from dataclasses import dataclass + +@dataclass(frozen=True) +class FrameSpec: + row_keys: tuple[str, ...] + target: str | None = None + +@dataclass(frozen=True) +class ExecutionOptions: + engine: str + state_max_bytes: int = 8 * 1024 * 1024 + python_batch_rows: int = 4096 + model_max_bytes: int = 256 * 1024 * 1024 +``` + +Bunlar başlangıç koruma limitleridir, performans garantisi değildir. Her değer +pozitif olmalı; model/batch limitleri hedef ortam ölçümünde düşürülebilir. +Batch satır sınırı byte sınırı değildir; geniş satırlarda bellek ayrıca ölçülür. +Spark session açık parametreyle adapter'a verilir; state/model içine konmaz. + +## 4. Capability ve state + +`skyulf/core/capabilities.py` için planlanan sorgu: + +```python +def require_capability( + node_type: str, operation: str, engine: str, *, config: dict +) -> None: + # Destek yoksa UnsupportedExecutionError: node/operation/engine/reason. + ... +``` + +Kayıtlar fit/apply ayrı, config stratejisi ayrı ve şu özelliklerle tutulur: +`execution_kind` (native/python_batch/local), `row_effect` +(preserve/filter/expand), `context` (row/group/window/global), state codec sürümü. +Yeni `NodeRegistry` kopyası oluşturulmaz; mevcut kayıt anahtarlarıyla ilişkilendirilir. +Spark desteği ilan edilmemiş bütün kayıtlar açıkça unsupported sayılır. +Operation-level öğrenme ve leakage metadata'sı mevcut mekanizma ile uyumlu kalır. + +`skyulf/core/portable_state.py` planlanan envelope alanları: + +```text +format_version=1, node_type, codec_version, ordered_columns, +input_schema, output_schema, learned_parameters, semantic_options, +producer_engine, producer_version, compatibility, semantic_digest +``` + +Envelope mevcut artifact dict'lerini codec üzerinden taşır; Calculator'ın tüm +return tipleri bir seferde değiştirilmez. İlk codec'ler SimpleImputer(mean/constant) +ve StandardScaler. JSON NaN/Infinity ve dtype değerleri için açık tagged encoding +kullanılır; `repr` veya pickle bytes üzerinden semantic digest üretilmez. +Enum/version bilinmiyorsa deserialize etmeden hata verilir. + +Küçük state inline taşınabilir. Büyük kategori/group state için immutable tablo +referansı, schema ve içerik kimliği gerekir; bu SM-17 kapsamıdır. Küçük state +codec'i büyük tabloları driver'a indirmez. Python estimator nesneleri portable +numeric state gibi sunulmaz; sürümlenmiş model paketi içinde ayrı payload olur. + +## 5. İki inference yolu + +```mermaid +flowchart LR + A["Spark raw data + keys"] --> B["Native Spark FE"] + B --> C["Worker: Python estimator"] + C --> D["Spark predictions + keys"] + A --> E["Worker: compatible Python FE + estimator"] + E --> D +``` + +Yol A'da worker yalnız model girişini alır; FE ikinci kez uygulanmaz. Yol B'de +batch-independent Python pipeline çalışır. Bundle `input_stage=raw|features` +ve `feature_order` alanları bu ayrımı doğrular. Sırf row sayısı korundu diye +rolling/group/global işlemler Yol B'ye kabul edilmez. + +Planlanan `skyulf/inference/spark.py` giriş noktası: + +```python +def predict_spark(frame, bundle, *, frame_spec, options, mode): + # mode: native_features | python_pipeline; returns Spark DataFrame + ... +``` + +İlk Python modeli sklearn regression; ardından classification/proba/threshold +semantiği. Worker'da model bir iterator çağrısında bir kez yüklenir; task retry +tekrar yükleyebilir. UDF içinde tracking, registry mutation veya çıktı tablosuna +yazma olmaz. Model/model state limitleri uygulanır. Desteklenmeyen pipeline +driver preflight'ta reddedilir. Çalışan kod her worker'a kurulmuş wheel'dedir. + +## 6. Eğitim ve bağlamsal işlemler + +Spark FE ile distributed training aynı şey değildir. İlk model yerel, açıkça +seçilmiş eğitim verisiyle mevcut API'den eğitilir; inference Spark'ta çalışır. +Spark dataframe'i sklearn fit'e verilirse hata alınır. Bounded local training +export ancak açık row/byte limiti ve sample/selection provenance ile SM-17'de +eklenebilir. Distributed XGBoost/Spark ML estimator'ları ilk release sözü değildir. + +Rolling/lag için group + total order + geçmiş pencere gerekir. Zaman aralığı +ve geçmiş ayrı parametrelerdir. Target/WOE encoding train tarafında OOF state +ve leakage koruması gerektirir. SMOTE'nin yerine Spark sample konulmaz. +SHAP, tuning ve EDA için explicit bounded local yol veya unsupported sonucu +seçilir; native Spark desteği varsayılmaz. Ayrıntılı aile matrisi rapordadır. + +## 7. Dosya sorumlulukları + +| Mevcut dosyalar | Planlanan değişiklik | +| --- | --- | +| `skyulf-core/skyulf/engines/registry.py`, `protocol.py`, `__init__.py` | Spark kimliği; lazy adapter; local/distributed sınırı | +| `skyulf-core/skyulf/preprocessing/dispatcher.py`, `base.py`, `pipeline.py` | capability preflight; Spark input; action-free ölçüm varsayılanı | +| `skyulf-core/skyulf/preprocessing/scaling/standard.py` | Spark aggregate fit ve expression apply | +| `skyulf-core/skyulf/preprocessing/imputation/simple.py` | ilk mean/constant Spark branch'leri | +| `skyulf-core/skyulf/core/artifacts.py`, `core/schema.py` | mevcut tiplerle envelope/schema uyumu | +| `skyulf-core/skyulf/pipeline/_pipeline.py`, `seal.py`, `utils.py` | yeni yollar; save/load uyumu; istatistik ve fingerprint sınırı | +| `skyulf-core/setup.py`, `skyulf-core/pyproject.toml` ve mevcut requirements dosyaları | optional extra ve test ortamı tutarlılığı | + +| Yeni modül | Sorumluluk | +| --- | --- | +| `skyulf-core/skyulf/core/execution.py` | FrameSpec/ExecutionOptions ve doğrulama | +| `skyulf-core/skyulf/core/capabilities.py` | node/operation destek kararı | +| `skyulf-core/skyulf/core/portable_state.py` | versioned state codec | +| `skyulf-core/skyulf/engines/spark_engine.py` | Spark dataframe tanıma ve desteklenen işlemler | +| `skyulf-core/skyulf/preprocessing/_spark.py` | Spark kolon/schema/aggregate yardımcıları | +| `skyulf-core/skyulf/inference/bundle.py` | Python model paketi, giriş/çıkış sözleşmesi | +| `skyulf-core/skyulf/inference/spark.py` | iki dağıtık inference yolu | +| `skyulf-core/skyulf/integrations/mlflow/{tracking,model,registry}.py` | opsiyonel run, pyfunc ve registry adapter'ları | +| `skyulf-core/skyulf/integrations/databricks/{batch,delta}.py` | platform I/O ve batch sonucu yayınlama | + +Yeni paketlerde `__init__.py` yalnız hafif public export içerir. Spark/MLflow +ithalatı ihtiyaç anında yapılır. `core/compute.py` seam'i native node uygulaması +yerine kullanılmaz. `core/serialization.py` ve `core/model_registry.py` mevcut +sözleşmelerle uyumu incelenmeden remote registry yükleme aracı gibi kullanılmaz. + +## 8. Bilinmeyen ortam bilgileri için karar kapısı + +DBR/Python/Spark sürümü, classic/serverless compute, Connect ihtiyacı, izinli +catalog/schema ve tahmini veri genişliği henüz doğrulanmış değil. SM-00 yerel +geliştirme hedefini mevcut Python >=3.12 paket koşuluyla sabitler; SM-16 gerçek +ortam sürümlerini kaydeder ve bağımlılık uyumunu test eder. Sadece bu kapı +ortam bilgisine bağlıdır; core tasarımı ve yerel testler bekletilmez. + +Referanslar: [Spark mapInPandas](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.mapInPandas.html), +[MLflow pyfunc](https://mlflow.org/docs/latest/api_reference/python_api/mlflow.pyfunc.html), +[UC model signature](https://docs.databricks.com/aws/en/machine-learning/manage-model-lifecycle/migrate-to-uc). +Sürümler bu latest sayfalardan tahmin edilmez; hedef runtime üzerinde doğrulanır. diff --git a/initiatives/spark_and_mlflow/BASELINE.md b/initiatives/spark_and_mlflow/BASELINE.md new file mode 100644 index 000000000..e7f929c88 --- /dev/null +++ b/initiatives/spark_and_mlflow/BASELINE.md @@ -0,0 +1,110 @@ +# SM-00 — Güncel baseline ve Spark runtime kanıtı + +Tarih: 2026-09-21. Başlangıç HEAD: +`2397c11648c27645a4ee332412a503c394c1c2f2`. Değişiklikler uncommitted. +Başlangıç sürümü 0.8.20; son geliştirme sürümü 0.9.0, Unreleased. + +Çalışma ağacında önceden .gitignore değişiklikleri, initiative silmeleri ve +untracked plan/test klasörleri vardı; bunlar geri alınmadı. Worktree yaratma +`.git/refs/heads` yazma izni nedeniyle başarısız oldu; bu görev mevcut dizinde +dar kapsamla yürütüldü. Commit/push/release yapılmadı. + +## İlk checkout'un kaynak davranışı + +- EngineRegistry default pandas, sınıf değişkeni; pandas/Polars input detection var. +- Spark enum/engine henüz yok. SM-00 extra yalnız runtime dependency hazırlığı. +- Calculator.fit ve Applier.apply, engine-keyed dispatcher kullanıyor. +- FeatureEngineer fit_transform/transform mevcut local API; Spark girişi yok. +- SkyulfPipeline save/load ve core serializer seam aynı şey sayılmamalı; + native state taşınması henüz uygulanmadı. +- Eski envanterdeki 0.8.24/Polars-default sonuçları bu baseline'a taşınmadı. + +## Ortamlar + +| Paket | Mevcut .venv | Ayrı .venv-spark | +| --- | --- | --- | +| Python | 3.12.10 | 3.12.10 | +| pandas | 2.3.2 | 2.3.2 | +| Polars | 1.44.1 | 1.44.2 | +| NumPy | 1.26.4 | 1.26.4 | +| PyArrow | 24.0.0 | 24.0.0 | +| scikit-learn | 1.8.0 | 1.9.1 | +| pytest | 9.1.1 | 9.1.1 | +| PySpark | kurulu değil | 4.0.3 | +| MLflow | kurulu değil | kurulu değil | + +Spark test hedefi Python 3.12 + Spark 4.0.3 + Java 17. Runtime uyumu için +[Spark 4.0.3 kurulum belgesi](https://spark.apache.org/docs/4.0.3/api/python/getting_started/install.html) +esas alındı. Test edilen Java: Eclipse Temurin 17.0.20.1+1. +JDK resmi [Adoptium API](https://adoptium.net/installation/ci-scripts) üzerinden +indirildi ve API'nin SHA-256 değeriyle doğrulandı. Konumu +`.cache/spark-jdk/jdk-17.0.20.1+1`; sistem PATH/JAVA_HOME ayarları değiştirilmedi. +Bu kurulum Databricks Runtime veya Connect desteği iddiası değildir. + +## Tekrar çalıştırma + +```powershell +uv venv .venv-spark --python .venv/Scripts/python.exe --no-python-downloads +uv pip install --python .venv-spark/Scripts/python.exe -r requirements-spark.txt +$env:JAVA_HOME = (Resolve-Path '.cache/spark-jdk/jdk-17.0.20.1+1').Path +$env:SKYULF_REQUIRE_SPARK = '1' +.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm00-spark-final +``` + +Venv zaten varsa ilk komut tekrar çalıştırılmaz. JAVA_HOME yeni makinedeki Java 17 +konumuna göre ayarlanır. Bu env değerleri yalnız terminal sürecinde geçerlidir. +Repo pytest ayarları için requirements-spark pytest-asyncio da içerir. +Sonuç: **2 passed in 7.23s**, JVM alt süreçleri başarıyla kapandı. + +İlk sandbox denemesi 2 passed ardından PySpark'ın Windows taskkill temizliğinde +Access denied yazdı. İzinli tekrar temiz bitti; son process kontrolünde Skyulf +Spark Java süreci bulunmadı. Son test pytest config uyarısı da üretmedi. + +## Baseline komutu + +```powershell +.venv/Scripts/python.exe -m pytest skyulf-core/tests/unit/test_core_serialization.py skyulf-core/tests/unit/test_core_model_registry.py skyulf-core/tests/unit/test_artifact_shapes.py skyulf-core/tests/unit/test_engines_registry.py skyulf-core/tests/unit/test_engines_sklearn_bridge.py skyulf-core/tests/unit/test_engine_parity.py skyulf-core/tests/integration/test_scaling.py skyulf-core/tests/integration/test_pipeline_integration_preprocessing.py -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm00-baseline +``` + +**206 passed, 5 warnings in 4.47s.** Warning'ler all-NaN scaler fixture'larının +mevcut sklearn/NumPy hesaplamalarından. İlk denemelerde iki test dosyası adı +güncel checkout'ta yoktu; doğru adlar keşfedilip komut düzeltildi. Sistem temp +klasörünün erişim hatası repo içi basetemp kullanılarak giderildi. Bunlar ürün +regresyonu olarak kaydedilmedi. Tam core suite bu görevde tekrar çalıştırılmadı. + +## Negatif test ve statik kontroller + +- Yeni smoke testleri fixture eklenmeden önce beklenen missing-fixture hatası verdi. + Bu test altyapısı bootstrap kontrolüdür; native node TDD kanıtı değildir. +- Base .venv, `SKYULF_REQUIRE_SPARK` yok: 2 skipped. +- Base .venv, `SKYULF_REQUIRE_SPARK=1`: 2 beklenen setup error, exit 1. +- `ruff check skyulf-core/tests/spark skyulf-core/setup.py`: geçti. +- `ruff format --check skyulf-core/tests/spark skyulf-core/setup.py`: geçti. +- `ty check skyulf-core/tests/spark --python .venv-spark`: geçti. +- CI workflow YAML parse edildi; dedicated lane require flag'i doğrulandı. +- Root pyproject, core setup ve frontend package/lock sürümleri 0.9.0 olarak + eşleşiyor. `npm run sync-version` ve `npm run check-version` başarılı. +- `npm run build`: tsc + Vite başarılı (20.43s); circular chunk ve empty + vendor-react chunk uyarıları var. İlk sandbox denemesinin üst dizin erişim + engelinden sonra izinli build tamamlandı; generated static çıktı yeniden üretildi. +- `git diff --check`: başarılı. 0.9.0 changelog Unreleased; yayın/commit yok. + +SM-00 yalnız test foundation kapısıdır. Spark node'ları, portable state, inference +bundle ve MLflow adapter'ları sonraki görevlerdir. Yeni GitHub Actions workflow'u +yazıldı; uzak CI çalıştırılmadı. Sonraki READY görev: SM-01. + +## Master güncellemesi sonrası yeniden doğrulama + +Kullanıcının talimatıyla origin fetch edildi; 090 ve yerel master +`97536eae20e5422220f9824bc591ceb05576ee50` commit'ine fast-forward edildi. +Bu commit 0.8.24 PR #175 merge'idir. Başlangıçta yerel master 70 commit gerideydi. +Stash üzerinden çalışma korundu; version conflict'leri 0.9.0 olarak çözüldü. +Yeni tabanda Polars default ve ContextVar engine scope tekrar mevcut. + +Yukarıdaki baseline komutuna `skyulf-core/tests/unit/test_engine_context.py` +eklenerek `.cache/sm00-upstream-baseline` basetemp'iyle tekrar çalıştırıldı: +**231 passed, 5 warnings (3.26s)**. Spark lane: +`.cache/sm00-upstream-spark` basetemp'iyle **2 passed (7.38s)**, temiz JVM kapanışı. +Tam repo ty check ve scoped Ruff geçti. `mkdocs build --strict` yeni Spark +kullanıcı rehberiyle başarılı. Spark optional imports test fixture'da lazy +importlib yüklemesiyle çözülür; base ortamda PySpark zorunlu hale getirilmez. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md new file mode 100644 index 000000000..a4c54523e --- /dev/null +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -0,0 +1,82 @@ +# Spark ve MLflow — Open Queue + +Güncelleme: 2026-09-21. **SM-00 tamamlandı. Sonraki görev: SM-01. Hedef: 0.9.0.** +Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. + +Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; +LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; +DONE = kanıtla tamamlandı. Şu an ACTIVE görev yok; SM-01 başlanabilir. + +| Sıra | Görev | Bağımlılık | Durum | Kısa bitiş ölçütü | +| --- | --- | --- | --- | --- | +| SM-00 | Baseline ve Spark test ortamı | — | DONE | Güncel master: 231 baseline; 2 Spark smoke; [kanıt](BASELINE.md) | +| SM-01 | Execution/capability kuralları | SM-00 | READY | Desteklenmeyen engine/operation erken ret | +| SM-02 | Spark engine ve conversion sınırı | SM-01 | WAIT | Spark tanınır; gizli local conversion yok | +| SM-03 | Dispatcher, schema, row keys | SM-02 | WAIT | Key/target korunur; local API çalışır | +| SM-04 | Versioned portable state | SM-03 | WAIT | Limit/version kontrolü; state round-trip | +| SM-05 | Native SimpleImputer | SM-04 | WAIT | Mean/constant train-only fit, Spark apply | +| SM-06 | Native StandardScaler | SM-05 | WAIT | Population variance ve flag parity | +| SM-07 | Uçtan uca FE kapısı | SM-06 | WAIT | Üç engine çapraz fit/apply; kayıt/yükleme | +| SM-08 | Ortak inference bundle | SM-07 | WAIT | Raw/features ayrımı; model metadata round-trip | +| SM-09 | Native FE + worker model | SM-08 | WAIT | Spark tahmini local ile key bazında aynı | +| SM-10 | Worker Python FE + model | SM-09 | WAIT | Batch-safe pipeline; window gibi yollar açık ret | +| SM-11 | Classification ve ölçek kapısı | SM-10 | WAIT | Class/proba/threshold parity; worker kanıtı | +| SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | +| SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | +| SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | +| SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | +| SM-16 | Gerçek Databricks kapısı | SM-15 | WAIT | Job/run kanıtı; UC load; iki inference yolu | +| SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | +| SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | +| SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | +| SM-20 | Template / Databricks Bundle | SM-19 | LATER | Seçilebilir working runner; validate ve smoke | + +## Detay planlar + +- SM-00–SM-07: [Core/Spark](01-core-spark-plan.md) +- SM-08–SM-11: [Inference](02-inference-plan.md) +- SM-12–SM-20: [MLflow/batch/son teslimatlar](03-mlflow-batch-delivery-plan.md) +- Ortak kurallar: [Mimari](ARCHITECTURE.md), [Doğrulama](VALIDATION.md) + +SM-17 başlangıcında 17a column/cast/date, 17b quantile/category, +17c group/window, 17d OOF alt görevlerine ayrılır. Her alt görevin kendi +test/review kapısı vardır. Tüm node'ların native olması zorunlu değildir; +gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. +SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported +olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. + +## Bir görevi kapatma kaydı + +Her DONE satırına aynı dosyada aşağıdaki bilgileri içeren tarihli kayıt ekle: + +```text +Task ID / tarih / incelenen commit / değişiklik commit'i veya uncommitted +Değişen dosyalar ve sağlanan davranış +Çalıştırılan exact komutlar / passed-failed-skipped / runtime sürümleri +Olumsuz senaryo kanıtı (unsupported, leakage, retry vb.) +Bilinen sınırlamalar / sonraki görev +``` + +Komutlar çalıştırılmadan kutular işaretlenmez. Spark lane'inde tamamı skip olmuş +suite DONE kanıtı değildir. Platform erişimi gerektiğinde BLOCKED nedeni somut +olarak yazılır; yerel test sonucu gerçek UC/Databricks sonucu yerine geçmez. + +## Devam oturumu için kısa talimat + +Önce README, mimari ve bu kuyruğu oku. Güncel git durumunu ve ilgili kaynakları +doğrula; kullanıcı değişikliklerini koru. İlk READY görevi ACTIVE yap, kendi +test döngüsüyle tamamla ve kanıtı yaz. Sonraki bağımlılığı aç. Endpoint veya +template'e önden başlama. SM-00 test/runtime hazırlığıdır; native node uygulaması +ve MLflow entegrasyonu henüz yok. + +## SM-00 — 2026-09-21 tamamlanma kaydı + +- Başlangıç HEAD: `2397c11648c27645a4ee332412a503c394c1c2f2`; değişiklikler uncommitted. +- Test fixture/smoke, optional extra/requirements, Spark CI lane ve 0.9.0 + Unreleased changelog oluşturuldu. Detaylı ortam ve komutlar [BASELINE.md](BASELINE.md). +- Local baseline: 206 passed, 5 mevcut numeric warning. +- PySpark 4.0.3 + Temurin Java 17.0.20.1 + Python 3.12.10: 2 passed, temiz kapanış. +- Spark olmayan base ortam: 2 skipped; zorunlu Spark modu: beklenen 2 setup error, + exit 1. Eksik dependency başarılı CI gibi raporlanmıyor. +- Ruff check/format ve scoped ty geçti. GitHub Actions ve Databricks çalıştırılmadı. +- Sonraki görev SM-01; bu kanıt native Spark node desteği anlamına gelmez. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md new file mode 100644 index 000000000..5b6c40e12 --- /dev/null +++ b/initiatives/spark_and_mlflow/README.md @@ -0,0 +1,68 @@ +# Spark ve MLflow initiative + +Tarih: 2026-09-21. Durum: **SM-00 tamamlandı; sıradaki görev SM-01.** +Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). +Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). + +Amaç: Skyulf Core'un mevcut pandas/Polars davranışını koruyarak gerçek Spark +feature engineering, dağıtık Python inference ve opsiyonel MLflow/Unity Catalog +entegrasyonu sağlamak. Aylık batch teslimatından sonra endpoint'ler, en son +template/Databricks Bundle gelir. + +## Okuma ve uygulama sırası + +1. [OPEN_QUEUE.md](OPEN_QUEUE.md): kısa, sıralı görev kuyruğu ve sonraki iş. +2. [ARCHITECTURE.md](ARCHITECTURE.md): kapsam, değişmez kurallar ve dosya sınırları. +3. [01-core-spark-plan.md](01-core-spark-plan.md): SM-00–SM-07, engine ve fit/apply. +4. [02-inference-plan.md](02-inference-plan.md): SM-08–SM-11, iki inference yolu. +5. [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md): + SM-12–SM-20, MLflow, registry, batch ve son teslimatlar. +6. [VALIDATION.md](VALIDATION.md): test matrisi, ortamlar ve tamamlanma kanıtı. + +Tarihsel araştırma: + +- [Hazırlık incelemesi](reports/2026-09-21-spark-databricks-readiness.md) +- [Kaynak/node/test envanteri](reports/2026-09-21-spark-core-inventory.md) + +Bu iki rapor `initiatives/reports/` içinden taşındı. Rapordaki sayılar ve test +sonuçları raporun incelediği commit'e aittir; güncel dalın sonucu değildir. +Plan hazırlanırken HEAD `2397c11648c27645a4ee332412a503c394c1c2f2` idi. +Özellikle güncel `engines/registry.py` pandas varsayılanı ve sınıf değişkeni +kullanıyor; eski rapordaki Polars/ContextVar ifadesi güncel varsayım yapılmamalı. +SM-00 mevcut davranışı yeniden kaydeder. Bu initiative global varsayılan engine'i +değiştirmeyi gerektirmez; ileride wizard önerisi ayrı bir kullanıcı tercihidir. + +Güncelleme: 090 ve yerel master 0.8.24 merge noktası +`97536eae20e5422220f9824bc591ceb05576ee50` üzerine ilerletildi. Yukarıdaki +pandas-default notu önceki checkout'u anlatır; güncel kaynak Polars/ContextVar +davranışını geri içeriyor. Güncel tekrar: 231 baseline + 2 Spark smoke geçti. +Kullanıcı belgeleri: [Spark rehberi](../../docs/user_guide/spark.md). + +## İlk teslimat + +Kolon seçimi → SimpleImputer(mean/constant) → StandardScaler → kayıt/yükleme → +Spark apply. Sonra aynı feature'larla mevcut bir Python modelinin Spark worker +tahmini. Spark verisini driver'a indirmek hiçbir aşamanın gizli çözümü değildir. +Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutulur. + +## Çalışma kuralları + +- Sonraki görev **SM-01**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. +- Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak + yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. +- Dosya yazılmış olması, testlerin geçmesi ve Databricks'te çalışması ayrı durumlar. +- Queue'da DONE için komut, sonuç, runtime ve commit/çalışma ağacı kaydı gerekir. +- Commit/push bu planın otomatik adımı değildir; yalnız kullanıcı istediğinde + güncel kontrollerle DCO commit hazırlanır. +- Önce core/SDK; backend/Canvas değişikliği SM-18. Endpoint SM-19, + template SM-20. Streaming ilk release'in zorunlu koşulu değildir. + +## Diğer initiative'lerle ilişki + +[Önceki MLflow planı](../analysis/skyulf-core-mlflow-integration-plan.md) +tarihsel girdidir. Bu çalışma için sıra ve karar kaynağı burasıdır: global fit +callback veya backend job'a zorunlu bağlı tracking yerine açık run kapsamı; +ilk teslimatta UI yok. Joblib/ONNX, Ray ve deep-learning planları bu çalışmanın +önkoşulu değildir. Paylaşılan artifact/pipeline dosyalarındaki eşzamanlı +değişiklikler her görev başında kontrol edilir. diff --git a/initiatives/spark_and_mlflow/VALIDATION.md b/initiatives/spark_and_mlflow/VALIDATION.md new file mode 100644 index 000000000..1377574da --- /dev/null +++ b/initiatives/spark_and_mlflow/VALIDATION.md @@ -0,0 +1,88 @@ +# Doğrulama ve release kapıları + +Bu belge gelecek uygulamanın kabul ölçütlerini tanımlar. Tarihsel rapordaki +9.815 passed / 68 skipped / 1 failed sonucu bu planın test sonucu değildir. +O çalışmadaki ağ bağımlı embedding testi offline tek tekrarında geçmişti; +güncel baseline SM-00'da yeniden ölçülür. + +## Ortam matrisi + +| Lane | Amaç | Geçme koşulu | +| --- | --- | --- | +| Base Python | Spark/MLflow olmadan mevcut core | Import + local regression | +| OSS Spark local[2] | Gerçek partition/action ve parity | Spark suite çalışır, toplu skip yok | +| MLflow local store | Run/model/registry lifecycle | Gerçek save/load; subprocess packaging | +| Delta integration | Atomik dönem yayını | Gerçek tablo, retry ve conflict | +| Databricks seçili runtime | UC/worker/wheel/job entegrasyonu | SM-16 platform evidence | +| Connect/serverless | İsteğe bağlı ortam profili | Ayrı smoke; başka lane sonucu yeterli değil | + +OSS Spark, DBR ve Connect ayrı dependency profilleri olarak ele alınır. DBR'ın +runtime paketlerini OSS test extra'sıyla körlemesine değiştirme. Sürüm sabitleme +SM-00/SM-16 çıktısıdır. Python >=3.12 mevcut paket gereksinimidir. + +## Davranış matrisi + +| Sözleşme | Test verisi ve assertion | +| --- | --- | +| Train-only state | Train [1,null,3], held-out [100,null]; fill 2 | +| StandardScaler | [1,3] → mean=2, var=1, scale=1; dört flag kombinasyonu | +| Null/NaN | All-null, NaN, constant, empty; açık local semantiği | +| Kolon/dtype | Farklı sıra, missing/extra, dot/backtick; silent coercion yok | +| Row identity | Repartition 1/2/7, shuffle; key eşleşmesi; null/duplicate ret | +| State transport | 3 fit engine × 3 apply engine; supported operation'lar | +| Persistence | Codec/bundle round-trip; eski pickle local regression | +| Native execution | FE apply'da Python UDF/ham data collect yok | +| Distributed Python | Batch size 2/17/default; aynı key için aynı tahmin | +| Temporal | Rolling [1..6] chunk karşı örneği; generic worker yolunda ret | +| Classification | String/multiclass, classes_ sırası, proba, threshold precedence | +| Lifecycle | Worker fit yok; state mutation yok; concurrent run id isolation | +| MLflow optional | Paket yokken disabled çalışır; enabled açık dependency hatası | +| Registry | Alias run başında sabitlenir; arada alias değişimi sonucu etkilemez | +| Batch output | Aynı ay retry, başka ay korunur, empty guard, concurrent conflict | +| Packaging | Temiz subprocess/worker wheel; repo cwd bağımlılığı yok | + +Float tolerance fixture'ın sayısal ölçeğine göre gerekçelendirilir; küçük FE +fixture'larında rtol=1e-10/atol=1e-12. Category/key/schema için exact equality. +Row sırasına göre list equality Spark kanıtı değildir. + +## Materialization kanıtı + +Static toPandas araması tek başına yeterli değildir. Üretim input'unda collection +metodlarını guard eden test, gerçek Spark plan ve ölçek ölçümü birlikte kullanılır. +Aggregate state toplama izinli ve state_max_bytes limitlidir. Testin küçük +beklenen sonucunu collect etmesi üretim driver fallback'i sayılmaz. Native FE +planında Python UDF olmamalı; model inference planında Python yürütmesi beklenir. +Yürütme testleri action çağırmalı; erken ret testleri action olmadığını doğrulamalı. + +## Komutlar + +Önce görev dosyasındaki dar pytest komutu. Interpreter ilgili lane'in venv'i +olmalı; `.venv` ile `.venv-spark` karıştırılmaz. + +```powershell +.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark -q +.venv/Scripts/python.exe -m pytest skyulf-core/tests -q +.venv/Scripts/python.exe -m ruff check skyulf-core/skyulf skyulf-core/tests +.venv/Scripts/python.exe -m ruff format --check skyulf-core/skyulf skyulf-core/tests +``` + +Type gate: repo'nun güncel ty check kapsamını uygula; optional modüllerde paket +yokken type import hatalarını maskelemeden dependency lane'i ayır. Backend +değişirse ilgili root integration testleri; frontend değişirse typecheck, vitest, +eslint ve build. Yalnız Markdown planı için uygulama suite'i tekrar çalıştırmak +veya mkdocs build yapmak gerekmez; doküman linkleri doğrulanır. + +## Kapılar + +- G1 / SM-07: native FE ve portable state; local API regresyonu yok. +- G2 / SM-11: iki inference yolu + classification + worker/ölçek kanıtı. +- G3 / SM-14: opsiyonel MLflow model/run/registry; UC gerçek kanıtı G4'te. +- G4 / SM-16: gerçek Databricks job + UC load + idempotent Delta batch. +- G5 / SM-17: node support matrisi gerçeğe uygun; unsupported açık. +- G6 / SM-18: backend/Canvas supported akışlar ve legacy artifact uyumu. +- G7 / SM-19: endpoint/SQL parity; optional streaming ayrı sonuç. +- G8 / SM-20: template validation ve gerçek deploy/run kanıtı ayrı. + +Failure nedenini ürün hatası, ortam eksikliği veya önceden var olan failure +olarak kanıtla kaydet. Skip'i pass gibi yazma. Yanlış tahmin, leakage veya satır +kaybı varsa ilgili capability kapalı kalır. diff --git a/initiatives/spark_and_mlflow/reports/2026-09-21-spark-core-inventory.md b/initiatives/spark_and_mlflow/reports/2026-09-21-spark-core-inventory.md new file mode 100644 index 000000000..10ecdf9e8 --- /dev/null +++ b/initiatives/spark_and_mlflow/reports/2026-09-21-spark-core-inventory.md @@ -0,0 +1,597 @@ +# Spark incelemesi: kaynak ve node envanteri + +Tarih: 2026-09-21. Ana yorumlar ve sinirlar: [Inceleme raporu](2026-09-21-spark-databricks-readiness.md). + +Bu dosya AST/import/registry taramasidir. Bir dosyanin listelenmesi, her satirinin +bagimsiz dogruluk denetiminden gectigi veya Spark destegi oldugu anlamina gelmez. +Isaretler arama bulgularidir; docstring icinde de gecebilirler. + + +Ta??ma notu (2026-09-21): Bu envanter tarihsel snapshot kayd?d?r. ? ile +i?aretli 88 kaynak/test ba?lant?s?n?n hedefi plan haz?rlan?rken g?ncel +checkout'ta bulunmuyordu; kay?tlar silinmedi, k?r?k ba?lant?lar d?z yol etiketi +olarak korundu. Dosya say?lar? ve eski bulgular yeniden ?l??lm?? say?lmaz. + +## Kaynak dosyalari + +| Dosya | Satir | Kayitlar | Yerel veri / yurutme isaretleri | +| --- | ---: | --- | --- | +| [__init__.py](../../../skyulf-core/skyulf/__init__.py) | 54 | | | +| [_validation.py](../../../skyulf-core/skyulf/_validation.py) | 12 | | | +| [config_validation.py](../../../skyulf-core/skyulf/config_validation.py) | 111 | | | +| [core/__init__.py](../../../skyulf-core/skyulf/core/__init__.py) | 47 | | | +| [core/artifacts.py](../../../skyulf-core/skyulf/core/artifacts.py) | 653 | | | +| [core/compute.py](../../../skyulf-core/skyulf/core/compute.py) | 80 | | | +| [core/deprecation.py](../../../skyulf-core/skyulf/core/deprecation.py) | 93 | | | +| [core/meta/__init__.py](../../../skyulf-core/skyulf/core/meta/__init__.py) | 1 | | | +| [core/meta/decorators.py](../../../skyulf-core/skyulf/core/meta/decorators.py) | 54 | | | +| [core/model_registry.py](../../../skyulf-core/skyulf/core/model_registry.py) | 92 | | | +| [core/protocols.py](../../../skyulf-core/skyulf/core/protocols.py) | 77 | | | +| [core/schema.py](../../../skyulf-core/skyulf/core/schema.py) | 303 | | | +| [core/serialization.py](../../../skyulf-core/skyulf/core/serialization.py) | 94 | | pickle, joblib | +| `core/validation.py` ? | 30 | | | +| [core/warnings.py](../../../skyulf-core/skyulf/core/warnings.py) | 52 | | | +| [data/__init__.py](../../../skyulf-core/skyulf/data/__init__.py) | 8 | | | +| [data/catalog.py](../../../skyulf-core/skyulf/data/catalog.py) | 47 | | | +| [data/dataset.py](../../../skyulf-core/skyulf/data/dataset.py) | 74 | | | +| [engines/__init__.py](../../../skyulf-core/skyulf/engines/__init__.py) | 26 | | | +| [engines/pandas_engine.py](../../../skyulf-core/skyulf/engines/pandas_engine.py) | 148 | pandas | to_pandas, to_numpy | +| [engines/polars_engine.py](../../../skyulf-core/skyulf/engines/polars_engine.py) | 209 | polars | to_pandas, to_numpy | +| [engines/protocol.py](../../../skyulf-core/skyulf/engines/protocol.py) | 136 | | to_pandas, iloc | +| [engines/registry.py](../../../skyulf-core/skyulf/engines/registry.py) | 170 | | to_numpy | +| [engines/sklearn_bridge.py](../../../skyulf-core/skyulf/engines/sklearn_bridge.py) | 164 | | to_numpy | +| [leakage.py](../../../skyulf-core/skyulf/leakage.py) | 326 | | | +| [modeling/__init__.py](../../../skyulf-core/skyulf/modeling/__init__.py) | 103 | | cross_val | +| [modeling/_boosting_progress.py](../../../skyulf-core/skyulf/modeling/_boosting_progress.py) | 107 | | | +| `modeling/_class_weights.py` ? | 42 | | | +| [modeling/_evaluation/__init__.py](../../../skyulf-core/skyulf/modeling/_evaluation/__init__.py) | 45 | | | +| [modeling/_evaluation/classification.py](../../../skyulf-core/skyulf/modeling/_evaluation/classification.py) | 174 | | | +| [modeling/_evaluation/clustering.py](../../../skyulf-core/skyulf/modeling/_evaluation/clustering.py) | 309 | | to_pandas, iter_rows | +| [modeling/_evaluation/common.py](../../../skyulf-core/skyulf/modeling/_evaluation/common.py) | 77 | | | +| [modeling/_evaluation/metrics.py](../../../skyulf-core/skyulf/modeling/_evaluation/metrics.py) | 500 | | | +| [modeling/_evaluation/regression.py](../../../skyulf-core/skyulf/modeling/_evaluation/regression.py) | 86 | | | +| [modeling/_evaluation/schemas.py](../../../skyulf-core/skyulf/modeling/_evaluation/schemas.py) | 88 | | | +| [modeling/_evaluation/thresholds.py](../../../skyulf-core/skyulf/modeling/_evaluation/thresholds.py) | 281 | | | +| [modeling/_explainability/__init__.py](../../../skyulf-core/skyulf/modeling/_explainability/__init__.py) | 7 | | | +| [modeling/_explainability/shap_explanation.py](../../../skyulf-core/skyulf/modeling/_explainability/shap_explanation.py) | 443 | | to_numpy, iloc | +| `modeling/_lightgbm.py` ? | 33 | | | +| [modeling/_sklearn_compat.py](../../../skyulf-core/skyulf/modeling/_sklearn_compat.py) | 54 | | | +| [modeling/_tuning/__init__.py](../../../skyulf-core/skyulf/modeling/_tuning/__init__.py) | 15 | | | +| [modeling/_tuning/engine.py](../../../skyulf-core/skyulf/modeling/_tuning/engine.py) | 1044 | | to_pandas, to_numpy, cross_val | +| [modeling/_tuning/fold_pipeline.py](../../../skyulf-core/skyulf/modeling/_tuning/fold_pipeline.py) | 234 | | to_pandas, to_numpy, iloc | +| `modeling/_tuning/fold_scoring.py` ? | 56 | | to_numpy | +| [modeling/_tuning/grid_random.py](../../../skyulf-core/skyulf/modeling/_tuning/grid_random.py) | 315 | | to_numpy, iloc | +| [modeling/_tuning/metrics.py](../../../skyulf-core/skyulf/modeling/_tuning/metrics.py) | 243 | | | +| [modeling/_tuning/params.py](../../../skyulf-core/skyulf/modeling/_tuning/params.py) | 148 | | | +| [modeling/_tuning/refit.py](../../../skyulf-core/skyulf/modeling/_tuning/refit.py) | 234 | | | +| [modeling/_tuning/reporter.py](../../../skyulf-core/skyulf/modeling/_tuning/reporter.py) | 97 | | | +| [modeling/_tuning/schemas.py](../../../skyulf-core/skyulf/modeling/_tuning/schemas.py) | 65 | | cross_val | +| [modeling/_tuning/splitters.py](../../../skyulf-core/skyulf/modeling/_tuning/splitters.py) | 175 | | to_pandas | +| [modeling/_tuning/strategies/__init__.py](../../../skyulf-core/skyulf/modeling/_tuning/strategies/__init__.py) | 7 | | | +| [modeling/_tuning/strategies/halving.py](../../../skyulf-core/skyulf/modeling/_tuning/strategies/halving.py) | 93 | | | +| [modeling/_tuning/strategies/optuna.py](../../../skyulf-core/skyulf/modeling/_tuning/strategies/optuna.py) | 323 | | | +| `modeling/_tuning/strategies/optuna_folds.py` ? | 187 | | to_numpy | +| `modeling/_tuning/strategies/optuna_search.py` ? | 211 | | | +| [modeling/_tuning/strategies/runner.py](../../../skyulf-core/skyulf/modeling/_tuning/strategies/runner.py) | 207 | | joblib | +| [modeling/base.py](../../../skyulf-core/skyulf/modeling/base.py) | 650 | | to_numpy, pickle, cross_val | +| [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | 937 | logistic_regression, calibrated_classifier, random_forest_classifier, svc, k_neighbors_classifier, decision_tree_classifier, gradient_boosting_classifier, adaboost_classifier, extra_trees_classifier, hist_gradient_boosting_classifier, gaussian_nb, sgd_classifier, xgboost_classifier, lgbm_classifier | | +| [modeling/clustering.py](../../../skyulf-core/skyulf/modeling/clustering.py) | 300 | kmeans, minibatch_kmeans, gaussian_mixture, birch | to_pandas, pickle | +| [modeling/cross_validation.py](../../../skyulf-core/skyulf/modeling/cross_validation.py) | 694 | | to_numpy, iloc, cross_val | +| [modeling/ensemble.py](../../../skyulf-core/skyulf/modeling/ensemble.py) | 678 | voting_classifier, stacking_classifier, voting_regressor, stacking_regressor | | +| [modeling/fold_preprocessing.py](../../../skyulf-core/skyulf/modeling/fold_preprocessing.py) | 33 | | cross_val | +| [modeling/hyperparameters/__init__.py](../../../skyulf-core/skyulf/modeling/hyperparameters/__init__.py) | 106 | | | +| [modeling/hyperparameters/_bayes.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_bayes.py) | 68 | | | +| [modeling/hyperparameters/_calibration.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_calibration.py) | 55 | | | +| [modeling/hyperparameters/_clustering.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_clustering.py) | 121 | | | +| [modeling/hyperparameters/_ensemble.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_ensemble.py) | 205 | | | +| [modeling/hyperparameters/_field.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_field.py) | 71 | | | +| [modeling/hyperparameters/_linear.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_linear.py) | 241 | | | +| [modeling/hyperparameters/_neighbors.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_neighbors.py) | 40 | | | +| [modeling/hyperparameters/_registry.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_registry.py) | 665 | | | +| [modeling/hyperparameters/_svm.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_svm.py) | 39 | | | +| [modeling/hyperparameters/_tree.py](../../../skyulf-core/skyulf/modeling/hyperparameters/_tree.py) | 656 | | | +| [modeling/naive_bayes.py](../../../skyulf-core/skyulf/modeling/naive_bayes.py) | 99 | multinomial_nb, bernoulli_nb | | +| `modeling/pruning.py` ? | 152 | | | +| [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | 658 | linear_regression, ridge_regression, random_forest_regressor, lasso_regression, elasticnet_regression, svr, k_neighbors_regressor, decision_tree_regressor, gradient_boosting_regressor, adaboost_regressor, extra_trees_regressor, hist_gradient_boosting_regressor, lgbm_regressor, xgboost_regressor | joblib | +| [modeling/sklearn_wrapper.py](../../../skyulf-core/skyulf/modeling/sklearn_wrapper.py) | 268 | | to_pandas, pickle | +| [pipeline/__init__.py](../../../skyulf-core/skyulf/pipeline/__init__.py) | 17 | | | +| [pipeline/_pipeline.py](../../../skyulf-core/skyulf/pipeline/_pipeline.py) | 786 | | to_pandas, pickle | +| [pipeline/diagram.py](../../../skyulf-core/skyulf/pipeline/diagram.py) | 134 | | | +| [pipeline/seal.py](../../../skyulf-core/skyulf/pipeline/seal.py) | 250 | | pickle | +| [preprocessing/__init__.py](../../../skyulf-core/skyulf/preprocessing/__init__.py) | 261 | | | +| [preprocessing/_artifacts.py](../../../skyulf-core/skyulf/preprocessing/_artifacts.py) | 121 | | | +| [preprocessing/_category_keys.py](../../../skyulf-core/skyulf/preprocessing/_category_keys.py) | 75 | | | +| [preprocessing/_helpers.py](../../../skyulf-core/skyulf/preprocessing/_helpers.py) | 319 | | to_pandas, to_numpy, iloc | +| `preprocessing/_output_names.py` ? | 29 | | | +| [preprocessing/_schema.py](../../../skyulf-core/skyulf/preprocessing/_schema.py) | 11 | | | +| [preprocessing/base.py](../../../skyulf-core/skyulf/preprocessing/base.py) | 341 | | tracemalloc | +| [preprocessing/bucketing.py](../../../skyulf-core/skyulf/preprocessing/bucketing.py) | 699 | GeneralBinning, CustomBinning, KBinsDiscretizer | to_pandas | +| [preprocessing/casting.py](../../../skyulf-core/skyulf/preprocessing/casting.py) | 535 | Casting | to_pandas, to_numpy | +| [preprocessing/cleaning/__init__.py](../../../skyulf-core/skyulf/preprocessing/cleaning/__init__.py) | 35 | | | +| [preprocessing/cleaning/_common.py](../../../skyulf-core/skyulf/preprocessing/cleaning/_common.py) | 48 | | | +| [preprocessing/cleaning/alias.py](../../../skyulf-core/skyulf/preprocessing/cleaning/alias.py) | 216 | AliasReplacement | | +| [preprocessing/cleaning/invalid_value.py](../../../skyulf-core/skyulf/preprocessing/cleaning/invalid_value.py) | 303 | InvalidValueReplacement | | +| [preprocessing/cleaning/text.py](../../../skyulf-core/skyulf/preprocessing/cleaning/text.py) | 250 | TextCleaning | | +| [preprocessing/cleaning/value_replacement.py](../../../skyulf-core/skyulf/preprocessing/cleaning/value_replacement.py) | 254 | ValueReplacement | | +| [preprocessing/dispatcher.py](../../../skyulf-core/skyulf/preprocessing/dispatcher.py) | 273 | | to_pandas | +| [preprocessing/drop_and_missing/__init__.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/__init__.py) | 29 | | | +| [preprocessing/drop_and_missing/_common.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/_common.py) | 59 | | to_numpy, iloc | +| [preprocessing/drop_and_missing/deduplicate.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/deduplicate.py) | 119 | Deduplicate | to_numpy, iloc | +| [preprocessing/drop_and_missing/drop_columns.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/drop_columns.py) | 150 | DropMissingColumns | | +| [preprocessing/drop_and_missing/drop_rows.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/drop_rows.py) | 170 | DropMissingRows | to_numpy, iloc | +| [preprocessing/drop_and_missing/missing_indicator.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/missing_indicator.py) | 177 | MissingIndicator | | +| [preprocessing/encoding/__init__.py](../../../skyulf-core/skyulf/preprocessing/encoding/__init__.py) | 44 | | | +| [preprocessing/encoding/_common.py](../../../skyulf-core/skyulf/preprocessing/encoding/_common.py) | 148 | | | +| [preprocessing/encoding/dummy.py](../../../skyulf-core/skyulf/preprocessing/encoding/dummy.py) | 297 | DummyEncoder | to_list | +| [preprocessing/encoding/hash.py](../../../skyulf-core/skyulf/preprocessing/encoding/hash.py) | 186 | HashEncoder | to_list | +| [preprocessing/encoding/label.py](../../../skyulf-core/skyulf/preprocessing/encoding/label.py) | 350 | LabelEncoder | to_numpy | +| [preprocessing/encoding/one_hot.py](../../../skyulf-core/skyulf/preprocessing/encoding/one_hot.py) | 271 | OneHotEncoder | to_numpy, toarray | +| [preprocessing/encoding/ordinal.py](../../../skyulf-core/skyulf/preprocessing/encoding/ordinal.py) | 384 | OrdinalEncoder | to_numpy | +| [preprocessing/encoding/target.py](../../../skyulf-core/skyulf/preprocessing/encoding/target.py) | 416 | TargetEncoder | to_pandas, to_numpy | +| [preprocessing/encoding/woe.py](../../../skyulf-core/skyulf/preprocessing/encoding/woe.py) | 385 | WOEEncoder | to_pandas, to_numpy, to_list, iloc | +| [preprocessing/feature_generation/__init__.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/__init__.py) | 31 | | | +| [preprocessing/feature_generation/_common.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/_common.py) | 197 | | to_numpy, iloc | +| [preprocessing/feature_generation/_pandas_ops.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/_pandas_ops.py) | 256 | | | +| [preprocessing/feature_generation/_polars_ops.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/_polars_ops.py) | 315 | | | +| [preprocessing/feature_generation/generation.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py) | 153 | FeatureGeneration, FeatureMath, FeatureGenerationNode | to_pandas | +| [preprocessing/feature_generation/interaction.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/interaction.py) | 215 | FeatureInteraction | to_pandas | +| [preprocessing/feature_generation/polynomial.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/polynomial.py) | 153 | PolynomialFeatures, PolynomialFeaturesNode | to_numpy | +| [preprocessing/feature_selection/__init__.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/__init__.py) | 25 | | | +| [preprocessing/feature_selection/_common.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/_common.py) | 365 | | to_pandas, to_numpy | +| [preprocessing/feature_selection/correlation.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/correlation.py) | 213 | CorrelationThreshold | to_pandas | +| [preprocessing/feature_selection/facade.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/facade.py) | 97 | feature_selection | | +| [preprocessing/feature_selection/model_based.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/model_based.py) | 117 | ModelBasedSelection | to_pandas | +| [preprocessing/feature_selection/univariate.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/univariate.py) | 117 | UnivariateSelection | to_pandas | +| [preprocessing/feature_selection/variance.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/variance.py) | 96 | VarianceThreshold | to_numpy | +| [preprocessing/fold_adapter.py](../../../skyulf-core/skyulf/preprocessing/fold_adapter.py) | 377 | | to_pandas | +| [preprocessing/geo/__init__.py](../../../skyulf-core/skyulf/preprocessing/geo/__init__.py) | 20 | | | +| [preprocessing/geo/distance.py](../../../skyulf-core/skyulf/preprocessing/geo/distance.py) | 226 | GeoDistance | to_pandas | +| [preprocessing/geo/h3_index.py](../../../skyulf-core/skyulf/preprocessing/geo/h3_index.py) | 165 | H3Index | to_pandas, to_numpy | +| [preprocessing/imputation/__init__.py](../../../skyulf-core/skyulf/preprocessing/imputation/__init__.py) | 25 | | | +| [preprocessing/imputation/_common.py](../../../skyulf-core/skyulf/preprocessing/imputation/_common.py) | 159 | | to_numpy | +| [preprocessing/imputation/iterative.py](../../../skyulf-core/skyulf/preprocessing/imputation/iterative.py) | 103 | IterativeImputer | to_numpy | +| [preprocessing/imputation/knn.py](../../../skyulf-core/skyulf/preprocessing/imputation/knn.py) | 97 | KNNImputer | to_numpy | +| [preprocessing/imputation/simple.py](../../../skyulf-core/skyulf/preprocessing/imputation/simple.py) | 236 | SimpleImputer | | +| [preprocessing/inspection.py](../../../skyulf-core/skyulf/preprocessing/inspection.py) | 187 | DatasetProfile, DataSnapshot | | +| [preprocessing/outliers/__init__.py](../../../skyulf-core/skyulf/preprocessing/outliers/__init__.py) | 32 | | | +| [preprocessing/outliers/_common.py](../../../skyulf-core/skyulf/preprocessing/outliers/_common.py) | 39 | | to_numpy, iloc | +| [preprocessing/outliers/elliptic.py](../../../skyulf-core/skyulf/preprocessing/outliers/elliptic.py) | 179 | EllipticEnvelope | to_pandas, to_numpy, iloc | +| [preprocessing/outliers/iqr.py](../../../skyulf-core/skyulf/preprocessing/outliers/iqr.py) | 124 | IQR | to_pandas, to_numpy | +| [preprocessing/outliers/manual_bounds.py](../../../skyulf-core/skyulf/preprocessing/outliers/manual_bounds.py) | 111 | ManualBounds | | +| [preprocessing/outliers/winsorize.py](../../../skyulf-core/skyulf/preprocessing/outliers/winsorize.py) | 129 | Winsorize | to_pandas | +| [preprocessing/outliers/zscore.py](../../../skyulf-core/skyulf/preprocessing/outliers/zscore.py) | 130 | ZScore | to_pandas | +| [preprocessing/pipeline.py](../../../skyulf-core/skyulf/preprocessing/pipeline.py) | 724 | | to_pandas | +| [preprocessing/resampling.py](../../../skyulf-core/skyulf/preprocessing/resampling.py) | 455 | Oversampling, Undersampling | to_pandas | +| [preprocessing/scaling/__init__.py](../../../skyulf-core/skyulf/preprocessing/scaling/__init__.py) | 29 | | | +| [preprocessing/scaling/_common.py](../../../skyulf-core/skyulf/preprocessing/scaling/_common.py) | 54 | | | +| [preprocessing/scaling/maxabs.py](../../../skyulf-core/skyulf/preprocessing/scaling/maxabs.py) | 119 | MaxAbsScaler | to_numpy | +| [preprocessing/scaling/minmax.py](../../../skyulf-core/skyulf/preprocessing/scaling/minmax.py) | 125 | MinMaxScaler | to_numpy | +| [preprocessing/scaling/robust.py](../../../skyulf-core/skyulf/preprocessing/scaling/robust.py) | 158 | RobustScaler | to_numpy | +| [preprocessing/scaling/standard.py](../../../skyulf-core/skyulf/preprocessing/scaling/standard.py) | 177 | StandardScaler | to_numpy | +| [preprocessing/split.py](../../../skyulf-core/skyulf/preprocessing/split.py) | 593 | Split, TrainTestSplitter, feature_target_split | to_pandas, to_numpy | +| [preprocessing/time_series/__init__.py](../../../skyulf-core/skyulf/preprocessing/time_series/__init__.py) | 23 | | | +| [preprocessing/time_series/_common.py](../../../skyulf-core/skyulf/preprocessing/time_series/_common.py) | 112 | | to_numpy, iloc | +| [preprocessing/time_series/date_features.py](../../../skyulf-core/skyulf/preprocessing/time_series/date_features.py) | 202 | DateFeatures | | +| [preprocessing/time_series/lag.py](../../../skyulf-core/skyulf/preprocessing/time_series/lag.py) | 148 | LagFeatures | to_numpy, iloc | +| [preprocessing/time_series/rolling.py](../../../skyulf-core/skyulf/preprocessing/time_series/rolling.py) | 194 | RollingAggregate | | +| [preprocessing/transformations/__init__.py](../../../skyulf-core/skyulf/preprocessing/transformations/__init__.py) | 19 | | | +| [preprocessing/transformations/_ops.py](../../../skyulf-core/skyulf/preprocessing/transformations/_ops.py) | 93 | | | +| [preprocessing/transformations/_power_common.py](../../../skyulf-core/skyulf/preprocessing/transformations/_power_common.py) | 69 | | | +| [preprocessing/transformations/general.py](../../../skyulf-core/skyulf/preprocessing/transformations/general.py) | 269 | GeneralTransformation | to_pandas, to_numpy | +| [preprocessing/transformations/power.py](../../../skyulf-core/skyulf/preprocessing/transformations/power.py) | 198 | PowerTransformer | to_pandas, to_numpy | +| [preprocessing/transformations/simple.py](../../../skyulf-core/skyulf/preprocessing/transformations/simple.py) | 116 | SimpleTransformation | | +| [preprocessing/vectorization/__init__.py](../../../skyulf-core/skyulf/preprocessing/vectorization/__init__.py) | 31 | | | +| [preprocessing/vectorization/_common.py](../../../skyulf-core/skyulf/preprocessing/vectorization/_common.py) | 327 | | to_pandas, toarray, to_list | +| [preprocessing/vectorization/count_vectorizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/count_vectorizer.py) | 175 | count_vectorizer | toarray | +| [preprocessing/vectorization/hashing_vectorizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/hashing_vectorizer.py) | 160 | hashing_vectorizer | | +| [preprocessing/vectorization/sentence_embedder.py](../../../skyulf-core/skyulf/preprocessing/vectorization/sentence_embedder.py) | 252 | sentence_embedder | to_list | +| [preprocessing/vectorization/tfidf_vectorizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/tfidf_vectorizer.py) | 169 | tfidf_vectorizer | | +| [preprocessing/vectorization/tokenizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/tokenizer.py) | 204 | tokenizer | to_list | +| [profiling/__init__.py](../../../skyulf-core/skyulf/profiling/__init__.py) | 43 | | | +| [profiling/_analyzer/__init__.py](../../../skyulf-core/skyulf/profiling/_analyzer/__init__.py) | 36 | | | +| [profiling/_analyzer/_utils.py](../../../skyulf-core/skyulf/profiling/_analyzer/_utils.py) | 114 | | collect( | +| [profiling/_analyzer/categorical.py](../../../skyulf-core/skyulf/profiling/_analyzer/categorical.py) | 36 | | | +| [profiling/_analyzer/causal.py](../../../skyulf-core/skyulf/profiling/_analyzer/causal.py) | 157 | | to_numpy | +| [profiling/_analyzer/column.py](../../../skyulf-core/skyulf/profiling/_analyzer/column.py) | 356 | | to_numpy | +| [profiling/_analyzer/dates.py](../../../skyulf-core/skyulf/profiling/_analyzer/dates.py) | 181 | | | +| [profiling/_analyzer/decomposition.py](../../../skyulf-core/skyulf/profiling/_analyzer/decomposition.py) | 230 | | iter_rows | +| [profiling/_analyzer/geo.py](../../../skyulf-core/skyulf/profiling/_analyzer/geo.py) | 162 | | collect( | +| [profiling/_analyzer/multivariate.py](../../../skyulf-core/skyulf/profiling/_analyzer/multivariate.py) | 418 | | to_numpy, to_list | +| [profiling/_analyzer/numeric.py](../../../skyulf-core/skyulf/profiling/_analyzer/numeric.py) | 141 | | to_numpy | +| [profiling/_analyzer/recommendations.py](../../../skyulf-core/skyulf/profiling/_analyzer/recommendations.py) | 283 | | to_list, collect( | +| [profiling/_analyzer/rules.py](../../../skyulf-core/skyulf/profiling/_analyzer/rules.py) | 372 | | to_numpy, to_list | +| [profiling/_analyzer/target.py](../../../skyulf-core/skyulf/profiling/_analyzer/target.py) | 231 | | iter_rows, collect( | +| [profiling/_analyzer/temporal.py](../../../skyulf-core/skyulf/profiling/_analyzer/temporal.py) | 286 | | to_numpy, iter_rows, collect( | +| [profiling/_analyzer/text.py](../../../skyulf-core/skyulf/profiling/_analyzer/text.py) | 136 | | to_list, iter_rows | +| [profiling/analyzer.py](../../../skyulf-core/skyulf/profiling/analyzer.py) | 680 | | collect( | +| [profiling/correlations.py](../../../skyulf-core/skyulf/profiling/correlations.py) | 184 | | collect( | +| [profiling/distributions.py](../../../skyulf-core/skyulf/profiling/distributions.py) | 87 | | iter_rows, collect( | +| [profiling/drift.py](../../../skyulf-core/skyulf/profiling/drift.py) | 630 | | to_numpy, to_list | +| [profiling/expect.py](../../../skyulf-core/skyulf/profiling/expect.py) | 237 | | to_pandas | +| [profiling/schemas.py](../../../skyulf-core/skyulf/profiling/schemas.py) | 466 | | | +| [profiling/visualizer.py](../../../skyulf-core/skyulf/profiling/visualizer.py) | 867 | | to_pandas | +| [registry.py](../../../skyulf-core/skyulf/registry.py) | 136 | | | +| [types.py](../../../skyulf-core/skyulf/types.py) | 52 | | | +| [utils.py](../../../skyulf-core/skyulf/utils.py) | 425 | | to_pandas | + +## Runtime node kayitlari + +Kurulu optional paketlere gore kayit sayisi degisebilir. Aliaslar dahildir. +Asagida bugunku ortamda gozlenen kayitlar vardir; Spark destek listesi degildir. + +| Kayit | Kategori | Kaynak | Veri ogreniyor | +| --- | --- | --- | --- | +| `AliasReplacement` | Cleaning | [preprocessing/cleaning/alias.py](../../../skyulf-core/skyulf/preprocessing/cleaning/alias.py) | False | +| `Casting` | Data Operations | [preprocessing/casting.py](../../../skyulf-core/skyulf/preprocessing/casting.py) | True | +| `CorrelationThreshold` | Feature Selection | [preprocessing/feature_selection/correlation.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/correlation.py) | True | +| `CustomBinning` | Preprocessing | [preprocessing/bucketing.py](../../../skyulf-core/skyulf/preprocessing/bucketing.py) | True | +| `DataSnapshot` | Inspection | [preprocessing/inspection.py](../../../skyulf-core/skyulf/preprocessing/inspection.py) | False | +| `DatasetProfile` | Inspection | [preprocessing/inspection.py](../../../skyulf-core/skyulf/preprocessing/inspection.py) | False | +| `DateFeatures` | Preprocessing | [preprocessing/time_series/date_features.py](../../../skyulf-core/skyulf/preprocessing/time_series/date_features.py) | False | +| `Deduplicate` | Data Operations | [preprocessing/drop_and_missing/deduplicate.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/deduplicate.py) | True | +| `DropMissingColumns` | Cleaning | [preprocessing/drop_and_missing/drop_columns.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/drop_columns.py) | True | +| `DropMissingRows` | Cleaning | [preprocessing/drop_and_missing/drop_rows.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/drop_rows.py) | False | +| `DummyEncoder` | Preprocessing | [preprocessing/encoding/dummy.py](../../../skyulf-core/skyulf/preprocessing/encoding/dummy.py) | True | +| `EllipticEnvelope` | Preprocessing | [preprocessing/outliers/elliptic.py](../../../skyulf-core/skyulf/preprocessing/outliers/elliptic.py) | True | +| `FeatureGeneration` | Feature Engineering | [preprocessing/feature_generation/generation.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py) | True | +| `FeatureGenerationNode` | Feature Engineering | [preprocessing/feature_generation/generation.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py) | True | +| `FeatureInteraction` | Feature Engineering | [preprocessing/feature_generation/interaction.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/interaction.py) | False | +| `FeatureMath` | Feature Engineering | [preprocessing/feature_generation/generation.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py) | True | +| `GeneralBinning` | Preprocessing | [preprocessing/bucketing.py](../../../skyulf-core/skyulf/preprocessing/bucketing.py) | True | +| `GeneralTransformation` | Preprocessing | [preprocessing/transformations/general.py](../../../skyulf-core/skyulf/preprocessing/transformations/general.py) | True | +| `GeoDistance` | Feature Engineering | [preprocessing/geo/distance.py](../../../skyulf-core/skyulf/preprocessing/geo/distance.py) | False | +| `H3Index` | Feature Engineering | [preprocessing/geo/h3_index.py](../../../skyulf-core/skyulf/preprocessing/geo/h3_index.py) | False | +| `HashEncoder` | Preprocessing | [preprocessing/encoding/hash.py](../../../skyulf-core/skyulf/preprocessing/encoding/hash.py) | True | +| `IQR` | Preprocessing | [preprocessing/outliers/iqr.py](../../../skyulf-core/skyulf/preprocessing/outliers/iqr.py) | True | +| `InvalidValueReplacement` | Cleaning | [preprocessing/cleaning/invalid_value.py](../../../skyulf-core/skyulf/preprocessing/cleaning/invalid_value.py) | False | +| `IterativeImputer` | Preprocessing | [preprocessing/imputation/iterative.py](../../../skyulf-core/skyulf/preprocessing/imputation/iterative.py) | True | +| `KBinsDiscretizer` | Preprocessing | [preprocessing/bucketing.py](../../../skyulf-core/skyulf/preprocessing/bucketing.py) | True | +| `KNNImputer` | Preprocessing | [preprocessing/imputation/knn.py](../../../skyulf-core/skyulf/preprocessing/imputation/knn.py) | True | +| `LabelEncoder` | Preprocessing | [preprocessing/encoding/label.py](../../../skyulf-core/skyulf/preprocessing/encoding/label.py) | True | +| `LagFeatures` | Preprocessing | [preprocessing/time_series/lag.py](../../../skyulf-core/skyulf/preprocessing/time_series/lag.py) | False | +| `ManualBounds` | Preprocessing | [preprocessing/outliers/manual_bounds.py](../../../skyulf-core/skyulf/preprocessing/outliers/manual_bounds.py) | False | +| `MaxAbsScaler` | Preprocessing | [preprocessing/scaling/maxabs.py](../../../skyulf-core/skyulf/preprocessing/scaling/maxabs.py) | True | +| `MinMaxScaler` | Preprocessing | [preprocessing/scaling/minmax.py](../../../skyulf-core/skyulf/preprocessing/scaling/minmax.py) | True | +| `MissingIndicator` | Feature Engineering | [preprocessing/drop_and_missing/missing_indicator.py](../../../skyulf-core/skyulf/preprocessing/drop_and_missing/missing_indicator.py) | True | +| `ModelBasedSelection` | Feature Selection | [preprocessing/feature_selection/model_based.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/model_based.py) | True | +| `OneHotEncoder` | Preprocessing | [preprocessing/encoding/one_hot.py](../../../skyulf-core/skyulf/preprocessing/encoding/one_hot.py) | True | +| `OrdinalEncoder` | Preprocessing | [preprocessing/encoding/ordinal.py](../../../skyulf-core/skyulf/preprocessing/encoding/ordinal.py) | True | +| `Oversampling` | Preprocessing | [preprocessing/resampling.py](../../../skyulf-core/skyulf/preprocessing/resampling.py) | True | +| `PolynomialFeatures` | Feature Engineering | [preprocessing/feature_generation/polynomial.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/polynomial.py) | True | +| `PolynomialFeaturesNode` | Feature Engineering | [preprocessing/feature_generation/polynomial.py](../../../skyulf-core/skyulf/preprocessing/feature_generation/polynomial.py) | True | +| `PowerTransformer` | Preprocessing | [preprocessing/transformations/power.py](../../../skyulf-core/skyulf/preprocessing/transformations/power.py) | True | +| `RobustScaler` | Preprocessing | [preprocessing/scaling/robust.py](../../../skyulf-core/skyulf/preprocessing/scaling/robust.py) | True | +| `RollingAggregate` | Preprocessing | [preprocessing/time_series/rolling.py](../../../skyulf-core/skyulf/preprocessing/time_series/rolling.py) | False | +| `SimpleImputer` | Preprocessing | [preprocessing/imputation/simple.py](../../../skyulf-core/skyulf/preprocessing/imputation/simple.py) | True | +| `SimpleTransformation` | Preprocessing | [preprocessing/transformations/simple.py](../../../skyulf-core/skyulf/preprocessing/transformations/simple.py) | False | +| `Split` | Data Operations | [preprocessing/split.py](../../../skyulf-core/skyulf/preprocessing/split.py) | False | +| `StandardScaler` | Preprocessing | [preprocessing/scaling/standard.py](../../../skyulf-core/skyulf/preprocessing/scaling/standard.py) | True | +| `TargetEncoder` | Preprocessing | [preprocessing/encoding/target.py](../../../skyulf-core/skyulf/preprocessing/encoding/target.py) | True | +| `TextCleaning` | Cleaning | [preprocessing/cleaning/text.py](../../../skyulf-core/skyulf/preprocessing/cleaning/text.py) | False | +| `TrainTestSplitter` | Data Operations | [preprocessing/split.py](../../../skyulf-core/skyulf/preprocessing/split.py) | False | +| `Undersampling` | Preprocessing | [preprocessing/resampling.py](../../../skyulf-core/skyulf/preprocessing/resampling.py) | True | +| `UnivariateSelection` | Feature Selection | [preprocessing/feature_selection/univariate.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/univariate.py) | True | +| `ValueReplacement` | Cleaning | [preprocessing/cleaning/value_replacement.py](../../../skyulf-core/skyulf/preprocessing/cleaning/value_replacement.py) | False | +| `VarianceThreshold` | Feature Selection | [preprocessing/feature_selection/variance.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/variance.py) | True | +| `WOEEncoder` | Preprocessing | [preprocessing/encoding/woe.py](../../../skyulf-core/skyulf/preprocessing/encoding/woe.py) | True | +| `Winsorize` | Preprocessing | [preprocessing/outliers/winsorize.py](../../../skyulf-core/skyulf/preprocessing/outliers/winsorize.py) | True | +| `ZScore` | Preprocessing | [preprocessing/outliers/zscore.py](../../../skyulf-core/skyulf/preprocessing/outliers/zscore.py) | True | +| `adaboost_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `adaboost_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `bernoulli_nb` | Modeling | [modeling/naive_bayes.py](../../../skyulf-core/skyulf/modeling/naive_bayes.py) | True | +| `birch` | Modeling | [modeling/clustering.py](../../../skyulf-core/skyulf/modeling/clustering.py) | True | +| `calibrated_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `count_vectorizer` | Text | [preprocessing/vectorization/count_vectorizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/count_vectorizer.py) | True | +| `decision_tree_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `decision_tree_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `elasticnet_regression` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `extra_trees_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `extra_trees_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `feature_selection` | Feature Selection | [preprocessing/feature_selection/facade.py](../../../skyulf-core/skyulf/preprocessing/feature_selection/facade.py) | True | +| `feature_target_split` | Data Operations | [preprocessing/split.py](../../../skyulf-core/skyulf/preprocessing/split.py) | False | +| `gaussian_mixture` | Modeling | [modeling/clustering.py](../../../skyulf-core/skyulf/modeling/clustering.py) | True | +| `gaussian_nb` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `gradient_boosting_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `gradient_boosting_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `hashing_vectorizer` | Text | [preprocessing/vectorization/hashing_vectorizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/hashing_vectorizer.py) | False | +| `hist_gradient_boosting_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `hist_gradient_boosting_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `k_neighbors_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `k_neighbors_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `kmeans` | Modeling | [modeling/clustering.py](../../../skyulf-core/skyulf/modeling/clustering.py) | True | +| `lasso_regression` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `lgbm_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `lgbm_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `linear_regression` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `logistic_regression` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `minibatch_kmeans` | Modeling | [modeling/clustering.py](../../../skyulf-core/skyulf/modeling/clustering.py) | True | +| `multinomial_nb` | Modeling | [modeling/naive_bayes.py](../../../skyulf-core/skyulf/modeling/naive_bayes.py) | True | +| `random_forest_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `random_forest_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `ridge_regression` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `sentence_embedder` | Text | [preprocessing/vectorization/sentence_embedder.py](../../../skyulf-core/skyulf/preprocessing/vectorization/sentence_embedder.py) | False | +| `sgd_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `stacking_classifier` | Ensemble | [modeling/ensemble.py](../../../skyulf-core/skyulf/modeling/ensemble.py) | True | +| `stacking_regressor` | Ensemble | [modeling/ensemble.py](../../../skyulf-core/skyulf/modeling/ensemble.py) | True | +| `svc` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `svr` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | +| `tfidf_vectorizer` | Text | [preprocessing/vectorization/tfidf_vectorizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/tfidf_vectorizer.py) | True | +| `tokenizer` | Text | [preprocessing/vectorization/tokenizer.py](../../../skyulf-core/skyulf/preprocessing/vectorization/tokenizer.py) | False | +| `voting_classifier` | Ensemble | [modeling/ensemble.py](../../../skyulf-core/skyulf/modeling/ensemble.py) | True | +| `voting_regressor` | Ensemble | [modeling/ensemble.py](../../../skyulf-core/skyulf/modeling/ensemble.py) | True | +| `xgboost_classifier` | Modeling | [modeling/classification.py](../../../skyulf-core/skyulf/modeling/classification.py) | True | +| `xgboost_regressor` | Modeling | [modeling/regression.py](../../../skyulf-core/skyulf/modeling/regression.py) | True | + +## Test dosyasi envanteri + +269 test dosyasi. Tum core pytest sonucu ana rapordadir. + +- `tests/integration/test_alias_nontext_contract.py` ? +- `tests/integration/test_arithmetic_missing_values.py` ? +- `tests/integration/test_binning_contract_regressions.py` ? +- `tests/integration/test_binning_missing_labels.py` ? +- [tests/integration/test_bucketing.py](../../../skyulf-core/tests/integration/test_bucketing.py) +- [tests/integration/test_casting.py](../../../skyulf-core/tests/integration/test_casting.py) +- `tests/integration/test_casting_text_inputs.py` ? +- [tests/integration/test_classification_gaps.py](../../../skyulf-core/tests/integration/test_classification_gaps.py) +- [tests/integration/test_cleaning_alias.py](../../../skyulf-core/tests/integration/test_cleaning_alias.py) +- [tests/integration/test_cleaning_invalid_value.py](../../../skyulf-core/tests/integration/test_cleaning_invalid_value.py) +- [tests/integration/test_cleaning_text.py](../../../skyulf-core/tests/integration/test_cleaning_text.py) +- [tests/integration/test_clustering.py](../../../skyulf-core/tests/integration/test_clustering.py) +- [tests/integration/test_core_pipeline_tuning_leakage.py](../../../skyulf-core/tests/integration/test_core_pipeline_tuning_leakage.py) +- [tests/integration/test_cross_validation.py](../../../skyulf-core/tests/integration/test_cross_validation.py) +- `tests/integration/test_cross_validation_date_objects.py` ? +- [tests/integration/test_cross_validation_time_sort_integrity.py](../../../skyulf-core/tests/integration/test_cross_validation_time_sort_integrity.py) +- [tests/integration/test_cv_per_fold_refit.py](../../../skyulf-core/tests/integration/test_cv_per_fold_refit.py) +- `tests/integration/test_date_features_timezone.py` ? +- `tests/integration/test_decimal_numeric.py` ? +- [tests/integration/test_drop_and_missing_gaps.py](../../../skyulf-core/tests/integration/test_drop_and_missing_gaps.py) +- `tests/integration/test_drop_missing_rows_policy.py` ? +- [tests/integration/test_drop_rows.py](../../../skyulf-core/tests/integration/test_drop_rows.py) +- [tests/integration/test_encoding_dummy.py](../../../skyulf-core/tests/integration/test_encoding_dummy.py) +- [tests/integration/test_encoding_hash.py](../../../skyulf-core/tests/integration/test_encoding_hash.py) +- [tests/integration/test_encoding_label.py](../../../skyulf-core/tests/integration/test_encoding_label.py) +- [tests/integration/test_encoding_one_hot.py](../../../skyulf-core/tests/integration/test_encoding_one_hot.py) +- [tests/integration/test_encoding_ordinal.py](../../../skyulf-core/tests/integration/test_encoding_ordinal.py) +- [tests/integration/test_encoding_target.py](../../../skyulf-core/tests/integration/test_encoding_target.py) +- [tests/integration/test_encoding_woe.py](../../../skyulf-core/tests/integration/test_encoding_woe.py) +- [tests/integration/test_ensemble.py](../../../skyulf-core/tests/integration/test_ensemble.py) +- `tests/integration/test_ensemble_calibrated_tuning_refit.py` ? +- [tests/integration/test_ensemble_config_immutability.py](../../../skyulf-core/tests/integration/test_ensemble_config_immutability.py) +- `tests/integration/test_enum_text_cleaning.py` ? +- `tests/integration/test_evaluation_class_axis.py` ? +- [tests/integration/test_evaluation_classification.py](../../../skyulf-core/tests/integration/test_evaluation_classification.py) +- [tests/integration/test_evaluation_regression.py](../../../skyulf-core/tests/integration/test_evaluation_regression.py) +- `tests/integration/test_extended_pruning_support.py` ? +- `tests/integration/test_feature_generation_datetime_names.py` ? +- [tests/integration/test_feature_generation_full.py](../../../skyulf-core/tests/integration/test_feature_generation_full.py) +- [tests/integration/test_feature_generation_gaps.py](../../../skyulf-core/tests/integration/test_feature_generation_gaps.py) +- [tests/integration/test_feature_generation_group_agg.py](../../../skyulf-core/tests/integration/test_feature_generation_group_agg.py) +- [tests/integration/test_feature_generation_operation_validation.py](../../../skyulf-core/tests/integration/test_feature_generation_operation_validation.py) +- [tests/integration/test_feature_generation_polars_ops.py](../../../skyulf-core/tests/integration/test_feature_generation_polars_ops.py) +- [tests/integration/test_feature_generation_ratio_missing.py](../../../skyulf-core/tests/integration/test_feature_generation_ratio_missing.py) +- [tests/integration/test_feature_generation_ratio_sign.py](../../../skyulf-core/tests/integration/test_feature_generation_ratio_sign.py) +- [tests/integration/test_feature_interaction.py](../../../skyulf-core/tests/integration/test_feature_interaction.py) +- [tests/integration/test_feature_selection_common.py](../../../skyulf-core/tests/integration/test_feature_selection_common.py) +- [tests/integration/test_feature_selection_facade.py](../../../skyulf-core/tests/integration/test_feature_selection_facade.py) +- [tests/integration/test_feature_selection_gaps.py](../../../skyulf-core/tests/integration/test_feature_selection_gaps.py) +- `tests/integration/test_feature_selection_target_dtypes.py` ? +- [tests/integration/test_geo_nodes.py](../../../skyulf-core/tests/integration/test_geo_nodes.py) +- `tests/integration/test_group_aggregate_null_keys.py` ? +- [tests/integration/test_imputation_common_knn_iterative_simple.py](../../../skyulf-core/tests/integration/test_imputation_common_knn_iterative_simple.py) +- `tests/integration/test_imputation_text_column_contract.py` ? +- [tests/integration/test_inspection.py](../../../skyulf-core/tests/integration/test_inspection.py) +- `tests/integration/test_invalid_value_integer_precision.py` ? +- `tests/integration/test_invalid_value_numeric_contract.py` ? +- [tests/integration/test_leakage_fixture_contract.py](../../../skyulf-core/tests/integration/test_leakage_fixture_contract.py) +- [tests/integration/test_leakage_operation_contract.py](../../../skyulf-core/tests/integration/test_leakage_operation_contract.py) +- `tests/integration/test_logistic_elasticnet_defaults.py` ? +- `tests/integration/test_logistic_penalty_consistency.py` ? +- `tests/integration/test_model_seal_supported_state.py` ? +- [tests/integration/test_modeling_all.py](../../../skyulf-core/tests/integration/test_modeling_all.py) +- [tests/integration/test_naive_bayes.py](../../../skyulf-core/tests/integration/test_naive_bayes.py) +- `tests/integration/test_optuna_fold_pruning.py` ? +- `tests/integration/test_optuna_incremental_pruning.py` ? +- `tests/integration/test_optuna_native_pruning.py` ? +- `tests/integration/test_optuna_public_pruning.py` ? +- [tests/integration/test_outliers_elliptic_winsorize_zscore_iqr.py](../../../skyulf-core/tests/integration/test_outliers_elliptic_winsorize_zscore_iqr.py) +- [tests/integration/test_outliers_manual_bounds.py](../../../skyulf-core/tests/integration/test_outliers_manual_bounds.py) +- [tests/integration/test_pipeline_integration_modeling.py](../../../skyulf-core/tests/integration/test_pipeline_integration_modeling.py) +- [tests/integration/test_pipeline_integration_multi_model.py](../../../skyulf-core/tests/integration/test_pipeline_integration_multi_model.py) +- [tests/integration/test_pipeline_integration_preprocessing.py](../../../skyulf-core/tests/integration/test_pipeline_integration_preprocessing.py) +- [tests/integration/test_pipeline_integration_tuning.py](../../../skyulf-core/tests/integration/test_pipeline_integration_tuning.py) +- `tests/integration/test_prediction_row_contract.py` ? +- `tests/integration/test_prediction_temporal_order.py` ? +- [tests/integration/test_preprocessing_behavioral_reaudit.py](../../../skyulf-core/tests/integration/test_preprocessing_behavioral_reaudit.py) +- [tests/integration/test_preprocessing_time_series_common.py](../../../skyulf-core/tests/integration/test_preprocessing_time_series_common.py) +- [tests/integration/test_profiling_analyzer.py](../../../skyulf-core/tests/integration/test_profiling_analyzer.py) +- [tests/integration/test_profiling_column_name_collisions.py](../../../skyulf-core/tests/integration/test_profiling_column_name_collisions.py) +- `tests/integration/test_profiling_constant_columns.py` ? +- `tests/integration/test_profiling_correlation_omissions.py` ? +- [tests/integration/test_profiling_correlations_distributions.py](../../../skyulf-core/tests/integration/test_profiling_correlations_distributions.py) +- [tests/integration/test_profiling_dates.py](../../../skyulf-core/tests/integration/test_profiling_dates.py) +- `tests/integration/test_profiling_dates_lossless.py` ? +- [tests/integration/test_profiling_decomposition.py](../../../skyulf-core/tests/integration/test_profiling_decomposition.py) +- `tests/integration/test_profiling_decomposition_missing.py` ? +- `tests/integration/test_profiling_decomposition_names.py` ? +- [tests/integration/test_profiling_drift.py](../../../skyulf-core/tests/integration/test_profiling_drift.py) +- `tests/integration/test_profiling_drift_dtypes.py` ? +- [tests/integration/test_profiling_geo.py](../../../skyulf-core/tests/integration/test_profiling_geo.py) +- [tests/integration/test_profiling_multivariate.py](../../../skyulf-core/tests/integration/test_profiling_multivariate.py) +- [tests/integration/test_profiling_null_enum.py](../../../skyulf-core/tests/integration/test_profiling_null_enum.py) +- [tests/integration/test_profiling_numeric.py](../../../skyulf-core/tests/integration/test_profiling_numeric.py) +- `tests/integration/test_profiling_outlier_population.py` ? +- `tests/integration/test_profiling_recommendation_safety.py` ? +- [tests/integration/test_profiling_recommendations.py](../../../skyulf-core/tests/integration/test_profiling_recommendations.py) +- [tests/integration/test_profiling_repeated_exclusions.py](../../../skyulf-core/tests/integration/test_profiling_repeated_exclusions.py) +- `tests/integration/test_profiling_repeated_filters.py` ? +- [tests/integration/test_profiling_rules.py](../../../skyulf-core/tests/integration/test_profiling_rules.py) +- `tests/integration/test_profiling_seasonality_measure.py` ? +- `tests/integration/test_profiling_string_categories.py` ? +- [tests/integration/test_profiling_target.py](../../../skyulf-core/tests/integration/test_profiling_target.py) +- [tests/integration/test_profiling_target_contract.py](../../../skyulf-core/tests/integration/test_profiling_target_contract.py) +- [tests/integration/test_profiling_target_outlier_regressions.py](../../../skyulf-core/tests/integration/test_profiling_target_outlier_regressions.py) +- `tests/integration/test_profiling_target_recommendation_inference.py` ? +- [tests/integration/test_profiling_temporal.py](../../../skyulf-core/tests/integration/test_profiling_temporal.py) +- `tests/integration/test_profiling_temporal_decomposition.py` ? +- [tests/integration/test_profiling_temporal_missing_values.py](../../../skyulf-core/tests/integration/test_profiling_temporal_missing_values.py) +- [tests/integration/test_profiling_text.py](../../../skyulf-core/tests/integration/test_profiling_text.py) +- `tests/integration/test_profiling_unsupported_dtypes.py` ? +- `tests/integration/test_pruning_capability.py` ? +- `tests/integration/test_release_tuning_roundtrip.py` ? +- [tests/integration/test_repeated_split_boundary.py](../../../skyulf-core/tests/integration/test_repeated_split_boundary.py) +- `tests/integration/test_resampling_advanced_settings.py` ? +- [tests/integration/test_row_filter_column_collisions.py](../../../skyulf-core/tests/integration/test_row_filter_column_collisions.py) +- [tests/integration/test_scaling.py](../../../skyulf-core/tests/integration/test_scaling.py) +- `tests/integration/test_scaling_range_validation.py` ? +- [tests/integration/test_sentence_embedder.py](../../../skyulf-core/tests/integration/test_sentence_embedder.py) +- [tests/integration/test_split.py](../../../skyulf-core/tests/integration/test_split.py) +- `tests/integration/test_split_config_warnings.py` ? +- [tests/integration/test_stateful_estimator_tuple_targets.py](../../../skyulf-core/tests/integration/test_stateful_estimator_tuple_targets.py) +- `tests/integration/test_temporal_tuning_boundaries.py` ? +- [tests/integration/test_text_target_context.py](../../../skyulf-core/tests/integration/test_text_target_context.py) +- [tests/integration/test_time_series_gaps.py](../../../skyulf-core/tests/integration/test_time_series_gaps.py) +- [tests/integration/test_time_series_missing_values.py](../../../skyulf-core/tests/integration/test_time_series_missing_values.py) +- [tests/integration/test_time_series_nodes.py](../../../skyulf-core/tests/integration/test_time_series_nodes.py) +- [tests/integration/test_transformations_general.py](../../../skyulf-core/tests/integration/test_transformations_general.py) +- [tests/integration/test_transformations_power_simple.py](../../../skyulf-core/tests/integration/test_transformations_power_simple.py) +- [tests/integration/test_tuning.py](../../../skyulf-core/tests/integration/test_tuning.py) +- `tests/integration/test_tuning_class_axis.py` ? +- `tests/integration/test_tuning_class_weights.py` ? +- `tests/integration/test_tuning_filtered_validation.py` ? +- `tests/integration/test_tuning_native_missing_values.py` ? +- [tests/integration/test_tuning_per_fold_refit.py](../../../skyulf-core/tests/integration/test_tuning_per_fold_refit.py) +- `tests/integration/test_tuning_positive_class.py` ? +- [tests/integration/test_tuning_time_series_holdout.py](../../../skyulf-core/tests/integration/test_tuning_time_series_holdout.py) +- [tests/integration/test_value_replacement.py](../../../skyulf-core/tests/integration/test_value_replacement.py) +- [tests/integration/test_vectorization.py](../../../skyulf-core/tests/integration/test_vectorization.py) +- [tests/integration/test_woe_and_calibration.py](../../../skyulf-core/tests/integration/test_woe_and_calibration.py) +- [tests/integration/test_wrapped_polars_frames.py](../../../skyulf-core/tests/integration/test_wrapped_polars_frames.py) +- [tests/integration/test_xy_row_alignment.py](../../../skyulf-core/tests/integration/test_xy_row_alignment.py) +- [tests/test_preprocessing_split_callback.py](../../../skyulf-core/tests/test_preprocessing_split_callback.py) +- [tests/unit/test_all_nodes_smoke.py](../../../skyulf-core/tests/unit/test_all_nodes_smoke.py) +- [tests/unit/test_artifact_shapes.py](../../../skyulf-core/tests/unit/test_artifact_shapes.py) +- [tests/unit/test_artifact_snapshots.py](../../../skyulf-core/tests/unit/test_artifact_snapshots.py) +- [tests/unit/test_benchmarks.py](../../../skyulf-core/tests/unit/test_benchmarks.py) +- [tests/unit/test_boosting_progress.py](../../../skyulf-core/tests/unit/test_boosting_progress.py) +- [tests/unit/test_calendar_and_row_target_contract.py](../../../skyulf-core/tests/unit/test_calendar_and_row_target_contract.py) +- `tests/unit/test_calibrated_classifier_random_state.py` ? +- [tests/unit/test_cleaning_operation_leakage.py](../../../skyulf-core/tests/unit/test_cleaning_operation_leakage.py) +- [tests/unit/test_core_compute.py](../../../skyulf-core/tests/unit/test_core_compute.py) +- [tests/unit/test_core_model_registry.py](../../../skyulf-core/tests/unit/test_core_model_registry.py) +- [tests/unit/test_core_schema.py](../../../skyulf-core/tests/unit/test_core_schema.py) +- [tests/unit/test_core_seams.py](../../../skyulf-core/tests/unit/test_core_seams.py) +- [tests/unit/test_core_serialization.py](../../../skyulf-core/tests/unit/test_core_serialization.py) +- [tests/unit/test_data_catalog.py](../../../skyulf-core/tests/unit/test_data_catalog.py) +- [tests/unit/test_dataset.py](../../../skyulf-core/tests/unit/test_dataset.py) +- [tests/unit/test_deprecation.py](../../../skyulf-core/tests/unit/test_deprecation.py) +- `tests/unit/test_eda_profile_alias.py` ? +- [tests/unit/test_encoding_category_keys_regression_20260909.py](../../../skyulf-core/tests/unit/test_encoding_category_keys_regression_20260909.py) +- [tests/unit/test_encoding_common.py](../../../skyulf-core/tests/unit/test_encoding_common.py) +- [tests/unit/test_encoding_operation_leakage.py](../../../skyulf-core/tests/unit/test_encoding_operation_leakage.py) +- `tests/unit/test_encoding_output_names_regression_20260912.py` ? +- `tests/unit/test_encoding_temporal_enum_regression_20260912.py` ? +- [tests/unit/test_encoding_text_deep_audit_20260908.py](../../../skyulf-core/tests/unit/test_encoding_text_deep_audit_20260908.py) +- `tests/unit/test_engine_context.py` ? +- `tests/unit/test_engine_empty_frames.py` ? +- [tests/unit/test_engine_parity.py](../../../skyulf-core/tests/unit/test_engine_parity.py) +- `tests/unit/test_engine_wrapper_serialization.py` ? +- [tests/unit/test_engines_pandas.py](../../../skyulf-core/tests/unit/test_engines_pandas.py) +- [tests/unit/test_engines_polars.py](../../../skyulf-core/tests/unit/test_engines_polars.py) +- [tests/unit/test_engines_registry.py](../../../skyulf-core/tests/unit/test_engines_registry.py) +- [tests/unit/test_engines_sklearn_bridge.py](../../../skyulf-core/tests/unit/test_engines_sklearn_bridge.py) +- [tests/unit/test_ensemble_nodes.py](../../../skyulf-core/tests/unit/test_ensemble_nodes.py) +- [tests/unit/test_evaluation_clustering.py](../../../skyulf-core/tests/unit/test_evaluation_clustering.py) +- [tests/unit/test_evaluation_clustering_polars.py](../../../skyulf-core/tests/unit/test_evaluation_clustering_polars.py) +- [tests/unit/test_evaluation_common.py](../../../skyulf-core/tests/unit/test_evaluation_common.py) +- [tests/unit/test_evaluation_metrics.py](../../../skyulf-core/tests/unit/test_evaluation_metrics.py) +- [tests/unit/test_evaluation_thresholds.py](../../../skyulf-core/tests/unit/test_evaluation_thresholds.py) +- [tests/unit/test_expect.py](../../../skyulf-core/tests/unit/test_expect.py) +- `tests/unit/test_expect_empty.py` ? +- [tests/unit/test_explainability.py](../../../skyulf-core/tests/unit/test_explainability.py) +- [tests/unit/test_feature_operation_leakage.py](../../../skyulf-core/tests/unit/test_feature_operation_leakage.py) +- [tests/unit/test_fold_audit.py](../../../skyulf-core/tests/unit/test_fold_audit.py) +- [tests/unit/test_fold_merge_guide_example.py](../../../skyulf-core/tests/unit/test_fold_merge_guide_example.py) +- [tests/unit/test_fold_merged_adapter.py](../../../skyulf-core/tests/unit/test_fold_merged_adapter.py) +- `tests/unit/test_fold_merged_row_contract.py` ? +- [tests/unit/test_fold_pipeline.py](../../../skyulf-core/tests/unit/test_fold_pipeline.py) +- [tests/unit/test_fold_preprocessing.py](../../../skyulf-core/tests/unit/test_fold_preprocessing.py) +- `tests/unit/test_fold_scoring.py` ? +- `tests/unit/test_general_transformation_sequential_fit.py` ? +- `tests/unit/test_geo_distance_schema.py` ? +- [tests/unit/test_hyperparameters_class_weight.py](../../../skyulf-core/tests/unit/test_hyperparameters_class_weight.py) +- [tests/unit/test_hyperparameters_random_state.py](../../../skyulf-core/tests/unit/test_hyperparameters_random_state.py) +- [tests/unit/test_hyperparameters_registry.py](../../../skyulf-core/tests/unit/test_hyperparameters_registry.py) +- [tests/unit/test_infer_output_schema.py](../../../skyulf-core/tests/unit/test_infer_output_schema.py) +- `tests/unit/test_label_target_containers_regression_20260912.py` ? +- [tests/unit/test_leakage_enforcement.py](../../../skyulf-core/tests/unit/test_leakage_enforcement.py) +- [tests/unit/test_leakage_safety_validation.py](../../../skyulf-core/tests/unit/test_leakage_safety_validation.py) +- `tests/unit/test_lightgbm_subsampling.py` ? +- `tests/unit/test_manual_bounds_missing_columns.py` ? +- [tests/unit/test_modeling.py](../../../skyulf-core/tests/unit/test_modeling.py) +- [tests/unit/test_modeling_base.py](../../../skyulf-core/tests/unit/test_modeling_base.py) +- [tests/unit/test_modeling_classification_gaps.py](../../../skyulf-core/tests/unit/test_modeling_classification_gaps.py) +- [tests/unit/test_modeling_clustering.py](../../../skyulf-core/tests/unit/test_modeling_clustering.py) +- [tests/unit/test_modeling_ensemble_gaps.py](../../../skyulf-core/tests/unit/test_modeling_ensemble_gaps.py) +- [tests/unit/test_modeling_naive_bayes.py](../../../skyulf-core/tests/unit/test_modeling_naive_bayes.py) +- [tests/unit/test_modeling_regression_gaps.py](../../../skyulf-core/tests/unit/test_modeling_regression_gaps.py) +- [tests/unit/test_modeling_sklearn_wrapper.py](../../../skyulf-core/tests/unit/test_modeling_sklearn_wrapper.py) +- [tests/unit/test_multi_output_audit.py](../../../skyulf-core/tests/unit/test_multi_output_audit.py) +- [tests/unit/test_no_inline_engine_dispatch.py](../../../skyulf-core/tests/unit/test_no_inline_engine_dispatch.py) +- [tests/unit/test_numeric_preprocessing_behavior_audit.py](../../../skyulf-core/tests/unit/test_numeric_preprocessing_behavior_audit.py) +- [tests/unit/test_outlier_failure_branches.py](../../../skyulf-core/tests/unit/test_outlier_failure_branches.py) +- [tests/unit/test_patch_coverage_core_round5.py](../../../skyulf-core/tests/unit/test_patch_coverage_core_round5.py) +- [tests/unit/test_patch_coverage_core_round6.py](../../../skyulf-core/tests/unit/test_patch_coverage_core_round6.py) +- [tests/unit/test_pipeline.py](../../../skyulf-core/tests/unit/test_pipeline.py) +- [tests/unit/test_pipeline_card.py](../../../skyulf-core/tests/unit/test_pipeline_card.py) +- [tests/unit/test_pipeline_config_validation.py](../../../skyulf-core/tests/unit/test_pipeline_config_validation.py) +- [tests/unit/test_pipeline_coverage.py](../../../skyulf-core/tests/unit/test_pipeline_coverage.py) +- [tests/unit/test_pipeline_describe.py](../../../skyulf-core/tests/unit/test_pipeline_describe.py) +- [tests/unit/test_pipeline_fit_lifecycle.py](../../../skyulf-core/tests/unit/test_pipeline_fit_lifecycle.py) +- [tests/unit/test_pipeline_seal.py](../../../skyulf-core/tests/unit/test_pipeline_seal.py) +- [tests/unit/test_pipeline_split_extraction.py](../../../skyulf-core/tests/unit/test_pipeline_split_extraction.py) +- `tests/unit/test_pipeline_threshold_alignment.py` ? +- `tests/unit/test_pipeline_threshold_fingerprint.py` ? +- [tests/unit/test_pipeline_threshold_tuning.py](../../../skyulf-core/tests/unit/test_pipeline_threshold_tuning.py) +- [tests/unit/test_polynomial_leakage_policy.py](../../../skyulf-core/tests/unit/test_polynomial_leakage_policy.py) +- [tests/unit/test_postfix_imputation_selection_leakage.py](../../../skyulf-core/tests/unit/test_postfix_imputation_selection_leakage.py) +- [tests/unit/test_preprocessing.py](../../../skyulf-core/tests/unit/test_preprocessing.py) +- [tests/unit/test_preprocessing_base.py](../../../skyulf-core/tests/unit/test_preprocessing_base.py) +- [tests/unit/test_preprocessing_dispatcher.py](../../../skyulf-core/tests/unit/test_preprocessing_dispatcher.py) +- [tests/unit/test_preprocessing_helpers.py](../../../skyulf-core/tests/unit/test_preprocessing_helpers.py) +- [tests/unit/test_preprocessing_inspection.py](../../../skyulf-core/tests/unit/test_preprocessing_inspection.py) +- [tests/unit/test_preprocessing_nodes.py](../../../skyulf-core/tests/unit/test_preprocessing_nodes.py) +- [tests/unit/test_preprocessing_pipeline.py](../../../skyulf-core/tests/unit/test_preprocessing_pipeline.py) +- `tests/unit/test_preprocessing_refactor_branches.py` ? +- [tests/unit/test_preprocessing_selection_leakage.py](../../../skyulf-core/tests/unit/test_preprocessing_selection_leakage.py) +- [tests/unit/test_profiling_column.py](../../../skyulf-core/tests/unit/test_profiling_column.py) +- [tests/unit/test_profiling_expect_gap.py](../../../skyulf-core/tests/unit/test_profiling_expect_gap.py) +- [tests/unit/test_profiling_geo_exclusions.py](../../../skyulf-core/tests/unit/test_profiling_geo_exclusions.py) +- `tests/unit/test_profiling_json_contract.py` ? +- `tests/unit/test_profiling_outlier_summary.py` ? +- `tests/unit/test_profiling_timeseries_alignment.py` ? +- [tests/unit/test_profiling_utils.py](../../../skyulf-core/tests/unit/test_profiling_utils.py) +- [tests/unit/test_profiling_visualizer.py](../../../skyulf-core/tests/unit/test_profiling_visualizer.py) +- [tests/unit/test_profiling_visualizer_labels.py](../../../skyulf-core/tests/unit/test_profiling_visualizer_labels.py) +- [tests/unit/test_protocols.py](../../../skyulf-core/tests/unit/test_protocols.py) +- [tests/unit/test_public_api_exports.py](../../../skyulf-core/tests/unit/test_public_api_exports.py) +- [tests/unit/test_pyarrow_dtypes.py](../../../skyulf-core/tests/unit/test_pyarrow_dtypes.py) +- [tests/unit/test_registry_contract.py](../../../skyulf-core/tests/unit/test_registry_contract.py) +- [tests/unit/test_registry_toplevel.py](../../../skyulf-core/tests/unit/test_registry_toplevel.py) +- [tests/unit/test_resampling.py](../../../skyulf-core/tests/unit/test_resampling.py) +- `tests/unit/test_resampling_smote_tomek.py` ? +- [tests/unit/test_schema_contract.py](../../../skyulf-core/tests/unit/test_schema_contract.py) +- [tests/unit/test_schema_inference_fuzz.py](../../../skyulf-core/tests/unit/test_schema_inference_fuzz.py) +- `tests/unit/test_sentence_embedder_concurrency.py` ? +- `tests/unit/test_shap_refactor_branches.py` ? +- `tests/unit/test_temporal_model_input.py` ? +- [tests/unit/test_text_vectorization.py](../../../skyulf-core/tests/unit/test_text_vectorization.py) +- [tests/unit/test_tuning_engine.py](../../../skyulf-core/tests/unit/test_tuning_engine.py) +- [tests/unit/test_tuning_engine_failure_branches.py](../../../skyulf-core/tests/unit/test_tuning_engine_failure_branches.py) +- [tests/unit/test_tuning_failed_fold_semantics.py](../../../skyulf-core/tests/unit/test_tuning_failed_fold_semantics.py) +- `tests/unit/test_tuning_refactor_branches.py` ? +- [tests/unit/test_tuning_reporter.py](../../../skyulf-core/tests/unit/test_tuning_reporter.py) +- [tests/unit/test_utils.py](../../../skyulf-core/tests/unit/test_utils.py) +- [tests/unit/test_vectorization_gaps.py](../../../skyulf-core/tests/unit/test_vectorization_gaps.py) +- `tests/unit/test_vectorization_output_names_regression_20260912.py` ? +- [tests/utils/test_case_loader.py](../../../skyulf-core/tests/utils/test_case_loader.py) diff --git a/initiatives/spark_and_mlflow/reports/2026-09-21-spark-databricks-readiness.md b/initiatives/spark_and_mlflow/reports/2026-09-21-spark-databricks-readiness.md new file mode 100644 index 000000000..e54fc22b6 --- /dev/null +++ b/initiatives/spark_and_mlflow/reports/2026-09-21-spark-databricks-readiness.md @@ -0,0 +1,360 @@ +# Skyulf Core: Spark, MLflow ve Databricks incelemesi + +Tarih: 2026-09-21. İncelenen HEAD: `f713003e6eccf7372fcf7676e8f38a7cb3b06e3d`. +Son kontrolde HEAD `3587521b469b3d957c3066c86b65048349aef117` oldu; +bu iki commit arasında `skyulf-core` ve `backend` değişikliği bulunmuyor. +Core paket sürümü: `0.8.24`. Bu belge bir inceleme ve tasarım önerisidir; +Spark/MLflow implementasyonunun tamamlandığını göstermez. + +## İnceleme kapsamı ve kanıt sınırı + +`skyulf-core/skyulf` altındaki 197 Python dosyasının tamamı yapısal olarak +taranmıştır: 40.772 satır; importlar, sınıflar, fonksiyonlar, node kayıtları ve +yerel materialization çağrıları çıkarılmıştır. Ana yürütme yolları ve node +ailelerinin fit/apply/state davranışları kaynak koddan ayrıca izlenmiştir. +269 test dosyası envantere alınmış ve bütün core pytest paketi çalıştırılmıştır. +Runtime registry bu ortamda 100 kayıt içerir: 62 transformer ve 38 model kaydı. +Bu sayılar alias kayıtlarını da içerir; 100 bağımsız algoritma anlamına gelmez. + +Ek olarak backend graph yürütme, artifact üretme ve deployment sınırları ile +frontend registry/config dönüştürme girişleri incelenmiştir. Backend/frontend'in +tam ürün denetimi veya bütün testleri bu çalışmanın kapsamında değildir. + +Tam dosya ve node dökümü: [İnceleme envanteri](2026-09-21-spark-core-inventory.md). +Yapısal tarama her branch'in doğruluğunun kanıtı değildir. Bu çalışma bir Spark +uyumluluk/mimari incelemesidir; satır satır bağımsız doğruluk denetimi değildir. + +Mevcut ortamda `pyspark`, `mlflow` ve `databricks` paketleri bulunmuyor. +Databricks workspace, Unity Catalog, Spark executor veya serving endpoint üzerinde +çalıştırma yapılmadı. Bu sınırlar yerel testlerin geçmesiyle ortadan kalkmaz. +Uygulama kodu, bağımlılıklar ve mevcut kullanıcı değişiklikleri değiştirilmedi. + +## Sonuç + +Core'un Calculator/Applier ayrımı, fitted state yaklaşımı ve engine dispatcher'ı +korunmaya değer. Ancak Spark desteği bir enum değeri ve birkaç node dalı eklemekten +fazlasını gerektiriyor. Veri kimliği, lazy execution, şema, istatistik semantiği, +artifact biçimi ve destek matrisi önce tanımlanmalı. + +Önerilen sıra: + +1. Engine/capability ve artifact sözleşmesi. +2. Spark temel yürütme yolu ve sınırlı bir native node grubu. +3. Kaydet/yükle ve engine'ler arası fitted-state uyumluluğu. +4. Opsiyonel MLflow tracking/model paketi ve Unity Catalog adaptörü. +5. Dönemsel batch inference, veri adaptörü ve güvenilir tablo yazma. +6. Online serving/SQL erişimi; ayrı sözleşmeyle streaming. +7. Canvas uyarlaması gerekiyorsa bu çalışan katmanlara bağlama. +8. En son template ve DAB üretimi. + +MLflow ile ilgili bağımsız işler sözleşme belirlendikten sonra Spark node +çalışmalarıyla aynı dönemde geliştirilebilir. Bütün node'ların Spark'a taşınması, +ilk batch inference teslimatının önkoşulu olmamalı. + +## Mevcut çalışma yolları + +### Standalone core + +`SkyulfPipeline` yapısal config doğrulaması yapar, registry'den model node'unu +çözer ve `FeatureEngineer` ile preprocessing zincirini oluşturur. `fit` önce +leakage kontrolünü çalıştırır. Normal eğitim ile tuning akışlarının preprocessing +yönetimi farklıdır: tuning fold-local fit ve son refit'in state'ini kullanır. + +`FeatureEngineer` sıralı adımlar çalıştırır. `StatefulTransformer`, train üzerinde +Calculator.fit çalıştırıp artifact'i held-out split'lere uygular. TargetEncoder ve +WOE gibi adımlar için `fit_transform_train` ayrı eğitim temsili üretir. + +Modeling sklearn tabanlıdır. `SklearnBridge` pandas/Polars verisini yerel NumPy +temsiline çevirir. CV, tuning ve değerlendirme yolları da yerel diziler kullanır. +`predict`, fitted preprocessing'i uygular ve satır sayısını korumayı denetler. + +Kaynaklar: [pipeline](../../../skyulf-core/skyulf/pipeline/_pipeline.py), +[preprocessing](../../../skyulf-core/skyulf/preprocessing/pipeline.py), +[stateful transformer](../../../skyulf-core/skyulf/preprocessing/base.py), +[model wrapper](../../../skyulf-core/skyulf/modeling/sklearn_wrapper.py). + +### Backend ve Canvas + +Backend `PipelineEngine`, ayrı bir graph/topological yürütücüdür. Ara DataFrame'leri +artifact store'a kaydeder; branch merge ve fold preprocessing yolları vardır. +Son inference artifact'i çoğunlukla `model`, `feature_engineer`, kolonlar, +dtype'lar, engine ve job bilgisini içeren bir dict'tir. + +Backend deployment, bu dict'i ve eski biçimleri okuyabilir; kendi target temizliği, +kolon kontrolü, label decoding ve threshold seçimini yapar. Standalone pipeline +ise bütün nesneyi pickle ile kaydeder. Bu iki biçimi aynı artifact sanmak hatalıdır. +Databricks model paketi ilk aşamada standalone core'dan üretilebilir; mevcut backend +artifact'leri için daha sonra açık bir adaptör gerekir. + +Spark DataFrame/session/plan nesneleri mevcut joblib ara-artifact alışkanlığına +doğrudan konulmamalı. Dağıtık ara verinin yaşam döngüsü cache/checkpoint veya +sürümü belirli tablo referansı olarak tasarlanmalı. + +Kaynaklar: [backend engine](../../../backend/ml_pipeline/_execution/engine/__init__.py), +[bundle üretimi](../../../backend/ml_pipeline/_execution/engine/_feature_eng.py), +[deployment](../../../backend/ml_pipeline/deployment/service.py). + +## Var olan arayüzler ve eksik bağlantılar + +| Alan | Kaynakta görülen durum | Gerekli karar | +| --- | --- | --- | +| EngineRegistry | pandas/Polars kayıtlı; Spark yalnızca geleceğe yönelik module eşlemesi | Spark için gerçek adapter; tanınan ama kurulu olmayan engine'e açık hata | +| Engine seçimi | Güncel fallback Polars, ContextVar ile kapsamlanmış | Input engine ve çalışma platformunu ayrı tut | +| Dispatcher | Engine-keyed mapping var; giriş hazırlama pandas/Polars'a özel | Spark hazırlama yolu, mixed X/y kontrolü, capability preflight | +| DataFrame protokolü | `shape`, `len`, assignment, copy ve local dönüşümler bekliyor | Metadata ile action/materialization işlemlerini ayır | +| ComputeBackend | `execute(func, ...)` seam'i; pipeline tarafından otomatik çağrılmıyor | Bunu node semantiği sağlamayan bir Spark çözümü olarak sunma | +| DataCatalog | load/save/exists; save seçenekleri genel kwargs | Ayrı Databricks adaptöründe açık kaynak/yazma sözleşmesi | +| ModelRegistry | InMemoryModelRegistry nesne referanslarını sürümlüyor | Kalıcı artifact URI, uzak registry version/alias ve yükleme ayrı ele alınmalı | +| Serializer | ContextVar provider var; pipeline save/load bunu kullanmıyor | Mevcut pickle formatını koruyarak yeni sürümlü paket biçimi | +| Metadata | learns_from_data/is_splitter var | fit/apply engine, satır değişimi, bağlam, model bağımlılığı ve serving uygunluğu | +| Schema | pandas/Polars çıkarımı ve sade dtype isimleri | Spark StructType, decimal, timestamp, nullability ve nested tip politikası | +| Config | Outer shape kontrolü, node params serbest | Yeni deployment/execution config'i açıkça doğrulanmalı; eski config bozulmamalı | + +AGENTS metnindeki pandas-only ve filesystem-free açıklamalarının mevcut kodla +uyuşmadığı görüldü. Core pandas/Polars içeriyor ve pipeline save/load dosya kullanıyor. +Core README'si pandas fallback diyor; canlı registry ve ilgili testler Polars +fallback'i doğruluyor. Tasarım uygulamadan önce bu doküman farkları düzeltilmeli. + +## Spark için temel sözleşmeler + +- Spark frame'i dağıtık ilişki olarak ele al. pandas index'i veya sıralı X/y dizisi + varsayma. Target ve entity/row key aynı ilişkide taşınmalı; join kardinalitesi + denetlenmeli. Spark'taki fiziksel sıra model çıktı eşleştirmesinin anahtarı olamaz. +- `len`, `shape`, boşluk kontrolü ve her node öncesi/sonrası satır sayımı action + tetikleyebilir. `get_data_stats`, prediction doğrulaması ve profiling buna göre + düzenlenmeli. Transform planlama zamanı, gerçek execution zamanı ve Python + tracemalloc ölçümü cluster çalışma süresi/belleği olarak raporlanmamalı. +- Otomatik `toPandas`, `collect` veya `to_numpy` fallback'i olmamalı. Yerel eğitim + gerekiyorsa ayrı materialization adımı ve satır/kolon/bellek bütçesi olmalı. +- Fit küçük bir istatistik vektörü döndürebilir; bu tüm satırları toplamakla aynı + değildir. Büyük vocab/group mapping için sınırsız dict yerine boyut sınırı ve + gerekirse harici state/tablo referansı gerekir. +- Spark session runner tarafından sağlanmalı; fitted artifact içine girmemeli. +- Spark Classic ve Spark Connect aynı destek varsayılmamalı. DataFrame/SQL API'si + öncelikli olmalı; RDD, SparkContext ve JVM erişimine dayalı çekirdek tasarlanmasın. +- Kaynak snapshot, engine/runtime sürümü ve session timezone run metadata'sında + bulunmalı. ANSI cast davranışı ve geçersiz değer politikası açık seçilmeli. + +Databricks Connect'te RDD/SparkContext ve dağıtık ML training kısıtları bulunduğu +resmi dokümanda belirtiliyor. Yerel Connect istemcisinde çalışmak, aynı kodun her +cluster/serving ortamında desteklendiği anlamına gelmez. +[Connect sınırlamaları](https://docs.databricks.com/aws/en/dev-tools/databricks-connect/python/limitations) + +## Node ailelerine göre taşıma kararı + +Tablodaki Spark davranışları öneridir; mevcut destek iddiası değildir. + +| Aile | Mevcut ayrıntı | Öneri | +| --- | --- | --- | +| Casting | Bazı category/datetime yolları veriyi inceliyor/dönüştürüyor | Basit cast ile learned categories ayrılmalı; decimal/UTC/invalid cast testleri | +| Cleaning | Alias, regex, text, invalid/value replacement engine dalları var | SQL ifadeleri; regex/string/boolean/null eşdeğerliği; özel fonksiyonlar açık capability | +| Drop/missing | Explicit kolon seçimi ile missing-threshold fit farklı | İlk native dal; row dropping için eğitim/inference farkını koru | +| Deduplicate | Keep policy ve target survivor eşleşmesi var | `first/last` için deterministik sıra; inference skip davranışını koru | +| SimpleImputer | Kolon bazlı fill_values taşınabilir | İlk learned native node; mean/median/mode ve all-null semantiği | +| Scalers | Fit sklearn'e gider; apply çoğunlukla sayısal state kullanır | Spark aggregation ile aynı mean/scale state; native apply | +| Outliers | IQR/ZScore/ManualBounds filtreler; Winsorize clip yapar | Filtreyi online model içinde gizleme; clip ile row filtering ayrı capability | +| Binning | Custom/equal-width/quantile/kmeans yolları farklı | Custom/equal-width önce; quantile doğruluğu ve kmeans ayrı destek | +| Dummy/label/ordinal/one-hot | Bazıları mapping, bazıları sklearn encoder nesnesi saklar | Kategori canonicalization, sırayla feature isimleri, unknown/null/drop davranışı korunmalı | +| HashEncoder | BLAKE2b ile sabit bucket ataması | Spark hash fonksiyonuyla sessizce değiştirme; aynı algoritma veya açık yeni semantik | +| TargetEncoder/WOE | Eğitim temsili cross-fit; inference full-train state kullanır | Fold identity/OOF sözleşmesi olmadan native fit desteklenmesin | +| FeatureGeneration | Arithmetic/ratio/date ve learned group_agg aynı node'da | Operation bazında capability; group mapping ile geçmiş pencere feature'ını ayır | +| FeatureInteraction/Polynomial | Bazı fit yolları NumPy/pandas; sklearn feature isimleri | Kontrollü kombinasyon/kolon limiti; aynı expansion sırası | +| FeatureSelection | Fit yerel sklearn olabilir; apply yalnızca kolon düşürebilir | Spark apply desteğini Spark fit desteğinden bağımsız sun | +| DateFeatures | Yeni artifact'lerde UTC politikası | Spark timezone/day-of-week/hafta sınırlarını aynı sözleşmeye uydur | +| Lag/Rolling | Satır sayılı pencere, grup/sıra, opsiyonel row drop | Window specification ve tie-breaker; geçmiş veri/context zorunlu | +| KNN/Iterative imputation | Fitted Python nesnesi | İlk native kapsam dışında; açık worker-Python veya bounded local yol | +| EllipticEnvelope | Kolon bazlı sklearn nesneleri | Native eşdeğerlik iddiası yok; filtre davranışı ayrı planlanmalı | +| Resampling | imblearn; Polars yolu pandas'a geçiyor | Train-only; distributed sampling ile SMOTE aynı işlem sayılmamalı | +| Count/TF-IDF/Hashing/Tokenizer | sklearn tokenizer/vocab; dense frame çıktısı | Vocab/IDF/tokenization ve sparse/dense politika; Spark sınıflarıyla kör değişim yok | +| SentenceEmbedder | Model ismiyle yükleme, process cache, harici model bağımlılığı | Model revision ve dosyalarını paketle; worker/GPU/batch bütçesi | +| GeoDistance/H3 | Yerel NumPy/H3 yolları | Distance ifadesi ayrı; H3 library/runtime parity ayrı | +| DatasetProfile/DataSnapshot | İçerik okuyan fit ve passthrough apply | Bounded sample/aggregate; büyük veri snapshot'ı serialize etme | + +Önemli semantik örnek: sklearn StandardScaler `ddof=0` kullanırken Spark ML +StandardScaler düzeltilmiş örnek standart sapması kullanır. Aynı sınıf adı aynı +sonuç demek değildir. Skyulf semantiğini koruyan Spark aggregate/ifadeleri gerekir. +[sklearn](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html), +[Spark](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.StandardScaler.html) + +Quantile/median yaklaşık hesaplanacaksa hata toleransı artifact/config'de açık +olmalı; mevcut kesin davranışın sessiz değişimi sayılmamalı. Model eşdeğerliği, +aynı fitted state'i uygulamak ve farklı engine'lerde yeniden fit etmek için ayrı +test edilmelidir; floating-point sonuçlarda uygun tolerans gerekir. + +## Artifact ve inference: iki farklı taşınabilirlik + +1. **Python runtime taşınabilirliği:** mevcut fitted pipeline MLflow Python model + paketi içinde çalışır. Spark worker batch'leri pandas olarak alabilir; gerekirse + wrapper Polars'a dönüştürür. Bu, Spark-native preprocessing değildir. +2. **State taşınabilirliği:** öğrenilmiş median/mean/category mapping aynı state ile + Spark-native Applier tarafından uygulanır. Her node ve artifact sürümü için + destek ayrı doğrulanır. Encoder/model nesneleri kendiliğinden Spark'a çevrilmez. + +Model paketi aşağıdakileri içermeli: + +- Format sürümü, Skyulf/Python/dependency sürümleri ve semantic fingerprint. +- Model blob/flavor, node türleri, fitted state ve gereken custom code. +- Ham giriş şeması, model feature şeması, kolon sırası, çıktı şeması. +- Target label mapping, probability class order, threshold politikası. +- Feature engineering sürümü ve external feature/table state referansları. +- Row-local, context gerektiren ve online uygun adımların açık bilgisi. +- Eğitim veri referansı ve sürümü; credentials/session objeleri içermez. + +Mevcut pickle okuyucuları korunabilir; yeni paket, migration/adaptör olmadan +eski artifact'lerin tamamını taşınabilir ilan etmemeli. `export_model_card` ve +`fingerprint` tekrar kullanılabilir; fingerprint bir dependency lock veya veri +snapshot kimliğinin yerine geçmez. + +MLflow `spark_udf` pandas batch arayüzü sunar; driver'a tüm tabloyu toplamak gerekmez. +Worker'da model bir kere yüklenmeli/reuse edilmeli ve saf predict çalışmalı; +UDF içinde registry'ye kayıt, tracking run açma veya tabloya yan etkili yazma olmamalı. +[MLflow pyfunc](https://www.mlflow.org/docs/latest/api_reference/python_api/mlflow.pyfunc.html) + +## Deneyler + +Mevcut kodla, yeni ürün kodu yazmadan iki küçük çalışma yapıldı: + +1. Polars üzerinde `SimpleImputer -> StandardScaler -> OneHotEncoder -> linear_regression` + fit edildi; pickle round-trip sonrası aynı girdi pandas ve Polars ile skorlandı. + En büyük tahmin farkı `7.105427357601002e-15`. İki parçalı Polars tahmininin + tam batch tahmininden farkı `0.0`. Bu yalnızca bu zincirin yerel kanıtıdır; + Spark/MLflow uyumluluğunun veya bütün node'ların kanıtı değildir. +2. `[1,2,3,4,5,6]` için window=3 rolling mean tam veride + `[1,1.5,2,3,4,5]`; iki üçlü parçaya bölündüğünde `[1,1.5,2,4,4.5,5]` çıktı. + Satır sayısı/sırası korunurken bile batch sınırı anlamı değiştirebilir. + +Bu nedenle sadece `preserve_rows=True` kontrolü distributed UDF güvenliği için +yeterli değildir. Lag/rolling'in gerekli history/context'i ayrı hazırlanmalıdır. + +## Eğitim, tuning, evaluation ve monitoring + +- Mevcut model ailesi sklearn temelli; XGBoost/LightGBM wrapper'ları da yerel + estimator arayüzündedir. Spark engine seçimi modelleri distributed yapmaz. +- İlk aşamada Spark FE + açık bounded materialization + mevcut trainer desteklenebilir. + Distributed training ayrı backend/model desteğidir; bütün algoritmaların Spark + karşılığı varmış gibi generic `engine=spark` altında gizlenmemeli. +- CV/tuning NumPy, sklearn splitter/clone, positional slicing ve joblib/Optuna + yürütmesine dayanıyor. `n_jobs` executor sayısı değildir. Fold refit ve target + encoder OOF davranışı distributed portta korunmalı; cached full-data FE leakage yaratabilir. +- Split membership seed kadar row/entity/time kimliğine de bağlı olmalı. Yeniden + partition edilince aynı split isteniyorsa sabit key/fold assignment kaydedilmeli. +- Evaluation sklearn/SciPy array tabanlı. Distributed confusion matrix/sum/count + gibi yeterli istatistikler ayrı yol olabilir; AUC/quantile ve global sıralama + isteyen metriklerin yaklaşık/kesin anlamı açıklanmalı. Ham prediction listesini + bütün dataset için run metadata'sına koymamak gerekir. +- Threshold tuning validation verisi üzerinde; class sırası ve threshold seçimi + endpoint/batch arasında aynı olmalı. Tuning metadata'sı ile aktif serving kararını ayır. +- SHAP yerel model ve bounded sample gerektiriyor; online predict'in zorunlu parçası olmamalı. +- EDAAnalyzer Polars'a özel; lazy view kullanması Spark dağıtık çalışma değildir. + Numeric/categorical/date/text/geo, PCA/outlier/causal/rules/temporal modülleri + farklı sample ve yerel algoritma yolları kullanıyor. +- DriftCalculator Polars/SciPy temelli. Büyük tablolar için Spark'ta histogram/count + üretip küçük özetleri değerlendirmek uygun bir tasarım adayıdır; mevcut KS veya + Wasserstein algoritmalarını histogram yaklaşımıyla aynı metrik diye değiştirme. +- Expectation kontrolleri pandas/Polars'a özel. Spark kolon/null/unique/range + kontrolleri aggregate ile çalışmalı; EDA/visualizer modülleri tabloyu toplamasın. + +## Aylık batch, online, SQL ve streaming + +Platform, feature engine, training backend, tracking, registry, tetikleyici ve +çıktı birbirinden bağımsız boyutlardır. Laptop'ta MLflow/UC kullanılabilir; +Databricks job içinde küçük veri pandas/Polars ile işlenebilir. DAB bir dağıtım +tanımıdır, dataframe engine'i değildir. + +### Aylık batch sözleşmesi + +Run girdileri `period_start`, `period_end`, `as_of`, model version ve kaynak +snapshot'tır. Varsayılan öneri tarih aralığını `[start, end)` olarak tanımlamak ve +timezone'u açık tutmaktır. Skorlanacak dönem ile feature üretmek için gereken +history aralığı aynı şey değildir. + +Model alias'ı run başında somut sürüme çözülür. Veriyi okuma, feature hazırlama, +schema/quality kontrolü, skor üretme, çıktı kontrolü ve publish ayrı adımlardır. +Çıktı entity/row key, scoring period, prediction, gerekiyorsa probability, +model version, feature version, run ID ve hesaplama zamanını taşır. + +Append/history ile dönem replace/merge ayrı seçeneklerdir. Merge anahtarı ve +tekrar çalıştırma politikası açık olmalı. Stage/validate/publish yaklaşımı ve Delta +işlem sınırı tasarlanmalı; checkpoint tek başına exactly-once iddiası sağlamaz. +Backfill'de tarihsel model mi güncel model mi kullanılacağı açık parametre olmalı. +Late-arriving data, aynı dönem için eşzamanlı iki run ve yarıda kalan yayın test edilmeli. + +Scheduler core dışında kalır. Databricks Jobs aylık/zaman tabanlı, tablo/file +olaylı veya manuel tetikleme sağlar. +[Jobs](https://docs.databricks.com/gcp/en/jobs/triggers) + +### Online ve ai_query + +Online endpoint yalnızca paketlenmiş model ve istekte sağlanan/lookup ile alınan +feature'larla çalışabilmeli. Spark window/history işlemlerini küçük HTTP request'in +içinde var sayamayız. Önceden hesaplanmış feature tablosu/online lookup gerekebilir. + +`ai_query`, custom model senaryosunda serving endpoint'ini SQL'den çağırır. +Registry URI'sine doğrudan local predict değildir. Aynı endpoint HTTP ve SQL +istemcilerine hizmet verebilir; bir batch job da ai_query kullanabilir. Request +şeması, sonuç tipi, hata politikası, retry ve kapasite endpoint adaptöründe tanımlanmalı. +[ai_query](https://docs.databricks.com/gcp/en/sql/language-manual/functions/ai_query) + +### Streaming + +Bağımsız kayıt skorlama ile stateful zaman özellikleri ayrı kapsamdır. Micro-batch +model sürüm politikası, checkpoint, watermark, geç gelen veri, deduplication ve +tekrar işleme sözleşmesi olmadan batch runner'a sadece streaming bayrağı eklenmemeli. + +## Paketleme ve custom code + +Spark/MLflow opsiyonel olmalı; temel import bunları veya Databricks SDK'yı zorunlu +kılmamalı. Local OSS Spark, Databricks job runtime ve Connect development için +ayrı dependency profilleri gerekir. Databricks Connect ve OSS PySpark aynı +ortamda kurulu olduğunda çakışabilir. +[Connect kurulum kısıtı](https://docs.databricks.com/aws/en/dev-tools/databricks-connect/python/troubleshooting) + +Core halen pandas, Polars, PyArrow, sklearn ve diğer yerel kütüphanelere bağımlı. +Spark extra eklemek bunları kaldırmaz. İlk teslimatta geniş dependency ayrıştırması +yerine hedef DBR/Python ile doğrulanmış constraints kullanılmalı. Daha sonra +gerekiyorsa serving paketi hafifletilebilir. Model serving wheel'i sürümlenmeli. + +Custom feature fonksiyonları config'de bir callable/module referansı ve capability +bilgisiyle yer alabilir. Registry importları her worker'da erişilebilir paket içinde +olmalı; yalnızca notebook'ta tanımlanmış fonksiyona veya driver belleğine dayanılmamalı. +Fonksiyon engine, giriş/çıkış şeması, row key ve context sözleşmesini uygulamalı. +İlk aşamada arbitrary kodu bütün engine'lere otomatik çevirme sözü verilmemeli. + +## Teslimat dilimleri ve kabul ölçütleri + +| Dilim | Somut çıktı | Kabul ölçütü | +| --- | --- | --- | +| A | Capability, veri/kimlik, şema ve artifact v1 kararı | Her node/operation fit ve apply için destek/ret sebebi; mevcut API uyumu | +| B | Spark adapter + sınırlı native FE | SimpleImputer, StandardScaler, açık kolon/drop ve basit dönüşümler gerçek Spark'ta çalışır; gizli collect yok | +| C | State portability | Local fit -> Spark apply ve Spark fit -> local apply; null/category/time/decimal edge case; save/load | +| D | MLflow ve UC | Tracking kapalıyken core çalışır; model package kayıt/yükleme; signature/class/threshold parity | +| E | Aylık batch runner + Delta sink | Gerçek Databricks run; model pinning; dönem, backfill ve idempotent yayın kanıtı | +| F | Bağlamsal FE ve kalan node grupları | Window/group, OOF ve büyük state kuralları ayrı testlerle; desteklenmeyenler açık | +| G | Online/SQL ve gerekiyorsa streaming | Python batch ile eşdeğer tahmin; bağımlılıklar bağımsız ortamda yüklenir; context eksikliği reddedilir | +| H | Canvas ve template | UI yalnızca desteklenen yolları sunar; DAB çalışan runner'ları paketler | + +İlk uygulama işi bütün node'ları bir seferde değiştirmek olmamalı. A dilimini +netleştirip B/C için bir küçük uçtan uca akış kurmak, geri kalan node portlarına +güvenilir örnek ve test sözleşmesi sağlar. Bu belge uygulama onayı veya tamamlanmış +implementation plan değildir; önerilen geliştirme sırasıdır. + +## Doğrulama + +- Seçili engine/artifact/pipeline/leakage sözleşmeleri: **260 passed**, 88 warnings. +- Bütün core: **9815 passed, 68 skipped, 1 failed**, 1075 warnings; **216.48 saniye**. +- Başarısız test: + `tests/integration/test_wrapped_polars_frames.py::test_sentence_embedder_accepts_wrapped_polars_frame`. + Dar tekrarda Hugging Face model metadata isteği `[WinError 10013]` ile + engellendi; ardından `Cannot send a request, as the client has been closed` + hatası geldi. Aynı test `HF_HUB_OFFLINE=1` ile önbellekteki modeli kullanarak + **1 passed (5.15 saniye)** sonucu verdi. Bu dar doğrulama, tam suite sonucunu + tümüyle başarılı olarak değiştirmez. +- İki yerel davranış deneyi: engine değişimi/round-trip ve rolling batch sınırı. +- Spark/MLflow/Databricks integration testi yapılmadı; paketler bu ortamda yok. +- Uygulama kodu değişmedi; lint/typecheck/build sonucu iddia edilmiyor. + +Tam core komutu: + +```powershell +.venv/Scripts/python.exe -m pytest skyulf-core/tests -q --tb=short -o addopts= -p no:cacheprovider --basetemp .tmp-spark-review-full +``` diff --git a/mkdocs.yml b/mkdocs.yml index 50ec0077c..58d3688e7 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -73,6 +73,7 @@ nav: - User Guide: - Overview: user_guide/overview.md - Installation: user_guide/installation.md + - Spark (Development): user_guide/spark.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/pyproject.toml b/pyproject.toml index 38e90e2e3..8ef7cc0c8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ [project] name = "skyulf" -version = "0.8.24" +version = "0.9.0" description = "MLOps web application for privacy-preserving ML workflows" readme = "README.md" requires-python = ">=3.12" diff --git a/requirements-spark.txt b/requirements-spark.txt new file mode 100644 index 000000000..a0739daa6 --- /dev/null +++ b/requirements-spark.txt @@ -0,0 +1,10 @@ +# SM-00 development/test lane; requires Java 17 (not installed by Python). +# Does not imply that Skyulf nodes already support Spark execution. +# Kept separate from base/backend dependencies and Databricks Runtime. +-e ./skyulf-core[spark] +pyspark==4.0.3 +pytest>=9.0.0,<10.0.0 +# Root pytest configuration declares asyncio_mode. +pytest-asyncio>=0.21.0,<2.0.0 +pandas>=2.0.0,<3.0.0 +pyarrow>=21.0.0 diff --git a/skyulf-core/setup.py b/skyulf-core/setup.py index 21192d421..78d0d06a2 100644 --- a/skyulf-core/setup.py +++ b/skyulf-core/setup.py @@ -16,7 +16,7 @@ setup( name="skyulf-core", - version="0.8.24", + version="0.9.0", description="The core machine learning library for Skyulf.", long_description=long_description, long_description_content_type="text/markdown", @@ -41,6 +41,8 @@ "statsmodels>=0.14.0", ], extras_require={ + # Experimental test/runtime dependency only; node support is gated separately. + "spark": ["pyspark>=4.0.3,<4.1.0", "pandas>=2.0.0,<3.0.0"], "dev": [ "pytest", "pytest-cov>=4.1.0,<5.0.0", @@ -77,7 +79,8 @@ "modeling-lightgbm": ["lightgbm>=4.0.0"], "explainability": ["shap>=0.46.0,<1.0.0"], # Convenience aggregate: every optional runtime feature (excludes dev/geo - # which carry heavy native deps and are opt-in on their own). + # which carry heavy native deps and are opt-in on their own). Spark + # also stays separate: it requires Java and is experimental. "all": [ "matplotlib>=3.7.0", "rich>=13.0.0", diff --git a/skyulf-core/tests/spark/conftest.py b/skyulf-core/tests/spark/conftest.py new file mode 100644 index 000000000..6c6b04b63 --- /dev/null +++ b/skyulf-core/tests/spark/conftest.py @@ -0,0 +1,42 @@ +"""Optional Spark fixtures; the dedicated lane fails when Spark is unavailable.""" + +import importlib +import importlib.util +import os +import sys + +import pytest + + +@pytest.fixture(scope="session") +def spark(tmp_path_factory): + """Run a local JVM with two workers and the current interpreter for Python tasks.""" + if importlib.util.find_spec("pyspark") is None: + message = "Spark tests require requirements-spark.txt and Java 17." + if os.environ.get("SKYULF_REQUIRE_SPARK") == "1": + pytest.fail(message) + pytest.skip(message) + + # Keep optional runtime imports out of the base environment's type resolution. + spark_sql = importlib.import_module("pyspark.sql") + + work_dir = tmp_path_factory.mktemp("spark") + with pytest.MonkeyPatch.context() as env: + env.setenv("PYSPARK_PYTHON", sys.executable) + env.setenv("PYSPARK_DRIVER_PYTHON", sys.executable) + env.setenv("SPARK_LOCAL_IP", "127.0.0.1") + session = ( + spark_sql.SparkSession.builder.master("local[2]") + .appName("skyulf-spark-tests") + .config("spark.ui.enabled", "false") + .config("spark.sql.session.timeZone", "UTC") + .config("spark.sql.shuffle.partitions", "2") + .config("spark.sql.execution.arrow.maxRecordsPerBatch", "3") + .config("spark.sql.warehouse.dir", (work_dir / "warehouse").as_uri()) + .config("spark.local.dir", str(work_dir / "local")) + .getOrCreate() + ) + try: + yield session + finally: + session.stop() diff --git a/skyulf-core/tests/spark/test_runtime_smoke.py b/skyulf-core/tests/spark/test_runtime_smoke.py new file mode 100644 index 000000000..52475b2f9 --- /dev/null +++ b/skyulf-core/tests/spark/test_runtime_smoke.py @@ -0,0 +1,33 @@ +"""Exercise the JVM and Python worker boundaries of the optional Spark test lane.""" + +import importlib + + +def test_spark_executes_multiple_partitions(spark): + """A successful import must not substitute for distributed JVM execution.""" + functions = importlib.import_module("pyspark.sql.functions") + + frame = spark.range(100).repartition(2).withColumn("partition", functions.spark_partition_id()) + result = frame.agg( + functions.sum("id").alias("total"), + functions.countDistinct("partition").alias("partitions"), + ).first() + + assert result["total"] == 4950 + assert result["partitions"] == 2 + + +def test_spark_executes_python_arrow_batches(spark): + """The configured Python worker must exchange Arrow batches with the driver.""" + functions = importlib.import_module("pyspark.sql.functions") + + def double_batches(batches): + """Double each batch without moving the input dataset to the driver.""" + for batch in batches: + yield batch.assign(doubled=batch["id"] * 2) + + frame = spark.range(10).repartition(2) + result = frame.mapInPandas(double_batches, "id long, doubled long") + total = result.agg(functions.sum("doubled").alias("total")).first()["total"] + + assert total == 90 diff --git a/uv.lock b/uv.lock index ff64f68bd..32be08ebe 100644 --- a/uv.lock +++ b/uv.lock @@ -3317,6 +3317,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/a9/023730ba63db1e494a271cb018dcd361bd2c917ba7004c3e49d5daf795a2/py_cpuinfo-9.0.0-py3-none-any.whl", hash = "sha256:859625bc251f64e21f077d099d4162689c762b5d6a4c3c97553d56241c9674d5", size = 22335, upload-time = "2022-10-25T20:38:27.636Z" }, ] +[[package]] +name = "py4j" +version = "0.10.9.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/31/0b210511177070c8d5d3059556194352e5753602fa64b85b7ab81ec1a009/py4j-0.10.9.9.tar.gz", hash = "sha256:f694cad19efa5bd1dee4f3e5270eb406613c974394035e5bfc4ec1aba870b879", size = 761089, upload-time = "2025-01-15T03:53:18.624Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bd/db/ea0203e495be491c85af87b66e37acfd3bf756fd985f87e46fc5e3bf022c/py4j-0.10.9.9-py2.py3-none-any.whl", hash = "sha256:c7c26e4158defb37b0bb124933163641a2ff6e3a3913f7811b0ddbe07ed61533", size = 203008, upload-time = "2025-01-15T03:53:15.648Z" }, +] + [[package]] name = "pyarrow" version = "24.0.0" @@ -3569,6 +3578,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ce/41/39842a6440834324286de1ac15a0402cb6626ef14be0e742b96fbb5df905/pyscan_rs-2.1.3-py3-none-win_arm64.whl", hash = "sha256:c9dea27f0f912e7e86ff00fb7924d4be3ddc29c795bb93f434fc9424890aaf14", size = 2410874, upload-time = "2026-06-03T08:42:27.121Z" }, ] +[[package]] +name = "pyspark" +version = "4.0.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "py4j" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9a/c8/27b5316543a4d724efef4ecc1cfcb42a9afcb8af33cfdff989164b9a4487/pyspark-4.0.4.tar.gz", hash = "sha256:7e119366364d48e3cda1b1efd1ebc6cd672949500667c9cabbeef858daba700f", size = 434312230, upload-time = "2026-07-15T11:15:10.721Z" } + [[package]] name = "pytest" version = "9.1.1" @@ -4508,7 +4526,7 @@ wheels = [ [[package]] name = "skyulf" -version = "0.8.24" +version = "0.9.0" source = { virtual = "." } dependencies = [ { name = "aiofiles" }, @@ -4780,6 +4798,10 @@ nlp = [ preprocessing-imbalanced = [ { name = "imbalanced-learn" }, ] +spark = [ + { name = "pandas" }, + { name = "pyspark" }, +] text = [ { name = "vadersentiment" }, ] @@ -4819,10 +4841,12 @@ requires-dist = [ { name = "optuna-integration", marker = "extra == 'all'", specifier = ">=3.0.0" }, { name = "optuna-integration", marker = "extra == 'tuning'", specifier = ">=3.0.0" }, { name = "pandas", specifier = ">=2.0.0,<3.0.0" }, + { name = "pandas", marker = "extra == 'spark'", specifier = ">=2.0.0,<3.0.0" }, { name = "polars", specifier = ">=1.43.2" }, { name = "pyarrow", specifier = ">=21.0.0" }, { name = "pydantic", specifier = ">=2.0.0" }, { name = "pyproj", marker = "extra == 'geo'", specifier = ">=3.6.0,<3.8.0" }, + { name = "pyspark", marker = "extra == 'spark'", specifier = ">=4.0.3,<4.1.0" }, { name = "pytest", marker = "extra == 'dev'" }, { name = "pytest-benchmark", marker = "extra == 'dev'", specifier = ">=5.0.0,<6.0.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.1.0,<5.0.0" }, @@ -4845,7 +4869,7 @@ requires-dist = [ { name = "xgboost", marker = "extra == 'all'", specifier = ">=2.1.4" }, { name = "xgboost", marker = "extra == 'modeling-xgboost'", specifier = ">=2.1.4" }, ] -provides-extras = ["dev", "viz", "eda", "text", "nlp", "geo", "tuning", "preprocessing-imbalanced", "modeling-xgboost", "modeling-lightgbm", "explainability", "all"] +provides-extras = ["spark", "dev", "viz", "eda", "text", "nlp", "geo", "tuning", "preprocessing-imbalanced", "modeling-xgboost", "modeling-lightgbm", "explainability", "all"] [[package]] name = "slicer" From b9eef16a636b9aa415b3ad414cd00fe5e06af908 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 20:14:52 +0300 Subject: [PATCH 02/85] feat(core): define execution contracts and explicit node capabilities Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 4 + docs/user_guide/spark.md | 59 +++++ .../spark_and_mlflow/01-core-spark-plan.md | 13 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 33 ++- initiatives/spark_and_mlflow/README.md | 4 +- skyulf-core/skyulf/core/capabilities.py | 126 ++++++++++ skyulf-core/skyulf/core/execution.py | 79 +++++++ skyulf-core/skyulf/registry.py | 23 +- .../tests/unit/test_execution_capabilities.py | 221 ++++++++++++++++++ .../tests/unit/test_execution_contract.py | 84 +++++++ 10 files changed, 632 insertions(+), 14 deletions(-) create mode 100644 skyulf-core/skyulf/core/capabilities.py create mode 100644 skyulf-core/skyulf/core/execution.py create mode 100644 skyulf-core/tests/unit/test_execution_capabilities.py create mode 100644 skyulf-core/tests/unit/test_execution_contract.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index fe61b59d3..bd9ea5919 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -19,6 +19,10 @@ execution and MLflow adapters remain under development. core tests can skip the optional runtime. No Spark node capability is enabled. - [Spark development guide](../docs/user_guide/spark.md) with isolated setup, a runtime example, troubleshooting and explicit support boundaries. +- Immutable execution options and row-key declarations, plus explicit + per-node fit/apply capability checks. Unsupported engine/configuration requests + produce structured errors without executing a node. Existing local pipelines + remain unchanged; these contracts do not enable Spark nodes yet. ### Planned scope — not yet available diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 115c33047..a95cef1b1 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -71,6 +71,65 @@ keep the dataset in Spark and transfer bounded learned state when supported. Python model inference on Spark workers is a separate capability from native Spark model training. +## Execution contracts + +The development API can validate a future execution request without starting +Spark or changing the current pandas/Polars engine: + +```python +from skyulf.core.execution import ExecutionOptions, FrameSpec + +options = ExecutionOptions.from_config({ + "engine": "spark", + "python_batch_rows": 4096, + "state_max_bytes": 8 * 1024 * 1024, +}) +identity = FrameSpec(row_keys=("customer_id", "event_id"), target="label") +``` + +Engine values are `pandas`, `polars` and `spark`; `databricks` names a platform, +not an engine. Unknown configuration fields and nonpositive/noninteger limits +are rejected. These immutable objects declare requirements; they do not apply +memory limits or validate the actual values in a dataframe. Runtime key-value +validation will arrive with the Spark dataframe adapter. + +A capability check distinguishes fit and apply and never falls back to pandas: + +```python +from skyulf.core.capabilities import UnsupportedExecutionError, require_capability + +try: + require_capability("SimpleImputer", "fit", "spark", config={"strategy": "mean"}) +except UnsupportedExecutionError as error: + print(error.node_type, error.operation, error.engine, error.reason) +``` + +This currently reports unsupported: no built-in Spark node has been enabled. +Existing local pipelines continue to work; this new preflight is not yet wired +into their execution. A local node without an explicit declaration also fails +this new query, even though its existing local pipeline path remains available. + +### Declaring custom operation support + +Node authors can pass an immutable `execution_capabilities` tuple to +`NodeRegistry.register`. Each `ExecutionCapability` records: + +| Field | Meaning | +| --- | --- | +| `engine`, `operation` | Exact engine and `fit` or `apply` | +| `execution_kind` | `native`, `python_batch` or `local` | +| `row_effect` | `preserve`, `filter` or `expand` | +| `context` | `row`, `group`, `window` or `global` | +| `codec_version` | Optional positive version of the fitted-state codec | +| `config_match` | Immutable tuple of required key/scalar-value pairs | + +For example, `config_match=(("strategy", "mean"),)` allows only an explicit +mean strategy; absent keys do not match. Normalize node defaults before querying. +Selectors compare types as well as values, so `True` is not treated as integer 1. +Aliases of the same calculator share declarations; subclasses must declare +their own support. Metadata is an implementation promise: it does not generate +Spark code, certify compatibility or make a window transform batch-independent. + ## Troubleshooting and support boundaries - **Java gateway fails:** check Java 17 and the current shell's `JAVA_HOME`. diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index ad5c503ae..99a1fc661 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -61,20 +61,21 @@ def test_spark_executes_multiple_partitions(spark): ## SM-01 — Execution ve capability sözleşmesi **Bağımlılık:** SM-00. **Oluştur:** `skyulf/core/execution.py`, -`skyulf/core/capabilities.py`, `tests/spark/test_capabilities.py` (ilk iki yol +`skyulf/core/capabilities.py`, `tests/unit/test_execution_capabilities.py`, +`tests/unit/test_execution_contract.py` (ilk iki yol `skyulf-core/` altında; bu planda tüm `skyulf/` ve `tests/` yolları aynı köke göre). **Değiştir:** `skyulf/registry.py`, `skyulf/config_validation.py`. **Tüketir:** Mevcut node registration anahtarları ve operation metadata. **Üretir:** ARCHITECTURE'daki FrameSpec, ExecutionOptions, `require_capability(...)`; `UnsupportedExecutionError(ValueError)`. -- [ ] Mevcut registry anahtarlarını dolaşan testte Spark desteği ilan edilmemiş +- [x] Mevcut registry anahtarlarını dolaşan testte Spark desteği ilan edilmemiş bütün fit/apply kombinasyonlarının açıklayıcı hatayla reddedildiğini sabitle. -- [ ] Capability kaydına engine + operation + config strategy + row/context etkisi +- [x] Capability kaydına engine + operation + config strategy + row/context etkisi ekle. Alias'lar canonical node ile aynı kararı vermeli; ikinci node registry yok. -- [ ] FrameSpec duplicate key isimlerini/target-key çakışmasını; options sıfır/negatif +- [x] FrameSpec duplicate key isimlerini/target-key çakışmasını; options sıfır/negatif limitleri ve bilinmeyen engine'i reddetsin. Frame içeriği kontrolü SM-03'te. -- [ ] Yeni runtime config'de yazım hatasının sessizce kabul edilmediğini test et. +- [x] Yeni runtime config'de yazım hatasının sessizce kabul edilmediğini test et. Eski config davranışını topluca değiştirme. ```python @@ -86,7 +87,7 @@ def test_unimplemented_spark_fit_is_explicit(): require_capability("KNNImputer", "fit", "spark", config={}) ``` -**Komut:** `python -m pytest skyulf-core/tests/spark/test_capabilities.py -q` +**Komut:** `python -m pytest skyulf-core/tests/unit/test_execution_contract.py skyulf-core/tests/unit/test_execution_capabilities.py -q` **Kabul:** Destek olmayan yol herhangi bir Spark action veya estimator fit çağırmaz. ## SM-02 — Spark engine ve materialization sınırı diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index a4c54523e..bce4b16ac 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,17 +1,17 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-00 tamamlandı. Sonraki görev: SM-01. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-01 tamamlandı. Sonraki görev: SM-02. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; -DONE = kanıtla tamamlandı. Şu an ACTIVE görev yok; SM-01 başlanabilir. +DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | Sıra | Görev | Bağımlılık | Durum | Kısa bitiş ölçütü | | --- | --- | --- | --- | --- | | SM-00 | Baseline ve Spark test ortamı | — | DONE | Güncel master: 231 baseline; 2 Spark smoke; [kanıt](BASELINE.md) | -| SM-01 | Execution/capability kuralları | SM-00 | READY | Desteklenmeyen engine/operation erken ret | -| SM-02 | Spark engine ve conversion sınırı | SM-01 | WAIT | Spark tanınır; gizli local conversion yok | +| SM-01 | Execution/capability kuralları | SM-00 | DONE | Immutable config; registry operation desteği; aşağıda kanıt | +| SM-02 | Spark engine ve conversion sınırı | SM-01 | READY | Spark tanınır; gizli local conversion yok | | SM-03 | Dispatcher, schema, row keys | SM-02 | WAIT | Key/target korunur; local API çalışır | | SM-04 | Versioned portable state | SM-03 | WAIT | Limit/version kontrolü; state round-trip | | SM-05 | Native SimpleImputer | SM-04 | WAIT | Mean/constant train-only fit, Spark apply | @@ -80,3 +80,28 @@ ve MLflow entegrasyonu henüz yok. exit 1. Eksik dependency başarılı CI gibi raporlanmıyor. - Ruff check/format ve scoped ty geçti. GitHub Actions ve Databricks çalıştırılmadı. - Sonraki görev SM-01; bu kanıt native Spark node desteği anlamına gelmez. + +## SM-01 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `105a6fe4`; bu kayıt doğrulanmış SM-01 çalışma ağacına aittir. +- Yeni `core/execution.py`: frozen FrameSpec ve ExecutionOptions, strict + `from_config`, pozitif integer limitleri; engine default'unu değiştirmez. +- Yeni `core/capabilities.py`: immutable operation/engine/config desteği ve + structured UnsupportedExecutionError. NodeRegistry mevcut Calculator sınıfında + declaration tutar; alias aynı sınıfı paylaşır, subclass açıkça yeniden ilan eder. +- Yeni testler `tests/unit/test_execution_contract.py` ve + `tests/unit/test_execution_capabilities.py`; Spark gerektirmeyen kurallar bu + yüzden planlanan spark/ dizini yerine unit/ altındadır. +- İlk 48 test eksik modüllerle fail oldu; uygulama sonrası geçti. Tam core: + `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q + --tb=short --disable-warnings -p no:cacheprovider --basetemp .cache/sm01-core` + → **9850 passed, 84 skipped, 1077 warnings**, 127.52 saniye; 3 snapshot geçti. +- Bağımsız inceleme bloklayan sorun bulmadı. Ek alias/subclass, type-exact + selector, invalid registration ve optional import regresyonlarından sonra: + iki yeni unit dosyası + test_engines_registry.py + test_core_seams.py + → **94 passed**. Bu son eklemeler test kapsamıdır; ürün kodu değişmedi. +- Tam repo ty, scoped Ruff/format ve yeni core modüllerinde CCN<=8 kontrolü geçti. + `mkdocs build --strict` başarılı; docs/user_guide/spark.md kontrat örnekleri + doğrudan çalıştırıldı. Kullanıcı belgeleri uygulamayla birlikte güncellendi. +- Spark engine/node desteği henüz etkin değil. Existing local pipeline preflight'ı + bu yeni API'ye bağlanmadı; SM-03'te yapılacak. Sıradaki görev SM-02. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index 5b6c40e12..be627809c 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00 tamamlandı; sıradaki görev SM-01.** +Tarih: 2026-09-21. Durum: **SM-00 ve SM-01 tamamlandı; sıradaki görev SM-02.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-01**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-02**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/core/capabilities.py b/skyulf-core/skyulf/core/capabilities.py new file mode 100644 index 000000000..b376cf510 --- /dev/null +++ b/skyulf-core/skyulf/core/capabilities.py @@ -0,0 +1,126 @@ +"""Explicit node execution support; declarations never perform fit or apply.""" + +import math +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +from .execution import _ENGINES, _require_choice, _require_positive_integer + +type ConfigValue = str | int | float | bool | None + + +class UnsupportedExecutionError(ValueError): + """Describe the requested node operation and why execution is unavailable.""" + + def __init__(self, node_type: str, operation: str, engine: str, reason: str) -> None: + """Expose structured fields as well as a human-readable error.""" + self.node_type = node_type + self.operation = operation + self.engine = engine + self.reason = reason + super().__init__(f"{node_type}.{operation} on {engine}: {reason}") + + +def _validate_config_match(match: tuple[tuple[str, ConfigValue], ...]) -> None: + """Keep capability selectors immutable and limited to exact scalar matches.""" + if not isinstance(match, tuple): + raise ValueError("config_match must be a tuple of key/value tuples.") + keys = [] + for pair in match: + _validate_config_pair(pair) + keys.append(pair[0]) + if len(set(keys)) != len(keys): + raise ValueError("config_match must not repeat a key.") + + +def _validate_config_pair(pair: tuple[str, ConfigValue]) -> None: + """Reject mutable, non-scalar and non-finite selector values.""" + if not isinstance(pair, tuple) or len(pair) != 2: + raise ValueError("config_match entries must be key/value tuples.") + key, value = pair + if not isinstance(key, str) or not key.strip(): + raise ValueError("config_match keys must be nonempty strings.") + if type(value) not in (str, int, float, bool, type(None)): + raise ValueError("config_match values must be scalar values.") + if isinstance(value, float) and not math.isfinite(value): + raise ValueError("config_match values must be finite.") + + +@dataclass(frozen=True) +class ExecutionCapability: + """Declare one operation's engine, row/context effects and state codec. + + Config selectors require explicit, type-exact values. Callers must normalize + defaults before querying; missing keys never match an explicit selector. + The declaration is an implementation promise, not runtime verification. + """ + + engine: str + operation: str + execution_kind: str + row_effect: str + context: str + codec_version: int | None = None + config_match: tuple[tuple[str, ConfigValue], ...] = () + + def __post_init__(self) -> None: + """Reject malformed metadata before it can advertise support.""" + _require_choice("engine", self.engine, _ENGINES) + _require_choice("operation", self.operation, ("fit", "apply")) + _require_choice("execution_kind", self.execution_kind, ("native", "python_batch", "local")) + _require_choice("row_effect", self.row_effect, ("preserve", "filter", "expand")) + _require_choice("context", self.context, ("row", "group", "window", "global")) + if self.codec_version is not None: + _require_positive_integer("codec_version", self.codec_version) + _validate_config_match(self.config_match) + + def matches_config(self, config: Mapping[str, Any]) -> bool: + """Require every selector, distinguishing booleans from numeric values.""" + return all( + key in config and type(config[key]) is type(value) and config[key] == value + for key, value in self.config_match + ) + + +def validate_capabilities(capabilities: tuple[ExecutionCapability, ...]) -> None: + """Require immutable, validated declarations on a registered calculator.""" + if not isinstance(capabilities, tuple) or any( + not isinstance(item, ExecutionCapability) for item in capabilities + ): + raise ValueError("execution_capabilities must be a tuple of ExecutionCapability objects.") + + +def require_capability( + node_type: str, operation: str, engine: str, *, config: Mapping[str, Any] +) -> None: + """Reject undeclared execution without initializing an engine or estimator. + + Existing local pipelines are unaffected until they explicitly use this + preflight. An empty declaration means unsupported, including for local + engines; it does not remove the existing local execution path. + + Raises: + UnsupportedExecutionError: The node, operation, engine or configuration + has no matching explicit execution declaration. + """ + from ..registry import NodeRegistry # noqa: PLC0415 - registry validates these declarations + + try: + _require_choice("operation", operation, ("fit", "apply")) + _require_choice("engine", engine, _ENGINES) + calculator = NodeRegistry.get_calculator(node_type) + except ValueError as exc: + raise UnsupportedExecutionError(node_type, operation, engine, str(exc)) from exc + capabilities = vars(calculator).get("__execution_capabilities__", ()) + validate_capabilities(capabilities) + for capability in capabilities: + if ( + capability.engine == engine + and capability.operation == operation + and capability.matches_config(config) + ): + return + raise UnsupportedExecutionError( + node_type, operation, engine, "No declared support for this operation and configuration." + ) diff --git a/skyulf-core/skyulf/core/execution.py b/skyulf-core/skyulf/core/execution.py new file mode 100644 index 000000000..29b34bf46 --- /dev/null +++ b/skyulf-core/skyulf/core/execution.py @@ -0,0 +1,79 @@ +"""Immutable execution declarations, independent of optional runtime packages.""" + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +_ENGINES = ("pandas", "polars", "spark") + + +def _require_choice(name: str, value: object, choices: tuple[str, ...]) -> None: + """Reject unknown names without coercing values into supported choices.""" + if not isinstance(value, str) or value not in choices: + raise ValueError(f"{name} must be one of {choices}; got {value!r}.") + + +def _require_positive_integer(name: str, value: object) -> None: + """Reject booleans and implicit numeric coercion for resource limits.""" + if type(value) is not int or value <= 0: + raise ValueError(f"{name} must be a positive integer.") + + +def _validate_row_keys(keys: tuple[str, ...]) -> None: + """Require stable, distinct names without accepting a mutable container.""" + if not isinstance(keys, tuple) or not keys: + raise ValueError("row_keys must be a nonempty tuple of column names.") + if any(not isinstance(key, str) or not key.strip() for key in keys): + raise ValueError("row_keys must contain nonempty column names.") + if len(set(keys)) != len(keys): + raise ValueError("row_keys must contain distinct column names.") + + +@dataclass(frozen=True) +class FrameSpec: + """Declare observation identity and an optional target in a single frame. + + This validates names only. Checking key values for nulls or duplicates + belongs to the runtime that receives the actual dataframe. + """ + + row_keys: tuple[str, ...] + target: str | None = None + + def __post_init__(self) -> None: + """Validate identity names without reading or modifying any data.""" + _validate_row_keys(self.row_keys) + if self.target is not None: + if not isinstance(self.target, str) or not self.target.strip(): + raise ValueError("target must be a nonempty column name or None.") + if self.target in self.row_keys: + raise ValueError("target must not also be a row_keys column.") + + +@dataclass(frozen=True) +class ExecutionOptions: + """Validate an explicit engine and resource budgets without activating it. + + These declarations do not install a runtime or enable node capabilities. + A Python batch row limit is not a guarantee about its memory footprint. + """ + + engine: str + state_max_bytes: int = 8 * 1024 * 1024 + python_batch_rows: int = 4096 + model_max_bytes: int = 256 * 1024 * 1024 + + def __post_init__(self) -> None: + """Reject invalid selections and limits before runtime submission.""" + _require_choice("engine", self.engine, _ENGINES) + for field in ("state_max_bytes", "python_batch_rows", "model_max_bytes"): + _require_positive_integer(field, getattr(self, field)) + + @classmethod + def from_config(cls, config: Mapping[str, Any]) -> "ExecutionOptions": + """Parse options strictly; unknown fields raise TypeError. + + Unlike legacy node configuration, execution configuration never ignores + misspelled fields. The caller's mapping is not modified. + """ + return cls(**dict(config)) diff --git a/skyulf-core/skyulf/registry.py b/skyulf-core/skyulf/registry.py index 3ac85eeca..dc731b940 100644 --- a/skyulf-core/skyulf/registry.py +++ b/skyulf-core/skyulf/registry.py @@ -8,7 +8,10 @@ import logging import warnings from threading import Lock -from typing import Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar + +if TYPE_CHECKING: + from .core.capabilities import ExecutionCapability logger = logging.getLogger(__name__) @@ -31,14 +34,28 @@ class NodeRegistry: _lock = Lock() @classmethod - def register(cls, name: str, applier_cls: type, metadata: dict[str, Any] | None = None): + def register( + cls, + name: str, + applier_cls: type, + metadata: dict[str, Any] | None = None, + *, + execution_capabilities: tuple["ExecutionCapability", ...] | None = None, + ): """Decorator to register a Calculator/Applier pair. Args: name: The unique string identifier for the node (e.g. 'random_forest'). applier_cls: The class of the Applier (must be passed as we decorate the Calculator). metadata: Optional dictionary of UI metadata. + execution_capabilities: Optional immutable declarations for explicit + execution preflight. Omission preserves declarations on aliases. """ + if execution_capabilities is not None: + # Avoid loading core and its registry consumers while nodes import. + from .core.capabilities import validate_capabilities # noqa: PLC0415 + + validate_capabilities(execution_capabilities) def wrapper(calculator_cls): with cls._lock: @@ -49,6 +66,8 @@ def wrapper(calculator_cls): cls._calculators[name] = calculator_cls cls._appliers[name] = applier_cls + if execution_capabilities is not None: + calculator_cls.__execution_capabilities__ = execution_capabilities # 1. Use passed metadata if available if metadata is not None: diff --git a/skyulf-core/tests/unit/test_execution_capabilities.py b/skyulf-core/tests/unit/test_execution_capabilities.py new file mode 100644 index 000000000..7ab347c76 --- /dev/null +++ b/skyulf-core/tests/unit/test_execution_capabilities.py @@ -0,0 +1,221 @@ +"""Explicit per-operation support must not turn into automatic local fallback.""" + +from typing import Any + +import pytest + +from skyulf.registry import NodeRegistry + + +@pytest.fixture +def isolated_registry(monkeypatch): + """Restore registry dictionaries after tests register local probe nodes.""" + for name in ("_calculators", "_appliers", "_metadata"): + monkeypatch.setattr(NodeRegistry, name, dict(getattr(NodeRegistry, name))) + + +def test_all_existing_nodes_reject_undeclared_spark_support(): + """An engine name alone must not advertise distributed execution for any node.""" + import skyulf.preprocessing # noqa: F401 - populate real node registrations + from skyulf.core.capabilities import UnsupportedExecutionError, require_capability + + nodes = NodeRegistry.get_all_metadata() + assert nodes + for node in nodes: + for operation in ("fit", "apply"): + with pytest.raises(UnsupportedExecutionError) as exc: + require_capability(node, operation, "spark", config={}) + assert (exc.value.node_type, exc.value.operation, exc.value.engine) == ( + node, + operation, + "spark", + ) + assert exc.value.reason + + +def test_support_is_operation_and_config_specific(isolated_registry): + """Supporting one imputation strategy must not enable another or its fit operation.""" + from skyulf.core.capabilities import ( + ExecutionCapability, + UnsupportedExecutionError, + require_capability, + ) + + @NodeRegistry.register( + "capability_probe", + object, + execution_capabilities=( + ExecutionCapability( + engine="spark", + operation="apply", + execution_kind="native", + row_effect="preserve", + context="row", + codec_version=1, + config_match=(("strategy", "mean"),), + ), + ), + ) + class Probe: + """A registered declaration without any executable estimator methods.""" + + assert NodeRegistry.get_calculator("capability_probe") is Probe + assert ( + require_capability("capability_probe", "apply", "spark", config={"strategy": "mean"}) + is None + ) + for operation, config in [ + ("fit", {"strategy": "mean"}), + ("apply", {}), + ("apply", {"strategy": "median"}), + ]: + with pytest.raises(UnsupportedExecutionError): + require_capability("capability_probe", operation, "spark", config=config) + + +def test_alias_shares_calculator_capabilities(isolated_registry): + """Registering the same calculator under an alias must preserve its capabilities.""" + from skyulf.core.capabilities import ExecutionCapability, require_capability + + class Probe: + """Share the exact same implementation under two registry names.""" + + capability = ExecutionCapability( + engine="spark", + operation="apply", + execution_kind="native", + row_effect="preserve", + context="row", + ) + NodeRegistry.register("canonical_probe", object, execution_capabilities=(capability,))(Probe) + NodeRegistry.register("alias_probe", object)(Probe) + assert require_capability("canonical_probe", "apply", "spark", config={}) is None + assert require_capability("alias_probe", "apply", "spark", config={}) is None + + +@pytest.mark.parametrize( + "change", + [ + {"engine": "cloud"}, + {"operation": "predict"}, + {"execution_kind": "automatic"}, + {"row_effect": "unknown"}, + {"context": "unknown"}, + {"codec_version": 0}, + {"codec_version": True}, + {"config_match": (("strategy", []),)}, + {"config_match": (("strategy", "mean"), ("strategy", "median"))}, + ], +) +def test_invalid_declarations_fail_before_registration(change): + """Malformed capability metadata must not become an execution permission.""" + from skyulf.core.capabilities import ExecutionCapability + + kwargs: dict[str, Any] = { + "engine": "spark", + "operation": "apply", + "execution_kind": "native", + "row_effect": "preserve", + "context": "row", + } + kwargs.update(change) + with pytest.raises(ValueError): + ExecutionCapability(**kwargs) + + +def test_unknown_node_has_structured_rejection(): + """An unknown node should report the requested operation without running anything.""" + from skyulf.core.capabilities import UnsupportedExecutionError, require_capability + + with pytest.raises(UnsupportedExecutionError) as exc: + require_capability("missing_probe", "apply", "spark", config={}) + assert exc.value.node_type == "missing_probe" + assert "not found" in exc.value.reason + + +def test_subclass_must_declare_its_own_support(isolated_registry): + """Changing an implementation through inheritance must not inherit execution permission.""" + from skyulf.core.capabilities import ( + ExecutionCapability, + UnsupportedExecutionError, + require_capability, + ) + + @NodeRegistry.register( + "parent_probe", + object, + execution_capabilities=( + ExecutionCapability( + engine="spark", + operation="apply", + execution_kind="native", + row_effect="preserve", + context="row", + ), + ), + ) + class Parent: + """Declare support for one implementation.""" + + @NodeRegistry.register("child_probe", object) + class Child(Parent): + """Represent a replacement implementation with no verified declaration.""" + + assert NodeRegistry.get_calculator("child_probe") is Child + with pytest.raises(UnsupportedExecutionError): + require_capability("child_probe", "apply", "spark", config={}) + + +@pytest.mark.parametrize("config", [{}, {"count": True}, {"count": 1.0}, {"count": "1"}]) +def test_selectors_do_not_coerce_or_supply_missing_values(config): + """A numeric selector must not accidentally authorize a boolean or absent setting.""" + from skyulf.core.capabilities import ExecutionCapability + + capability = ExecutionCapability( + engine="spark", + operation="apply", + execution_kind="native", + row_effect="preserve", + context="row", + config_match=(("count", 1),), + ) + assert capability.matches_config({"count": 1}) + assert not capability.matches_config(config) + + +@pytest.mark.parametrize("declarations", [[], (object(),)]) +def test_registry_rejects_invalid_declaration_container(declarations, isolated_registry): + """Malformed support metadata must not partially register a calculator.""" + with pytest.raises(ValueError, match="execution_capabilities"): + NodeRegistry.register("invalid_probe", object, execution_capabilities=declarations) + with pytest.raises(ValueError, match="not found"): + NodeRegistry.get_calculator("invalid_probe") + + +def test_contract_imports_leave_optional_runtimes_unloaded(): + """Base installations must query execution support without importing optional runtimes.""" + import subprocess + import sys + + code = """ +import sys +from skyulf.core.execution import ExecutionOptions +from skyulf.core.capabilities import require_capability, UnsupportedExecutionError +ExecutionOptions(engine="spark") +try: + require_capability("SimpleImputer", "fit", "spark", config={}) +except UnsupportedExecutionError: + pass +else: + raise AssertionError("undeclared Spark support was accepted") +assert "pyspark" not in sys.modules +assert "mlflow" not in sys.modules +""" + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + assert result.returncode == 0, result.stderr diff --git a/skyulf-core/tests/unit/test_execution_contract.py b/skyulf-core/tests/unit/test_execution_contract.py new file mode 100644 index 000000000..bc34485d5 --- /dev/null +++ b/skyulf-core/tests/unit/test_execution_contract.py @@ -0,0 +1,84 @@ +"""Execution options must reject ambiguous identities and implicit coercion.""" + +from dataclasses import FrozenInstanceError + +import pytest + + +def test_execution_options_preserve_explicit_engine(): + """Selecting a runtime must not change the process's current dataframe engine.""" + from skyulf.core.execution import ExecutionOptions + from skyulf.engines import get_engine + + before = get_engine().name + options = ExecutionOptions(engine="spark", python_batch_rows=17) + assert options.engine == "spark" + assert options.python_batch_rows == 17 + assert get_engine().name == before + + +@pytest.mark.parametrize("engine", ["cloud", "databricks", "Spark", "", None]) +def test_execution_options_reject_unknown_engine(engine): + """A platform or misspelled engine must not silently select a fallback.""" + from skyulf.core.execution import ExecutionOptions + + with pytest.raises(ValueError, match="engine"): + ExecutionOptions(engine=engine) + + +@pytest.mark.parametrize("field", ["state_max_bytes", "python_batch_rows", "model_max_bytes"]) +@pytest.mark.parametrize("value", [0, -1, True, 1.5, "12"]) +def test_execution_options_require_positive_integer_limits(field, value): + """Invalid resource limits must fail before a distributed job is submitted.""" + from skyulf.core.execution import ExecutionOptions + + with pytest.raises(ValueError, match=field): + ExecutionOptions.from_config({"engine": "spark", field: value}) + + +def test_execution_config_rejects_typo(): + """A misspelled batch limit must not be ignored by permissive node config parsing.""" + from skyulf.core.execution import ExecutionOptions + + with pytest.raises(TypeError, match="python_batch_row"): + ExecutionOptions.from_config({"engine": "spark", "python_batch_row": 17}) + + +def test_execution_config_does_not_mutate_input(): + """Parsing must not consume configuration shared with another execution.""" + from skyulf.core.execution import ExecutionOptions + + config = {"engine": "polars", "python_batch_rows": 17} + options = ExecutionOptions.from_config(config) + assert config == {"engine": "polars", "python_batch_rows": 17} + assert options.engine == "polars" + + +@pytest.mark.parametrize("keys", [(), ("id", "id"), ("",), (" ",), (1,), ["id"], "id"]) +def test_frame_spec_rejects_ambiguous_keys(keys): + """Row matching requires a nonempty immutable tuple of distinct column names.""" + from skyulf.core.execution import FrameSpec + + with pytest.raises(ValueError, match="row_keys"): + FrameSpec(row_keys=keys) + + +@pytest.mark.parametrize("target", ["id", "", " ", 1]) +def test_frame_spec_rejects_invalid_target(target): + """The label column must not also identify an observation.""" + from skyulf.core.execution import FrameSpec + + with pytest.raises(ValueError, match="target"): + FrameSpec(row_keys=("id",), target=target) + + +def test_contracts_are_immutable(): + """A concurrent caller must not be able to mutate another run's options.""" + from skyulf.core.execution import ExecutionOptions, FrameSpec + + spec = FrameSpec(row_keys=("entity", "event"), target="label") + options = ExecutionOptions(engine="pandas") + for instance, field, value in [(spec, "target", "other"), (options, "engine", "spark")]: + with pytest.raises(FrozenInstanceError): + setattr(instance, field, value) + assert spec.row_keys == ("entity", "event") From f8a353a7ed938b1d2cb8770d998564e6324ea437 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 20:31:41 +0300 Subject: [PATCH 03/85] feat(core): add optional Spark engine and distributed conversion guards Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 + docs/user_guide/spark.md | 52 +++++++- .../spark_and_mlflow/01-core-spark-plan.md | 8 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 40 +++++- initiatives/spark_and_mlflow/README.md | 4 +- skyulf-core/skyulf/engines/__init__.py | 9 +- skyulf-core/skyulf/engines/protocol.py | 30 ++++- skyulf-core/skyulf/engines/registry.py | 51 +++++-- skyulf-core/skyulf/engines/sklearn_bridge.py | 5 + skyulf-core/skyulf/engines/spark_engine.py | 124 ++++++++++++++++++ .../tests/spark/test_engine_contract.py | 107 +++++++++++++++ .../tests/unit/test_engine_empty_frames.py | 3 + .../tests/unit/test_engines_registry.py | 31 +++-- .../tests/unit/test_spark_optional_import.py | 57 ++++++++ 14 files changed, 484 insertions(+), 43 deletions(-) create mode 100644 skyulf-core/skyulf/engines/spark_engine.py create mode 100644 skyulf-core/tests/spark/test_engine_contract.py create mode 100644 skyulf-core/tests/unit/test_spark_optional_import.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index bd9ea5919..5932a6386 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -24,6 +24,12 @@ execution and MLflow adapters remain under development. produce structured errors without executing a node. Existing local pipelines remain unchanged; these contracts do not enable Spark nodes yet. +- Optional Spark engine adapter with real dataframe detection and a separate + distributed metadata/projection protocol. Local conversion and sklearn + entry points reject Spark inputs without collecting data. Sessions remain + caller-owned; base imports require neither PySpark nor MLflow. This adds no + native FE node or model inference capability yet. + ### Planned scope — not yet available - Native Spark feature engineering with explicit fit/apply capabilities and diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index a95cef1b1..14c527f5e 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -1,8 +1,8 @@ # Spark: development setup and current support Spark support is under development for 0.9.0. The optional dependency and -runtime tests are available in the development checkout. **Skyulf's Spark -engine, native nodes and distributed model inference are not available yet.** +runtime tests and Spark engine adapter are available in the development checkout. +**Native nodes and distributed model inference are not available yet.** Installing the extra does not convert a pandas/Polars pipeline to Spark. ## Why a separate environment? @@ -71,6 +71,52 @@ keep the dataset in Spark and transfer bounded learned state when supported. Python model inference on Spark workers is a separate capability from native Spark model training. +## Spark engine adapter + +The adapter detects real Spark dataframes without changing the default local +engine. Importing Skyulf does not import PySpark or MLflow. Requesting the Spark +engine without its optional dependency raises an explicit installation error. + +After creating your own `spark` session, you can run: + +```python +from skyulf.engines import EngineRegistry, SparkEngine, get_engine + +local_default = get_engine() +frame = spark.range(10).repartition(2) +assert get_engine(frame) is SparkEngine +wrapped = EngineRegistry.wrap(frame) +selected = wrapped.select(["id"]) +assert selected.columns == ["id"] +assert selected.schema == frame.schema +assert selected.to_native().count() == 10 # Explicit native Spark action. +assert get_engine() is local_default +``` + +The separate `DistributedDataFrame` protocol exposes `columns`, `schema`, +`select` and `to_native`. Projection treats names literally, including dots and +backticks; an empty projection keeps the rows. Schema access can require query +analysis, but these adapter operations do not collect rows or count them. + +The local `SkyulfDataFrame` protocol remains for pandas/Polars. Spark wrappers +reject `len`, `shape`, `to_pandas`, `to_numpy` and `to_arrow` with +`DistributedMaterializationError`. `SparkEngine.to_numpy` and `SklearnBridge` +also reject distributed features or targets. Worker inference will have its own +explicit entry point; it is not enabled by this adapter. + +Skyulf neither creates nor retains a Spark session. Use your own +`spark.createDataFrame(...)` to create input; `SparkEngine.from_pandas` and +`create_dataframe` reject calls with this guidance. `to_native()` returns the +original distributed frame: native actions you call explicitly remain your +responsibility. In particular, Spark's +[`toPandas`](https://spark.apache.org/docs/4.0.3/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.toPandas.html) +collects data into driver memory. + +Validation currently covers classic PySpark 4.0.3 on the local test runtime. +The adapter uses public dataframe APIs, but Databricks and Spark Connect have +not been integration-tested yet. Engine detection does not authorize a Spark +frame to run through existing local-only FE nodes. + ## Execution contracts The development API can validate a future execution request without starting @@ -91,7 +137,7 @@ Engine values are `pandas`, `polars` and `spark`; `databricks` names a platform, not an engine. Unknown configuration fields and nonpositive/noninteger limits are rejected. These immutable objects declare requirements; they do not apply memory limits or validate the actual values in a dataframe. Runtime key-value -validation will arrive with the Spark dataframe adapter. +validation will arrive with the Spark FE dispatcher (SM-03). A capability check distinguishes fit and apply and never falls back to pandas: diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index 99a1fc661..02bcdcd53 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -97,14 +97,14 @@ def test_unimplemented_spark_fit_is_explicit(): `skyulf/engines/{registry,protocol,__init__}.py`, `skyulf/engines/sklearn_bridge.py`. **Üretir:** SparkEngine; `EngineName.SPARK`; açık distributed frame sözleşmesi. -- [ ] Gerçek Spark frame'in `get_engine(frame)` sonucunu ve local default'un +- [x] Gerçek Spark frame'in `get_engine(frame)` sonucunu ve local default'un değişmediğini test et. Paket yokken core importu başarılı kalmalı. -- [ ] Bilinen pyspark frame için engine kurulu/kayıtlı değilse erken dependency +- [x] Bilinen pyspark frame için engine kurulu/kayıtlı değilse erken dependency hatası ekle; bilinmeyen local objelerin mevcut fallback davranışını ayrı koru. -- [ ] `len/shape/to_numpy/toPandas` gerektiren local protocol'ü Spark'a sahte +- [x] `len/shape/to_numpy/toPandas` gerektiren local protocol'ü Spark'a sahte implement etme. Local-only materialization metodları açıklayıcı hata versin; schema/columns/select gibi yetenekleri ayrı dar protocol üzerinden sağla. -- [ ] SklearnBridge Spark veriyi reddetsin. Session yaratma, session singleton +- [x] SklearnBridge Spark veriyi reddetsin. Session yaratma, session singleton tutma veya RDD tabanlı wrapper ekleme. ```python diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index bce4b16ac..2ac8a1d68 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-01 tamamlandı. Sonraki görev: SM-02. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-02 tamamlandı. Sonraki görev: SM-03. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -11,8 +11,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | --- | --- | --- | --- | --- | | SM-00 | Baseline ve Spark test ortamı | — | DONE | Güncel master: 231 baseline; 2 Spark smoke; [kanıt](BASELINE.md) | | SM-01 | Execution/capability kuralları | SM-00 | DONE | Immutable config; registry operation desteği; aşağıda kanıt | -| SM-02 | Spark engine ve conversion sınırı | SM-01 | READY | Spark tanınır; gizli local conversion yok | -| SM-03 | Dispatcher, schema, row keys | SM-02 | WAIT | Key/target korunur; local API çalışır | +| SM-02 | Spark engine ve conversion sınırı | SM-01 | DONE | Gerçek Spark adapter; conversion korumaları; aşağıda kanıt | +| SM-03 | Dispatcher, schema, row keys | SM-02 | READY | Key/target korunur; local API çalışır | | SM-04 | Versioned portable state | SM-03 | WAIT | Limit/version kontrolü; state round-trip | | SM-05 | Native SimpleImputer | SM-04 | WAIT | Mean/constant train-only fit, Spark apply | | SM-06 | Native StandardScaler | SM-05 | WAIT | Population variance ve flag parity | @@ -105,3 +105,37 @@ ve MLflow entegrasyonu henüz yok. doğrudan çalıştırıldı. Kullanıcı belgeleri uygulamayla birlikte güncellendi. - Spark engine/node desteği henüz etkin değil. Existing local pipeline preflight'ı bu yeni API'ye bağlanmadı; SM-03'te yapılacak. Sıradaki görev SM-02. + +## SM-02 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `b9eef16a`; bu kayıt SM-02 çalışma ağacına aittir. +- SparkEngine ve ayrı DistributedDataFrame sözleşmesi eklendi. Gerçek dataframe + tanıma, literal kolon seçimi ve native frame erişimi var; varsayılan local + engine korunur. Eksik Spark dependency/registration local fallback'e gitmez. +- Adapter session oluşturmaz; `len/shape/to_pandas/to_numpy/to_arrow` ve + SklearnBridge üzerinden Spark feature/target dönüşümü açık hata verir. + `from_pandas/create_dataframe` çağırana kendi SparkSession'ını kullanmasını söyler. +- TDD: ilk 12 gerçek Spark testi başarısızdı; adapter sonrası runtime dahil + 14 test geçti. Son iki lazy-operation/namespace testi ve review düzeltmesiyle: + `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, `SKYULF_REQUIRE_SPARK=1`; + `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark + skyulf-core/tests/unit/test_spark_optional_import.py + skyulf-core/tests/unit/test_engines_registry.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm02-spark-reviewed` + → **46 passed**, 11.07 saniye; JVM temiz kapandı. +- PySpark 4.0.3 / Python 3.12.10 / Java 17 profili kullanıldı. Base ortamda + subprocess import engeli PySpark/MLflow yokken core importunu ve local seçimi + doğrular. Aynı test Spark kurulu ortamda da dependency yokluğunu simüle eder. +- Bağımsız review yalnız dependency hata mesajındaki dağıtım adını düzeltti: + `skyulf-core[spark]`. İlk tam core koşusu bu düzeltme sırasında eski toplanmış + test beklentisi/yeni subprocess kaynağı nedeniyle 1 failed verdi; son kaynakla + odaklı test **3 passed**. Son kaynakla tam core tekrarı: + `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q + --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm02-core-reviewed` + → **9875 passed, 84 skipped, 1077 warnings**, 163.31 saniye. +- Ruff check/format ve tam repo ty geçti. Yeni adapter max CCN=3. + `mkdocs build --strict` geçti; Spark rehberindeki runtime/adapter örnekleri + gerçek oturumda çalıştırıldı. Rehber ve 0.9.0 Unreleased changelog güncel. +- Sınır: native FE node, Spark dispatcher veya model inference etkin değil. + Databricks/Connect/uzak CI çalıştırılmadı. Sonraki görev SM-03. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index be627809c..157818219 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00 ve SM-01 tamamlandı; sıradaki görev SM-02.** +Tarih: 2026-09-21. Durum: **SM-00–SM-02 tamamlandı; sıradaki görev SM-03.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-02**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-03**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/engines/__init__.py b/skyulf-core/skyulf/engines/__init__.py index 7f8abc583..959efabd6 100644 --- a/skyulf-core/skyulf/engines/__init__.py +++ b/skyulf-core/skyulf/engines/__init__.py @@ -1,4 +1,4 @@ -"""Engine abstraction: the ``SkyulfDataFrame`` protocol, pandas/polars adapters and registry.""" +"""Local and distributed dataframe protocols, adapters and engine registry.""" from .pandas_engine import PandasEngine from .polars_engine import ( @@ -7,13 +7,16 @@ PolarsEngine, SkyulfPolarsWrapper, ) -from .protocol import PandasBackedFrame, PolarsBackedFrame, SkyulfDataFrame +from .protocol import DistributedDataFrame, PandasBackedFrame, PolarsBackedFrame, SkyulfDataFrame from .registry import BaseEngine, EngineName, EngineRegistry, get_engine +from .spark_engine import DistributedMaterializationError, SkyulfSparkWrapper, SparkEngine __all__ = [ "POLARS_NUMERIC_BOOL_DTYPES", "POLARS_NUMERIC_DTYPES", "BaseEngine", + "DistributedDataFrame", + "DistributedMaterializationError", "EngineName", "EngineRegistry", "PandasBackedFrame", @@ -22,5 +25,7 @@ "PolarsEngine", "SkyulfDataFrame", "SkyulfPolarsWrapper", + "SkyulfSparkWrapper", + "SparkEngine", "get_engine", ] diff --git a/skyulf-core/skyulf/engines/protocol.py b/skyulf-core/skyulf/engines/protocol.py index 3a6fae4b0..a18c9540f 100644 --- a/skyulf-core/skyulf/engines/protocol.py +++ b/skyulf-core/skyulf/engines/protocol.py @@ -1,4 +1,4 @@ -"""Engine-agnostic DataFrame protocols: ``SkyulfDataFrame`` and its pandas/polars refinements.""" +"""Separate local and distributed dataframe contracts without hidden materialization.""" from typing import Any, Protocol, runtime_checkable @@ -7,10 +7,11 @@ @runtime_checkable class SkyulfDataFrame(Protocol): - """The Universal DataFrame Interface for Skyulf. + """The local DataFrame interface for Skyulf. This protocol defines the minimum set of operations that any compute engine - (Pandas, Polars, Spark, Dask) must support to be used within Skyulf nodes. + (pandas or Polars) must support to be used within local Skyulf nodes. + Distributed engines use a separate, narrower protocol. """ @property @@ -84,6 +85,29 @@ def copy(self) -> "SkyulfDataFrame": ... +@runtime_checkable +class DistributedDataFrame(Protocol): + """Metadata and lazy projection without local indexing or conversion semantics.""" + + @property + def columns(self) -> list[str]: + """Return column names without collecting rows.""" + ... + + @property + def schema(self) -> Any: + """Return the native distributed schema.""" + ... + + def select(self, columns: list[str]) -> "DistributedDataFrame": + """Return a lazy projection using literal column names.""" + ... + + def to_native(self) -> Any: + """Return the distributed native dataframe without conversion.""" + ... + + @runtime_checkable class PandasBackedFrame(SkyulfDataFrame, Protocol): """A :class:`SkyulfDataFrame` backed by pandas. diff --git a/skyulf-core/skyulf/engines/registry.py b/skyulf-core/skyulf/engines/registry.py index 354d01efa..80f23f948 100644 --- a/skyulf-core/skyulf/engines/registry.py +++ b/skyulf-core/skyulf/engines/registry.py @@ -7,19 +7,24 @@ import logging from contextvars import ContextVar from enum import StrEnum -from typing import Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, overload + +if TYPE_CHECKING: + import pandas as pd + import polars as pl # protocol.py is a leaf module (no engine imports), so this top-level import is safe. -from .protocol import SkyulfDataFrame +from .protocol import DistributedDataFrame, SkyulfDataFrame logger = logging.getLogger(__name__) class EngineName(StrEnum): - """Enumeration of the compute-engine identities (``pandas``, ``polars``, ``base``).""" + """Enumeration of local and distributed compute-engine identities.""" PANDAS = "pandas" POLARS = "polars" + SPARK = "spark" BASE = "base" @@ -28,6 +33,10 @@ class BaseEngine: name: EngineName = EngineName.BASE + @classmethod + def ensure_available(cls) -> None: + """Validate optional runtime dependencies; local engines need no extra check.""" + @classmethod def is_compatible(cls, data: Any) -> bool: """Check if this engine can handle the given data object.""" @@ -44,8 +53,8 @@ def to_numpy(cls, df: Any) -> Any: raise NotImplementedError @classmethod - def wrap(cls, data: Any) -> "SkyulfDataFrame": - """Wrap the native dataframe in a SkyulfDataFrame compliant wrapper.""" + def wrap(cls, data: Any) -> SkyulfDataFrame | DistributedDataFrame: + """Wrap the native dataframe using its local or distributed contract.""" raise NotImplementedError @classmethod @@ -63,8 +72,7 @@ class EngineRegistry: _active_engine: ClassVar[ContextVar[str]] = ContextVar("skyulf_active_engine", default="polars") # Maps a data object's detected top-level module package to the engine - # name registered for it. "spark"/"dask" are future-proofing: only used - # if/when those engines are actually registered in `_engines`. + # name registered for it. Recognized Spark inputs never fall back locally. _TOP_LEVEL_TO_ENGINE: ClassVar[dict[str, str]] = { "polars": "polars", "pandas": "pandas", @@ -83,7 +91,9 @@ def get(cls, name: str) -> type[BaseEngine]: """Get an engine by name.""" if name not in cls._engines: raise ValueError(f"Engine '{name}' not found. Available: {list(cls._engines.keys())}") - return cls._engines[name] + engine = cls._engines[name] + engine.ensure_available() + return engine @classmethod def set_active_engine(cls, name: str) -> None: @@ -93,8 +103,7 @@ def set_active_engine(cls, name: str) -> None: start with Polars unless a context is explicitly copied into them. Recognized input types still determine their own engine in ``resolve``. """ - if name not in cls._engines: - raise ValueError(f"Engine '{name}' not found. Available: {list(cls._engines.keys())}") + cls.get(name) cls._active_engine.set(name) logger.debug(f"Active engine set to: {name}") @@ -113,6 +122,13 @@ def resolve(cls, data: Any = None) -> type[BaseEngine]: top_level = cls._detect_top_level_package(data) engine_name = cls._TOP_LEVEL_TO_ENGINE.get(top_level) + if engine_name == "spark": + if "spark" not in cls._engines: + raise ImportError("Spark engine is not registered; cannot use a local fallback.") + engine = cls.get("spark") + if not engine.is_compatible(data): + raise TypeError("Spark engine requires a pyspark.sql.DataFrame.") + return engine if engine_name is not None and engine_name in cls._engines: return cls.get(engine_name) @@ -140,7 +156,10 @@ def _detect_top_level_package(data: Any) -> str: """ top_level = type(data).__module__.split(".", 1)[0] if top_level == "skyulf" and hasattr(data, "to_native"): - top_level = type(data.to_native()).__module__.split(".", 1)[0] + data = data.to_native() + top_level = type(data).__module__.split(".", 1)[0] + if any(base.__module__.split(".", 1)[0] == "pyspark" for base in type(data).__mro__): + return "pyspark" return top_level @classmethod @@ -157,8 +176,16 @@ def _warn_unknown_data_type(cls, data: Any) -> None: f"{cls._active_engine.get()}" ) + @overload + @classmethod + def wrap(cls, data: "pd.DataFrame | pl.DataFrame | SkyulfDataFrame") -> SkyulfDataFrame: ... + + @overload + @classmethod + def wrap(cls, data: Any) -> SkyulfDataFrame | DistributedDataFrame: ... + @classmethod - def wrap(cls, data: Any) -> "SkyulfDataFrame": + def wrap(cls, data: Any) -> SkyulfDataFrame | DistributedDataFrame: """Auto-detect engine and wrap the data.""" engine = cls.resolve(data) return engine.wrap(data) diff --git a/skyulf-core/skyulf/engines/sklearn_bridge.py b/skyulf-core/skyulf/engines/sklearn_bridge.py index de26fb9c8..6e9420093 100644 --- a/skyulf-core/skyulf/engines/sklearn_bridge.py +++ b/skyulf-core/skyulf/engines/sklearn_bridge.py @@ -10,6 +10,7 @@ from .pandas_engine import SkyulfPandasWrapper from .polars_engine import SkyulfPolarsWrapper from .registry import get_engine +from .spark_engine import SparkEngine, is_spark_input class SklearnBridge: @@ -54,6 +55,8 @@ def to_sklearn(X: Any, *, validate_features: bool = False) -> tuple[np.ndarray, @staticmethod def validate_features(data: Any) -> None: """Reject raw temporal features before engine conversion can erase their units.""" + if is_spark_input(data): + SparkEngine.to_numpy(data) native = ( data.to_native() if isinstance(data, SkyulfPandasWrapper | SkyulfPolarsWrapper) @@ -116,6 +119,8 @@ def _contains_temporal(values: np.ndarray) -> bool: @staticmethod def _convert_single(data: Any) -> np.ndarray | None: """Convert supported array-like containers without accepting arbitrary scalars.""" + if is_spark_input(data): + SparkEngine.to_numpy(data) if data is None: return None diff --git a/skyulf-core/skyulf/engines/spark_engine.py b/skyulf-core/skyulf/engines/spark_engine.py new file mode 100644 index 000000000..cbcad40d3 --- /dev/null +++ b/skyulf-core/skyulf/engines/spark_engine.py @@ -0,0 +1,124 @@ +"""Optional Spark adapter with no session ownership or driver materialization.""" + +import importlib +from typing import Any, NoReturn + +from .registry import BaseEngine, EngineName, EngineRegistry + + +class DistributedMaterializationError(TypeError): + """A local-only operation was requested for distributed Spark data.""" + + +def _reject_local(operation: str) -> NoReturn: + """Fail before collecting rows or counting a distributed frame.""" + raise DistributedMaterializationError( + f"Spark data is distributed; {operation} is a local-only operation. " + "Use native Spark transformations or an explicitly supported worker inference path. " + "Skyulf will not collect the dataset to the driver." + ) + + +def is_spark_input(data: Any) -> bool: + """Recognize Spark namespaces and subclasses without importing optional dependencies.""" + if isinstance(data, SkyulfSparkWrapper): + return True + return any(base.__module__.split(".", 1)[0] == "pyspark" for base in type(data).__mro__) + + +class SkyulfSparkWrapper: + """Expose lazy projection and metadata without pretending to be a local frame.""" + + def __init__(self, data: Any) -> None: + """Wrap a real Spark DataFrame without starting or storing a session.""" + if not SparkEngine.is_compatible(data): + raise TypeError("Spark engine requires a pyspark.sql.DataFrame.") + self._df = data.to_native() if isinstance(data, SkyulfSparkWrapper) else data + + @property + def columns(self) -> list[str]: + """Return column names without collecting rows.""" + return self._df.columns + + @property + def schema(self) -> Any: + """Return the native Spark schema without collecting rows.""" + return self._df.schema + + def select(self, columns: list[str]) -> "SkyulfSparkWrapper": + """Project literal names, escaping Spark SQL identifiers including backticks.""" + quoted = ["`" + name.replace("`", "``") + "`" for name in columns] + return SkyulfSparkWrapper(self._df.select(*quoted)) + + def to_native(self) -> Any: + """Return the same distributed frame for explicit native Spark operations.""" + return self._df + + def __len__(self) -> NoReturn: + """Reject implicit row counting; native count is an explicit Spark action.""" + _reject_local("len") + + @property + def shape(self) -> NoReturn: + """Reject local shape semantics that would hide a Spark count action.""" + _reject_local("shape") + + def to_pandas(self) -> NoReturn: + """Reject whole-frame collection into pandas on the driver.""" + _reject_local("to_pandas") + + def to_numpy(self) -> NoReturn: + """Reject whole-frame collection into NumPy on the driver.""" + _reject_local("to_numpy") + + def to_arrow(self) -> NoReturn: + """Reject whole-frame collection into Arrow on the driver.""" + _reject_local("to_arrow") + + +class SparkEngine(BaseEngine): + """Resolve real Spark frames lazily; leave session creation to the caller.""" + + name = EngineName.SPARK + + @classmethod + def ensure_available(cls) -> None: + """Load the optional runtime only when Spark is explicitly requested.""" + try: + importlib.import_module("pyspark.sql") + except ImportError as exc: + raise ImportError( + "Spark engine requires the optional skyulf-core[spark] dependency." + ) from exc + + @classmethod + def is_compatible(cls, data: Any) -> bool: + """Accept actual classic/Connect DataFrame classes, not namespace lookalikes.""" + if not is_spark_input(data): + return False + cls.ensure_available() + native = data.to_native() if isinstance(data, SkyulfSparkWrapper) else data + return isinstance(native, importlib.import_module("pyspark.sql").DataFrame) + + @classmethod + def wrap(cls, data: Any) -> SkyulfSparkWrapper: + """Wrap a distributed dataframe without executing its query.""" + return data if isinstance(data, SkyulfSparkWrapper) else SkyulfSparkWrapper(data) + + @classmethod + def to_numpy(cls, df: Any) -> NoReturn: + """Reject implicit conversion of distributed inputs for local sklearn.""" + _reject_local("to_numpy") + + @classmethod + def from_pandas(cls, df: Any) -> NoReturn: + """Require explicit creation through a caller-owned SparkSession.""" + raise TypeError("Use your SparkSession.createDataFrame explicitly; Skyulf owns no session.") + + @classmethod + def create_dataframe(cls, data: Any) -> NoReturn: + """Require explicit creation through a caller-owned SparkSession.""" + raise TypeError("Use your SparkSession.createDataFrame explicitly; Skyulf owns no session.") + + +EngineRegistry.register("spark", SparkEngine) diff --git a/skyulf-core/tests/spark/test_engine_contract.py b/skyulf-core/tests/spark/test_engine_contract.py new file mode 100644 index 000000000..23da09fb6 --- /dev/null +++ b/skyulf-core/tests/spark/test_engine_contract.py @@ -0,0 +1,107 @@ +"""Pin Spark detection, lazy operations and the local conversion boundary.""" + +import pytest + +from skyulf.engines import ( + DistributedDataFrame, + EngineRegistry, + SkyulfDataFrame, + SkyulfSparkWrapper, + get_engine, +) +from skyulf.engines.sklearn_bridge import SklearnBridge + + +def test_detection_preserves_default(spark): + """Recognized distributed inputs must not change unrelated local jobs.""" + before = get_engine() + frame = spark.range(6).repartition(2) + engine = get_engine(frame) + assert engine.name == "spark" + assert engine.is_compatible(frame) + assert get_engine() is before + assert get_engine(engine.wrap(frame)) is engine + + +def test_wrapper_selects_literal_columns_and_empty_rows(spark): + """Projection must preserve special column names and zero-column row counts.""" + frame = spark.createDataFrame([(1, 2), (3, 4)], ["a.b", "c`d"]) + wrapped = EngineRegistry.wrap(frame) + assert isinstance(wrapped, SkyulfSparkWrapper) + assert isinstance(wrapped, DistributedDataFrame) + assert not isinstance(wrapped, SkyulfDataFrame) + assert wrapped.to_native() is frame + assert wrapped.schema == frame.schema + assert wrapped.columns == ["a.b", "c`d"] + selected = wrapped.select(["c`d", "a.b"]).to_native() + assert [tuple(row) for row in selected.collect()] == [(2, 1), (4, 3)] + assert wrapped.select([]).to_native().count() == 2 + + +@pytest.mark.parametrize("operation", ["len", "shape", "to_pandas", "to_numpy", "to_arrow"]) +def test_wrapper_blocks_local_materialization(spark, monkeypatch, operation): + """A local API must fail before triggering any distributed data action.""" + frame = spark.range(4) + wrapped = EngineRegistry.wrap(frame) + assert isinstance(wrapped, SkyulfSparkWrapper) + + def forbidden(*args, **kwargs): + """Detect driver materialization even when the final exception is correct.""" + pytest.fail("Unexpected Spark action") + + for name in ("collect", "count", "toPandas", "toArrow"): + monkeypatch.setattr(type(frame), name, forbidden) + with pytest.raises(TypeError, match="Spark.*distributed"): + if operation == "len": + len(wrapped) + elif operation == "shape": + _ = wrapped.shape + else: + getattr(wrapped, operation)() + + +@pytest.mark.parametrize("wrapped", [False, True]) +@pytest.mark.parametrize("target", [False, True]) +def test_sklearn_rejects_distributed_input(spark, wrapped, target): + """Both model features and labels must avoid implicit driver collection.""" + frame = spark.range(4) + data = EngineRegistry.wrap(frame) if wrapped else frame + data = ([[1], [2]], data) if target else data + with pytest.raises(TypeError, match="Spark.*distributed"): + SklearnBridge.to_sklearn(data, validate_features=True) + + +def test_engine_blocks_local_creation_and_numpy(spark): + """Callers must provide their own Spark session and explicit native creation.""" + engine = get_engine(spark.range(1)) + with pytest.raises(TypeError, match="Spark.*distributed"): + engine.to_numpy(spark.range(1)) + for method in (engine.from_pandas, engine.create_dataframe): + with pytest.raises(TypeError, match="SparkSession"): + method({"a": [1]}) + + +def test_wrap_and_select_do_not_start_sessions_or_collect(spark, monkeypatch): + """Adapter metadata and projection must stay lazy in a caller-owned session.""" + frame = spark.range(10).repartition(2) + + def forbidden(*args, **kwargs): + """Fail on hidden session creation or row materialization.""" + pytest.fail("Unexpected session creation or Spark action") + + monkeypatch.setattr(type(spark).Builder, "getOrCreate", forbidden) + for name in ("collect", "count", "toPandas", "toArrow"): + monkeypatch.setattr(type(frame), name, forbidden) + wrapped = EngineRegistry.wrap(frame) + assert isinstance(wrapped, SkyulfSparkWrapper) + selected = wrapped.select(["id"]) + assert selected.columns == ["id"] + assert selected.schema == frame.schema + assert wrapped.to_native() is frame + + +def test_spark_namespace_object_is_not_a_dataframe(spark): + """Detection must reject namespace lookalikes even when PySpark is installed.""" + lookalike = type("Lookalike", (), {"__module__": "pyspark.sql.dataframe"})() + with pytest.raises(TypeError, match="pyspark.sql.DataFrame"): + get_engine(lookalike) diff --git a/skyulf-core/tests/unit/test_engine_empty_frames.py b/skyulf-core/tests/unit/test_engine_empty_frames.py index 69ecb8e94..2d7c321b2 100644 --- a/skyulf-core/tests/unit/test_engine_empty_frames.py +++ b/skyulf-core/tests/unit/test_engine_empty_frames.py @@ -7,6 +7,8 @@ import polars as pl import pytest +from skyulf.engines.pandas_engine import SkyulfPandasWrapper +from skyulf.engines.polars_engine import SkyulfPolarsWrapper from skyulf.engines.registry import EngineRegistry from skyulf.engines.sklearn_bridge import SklearnBridge @@ -70,6 +72,7 @@ def test_zero_sample_projection_stays_empty(engine_name): """Retaining height must not invent samples for genuinely empty input.""" engine = EngineRegistry.get(engine_name) empty = engine.wrap(engine.from_pandas(pd.DataFrame({"a": []}))).select([]) + assert isinstance(empty, SkyulfPandasWrapper | SkyulfPolarsWrapper) X, _ = SklearnBridge.to_sklearn(empty.drop([]).copy()) assert X.shape == (0, 0) assert empty.to_pandas().shape == (0, 0) diff --git a/skyulf-core/tests/unit/test_engines_registry.py b/skyulf-core/tests/unit/test_engines_registry.py index dcd03fcb4..8e7a918af 100644 --- a/skyulf-core/tests/unit/test_engines_registry.py +++ b/skyulf-core/tests/unit/test_engines_registry.py @@ -200,15 +200,16 @@ def test_get_engine_helper_matches_resolve(): assert get_engine(df) is EngineRegistry.resolve(df) -def test_resolve_pyspark_like_module_falls_back_without_spark_engine(): - """A pyspark-namespaced type with no registered 'spark' engine should fall back to default.""" +def test_resolve_pyspark_like_module_rejects_without_spark_engine(monkeypatch): + """Recognized distributed data must never reach the local fallback.""" + monkeypatch.delitem(EngineRegistry._engines, "spark") class _FakePysparkFrame: pass _FakePysparkFrame.__module__ = "pyspark.sql.dataframe" - resolved = EngineRegistry.resolve(_FakePysparkFrame()) - assert resolved is EngineRegistry.resolve() + with pytest.raises(ImportError, match="Spark engine is not registered"): + EngineRegistry.resolve(_FakePysparkFrame()) def test_resolve_dask_like_module_falls_back_without_dask_engine(): @@ -222,23 +223,25 @@ class _FakeDaskFrame: assert resolved is EngineRegistry.resolve() -def test_resolve_pyspark_like_module_uses_registered_spark_engine(): +def test_resolve_pyspark_like_module_uses_registered_spark_engine(monkeypatch): """When a 'spark' engine is registered, a pyspark-namespaced type should resolve to it.""" class DummySparkEngine(BaseEngine): name = EngineName.BASE - EngineRegistry.register("spark", DummySparkEngine) - try: + @classmethod + def is_compatible(cls, data): + """Let the test adapter explicitly accept the synthetic input.""" + return True - class _FakePysparkFrame: - pass + monkeypatch.setitem(EngineRegistry._engines, "spark", DummySparkEngine) - _FakePysparkFrame.__module__ = "pyspark.sql.dataframe" - resolved = EngineRegistry.resolve(_FakePysparkFrame()) - assert resolved is DummySparkEngine - finally: - del EngineRegistry._engines["spark"] + class _FakePysparkFrame: + pass + + _FakePysparkFrame.__module__ = "pyspark.sql.dataframe" + resolved = EngineRegistry.resolve(_FakePysparkFrame()) + assert resolved is DummySparkEngine def test_resolve_dask_like_module_uses_registered_dask_engine(): diff --git a/skyulf-core/tests/unit/test_spark_optional_import.py b/skyulf-core/tests/unit/test_spark_optional_import.py new file mode 100644 index 000000000..d7b0599ce --- /dev/null +++ b/skyulf-core/tests/unit/test_spark_optional_import.py @@ -0,0 +1,57 @@ +"""Verify optional Spark boundaries without requiring a JVM or PySpark install.""" + +import subprocess +import sys + +import pandas as pd +import pytest + +from skyulf.engines import EngineRegistry, SparkEngine + + +def test_core_import_does_not_load_optional_runtimes(): + """Base installs must import and run local engines even if extras are unavailable.""" + code = """ +import importlib.abc +import sys +class BlockExtras(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname.split('.')[0] in {'pyspark', 'mlflow'}: + raise ImportError('optional runtime deliberately unavailable') +sys.meta_path.insert(0, BlockExtras()) +import skyulf +import pandas as pd +from skyulf.engines import EngineRegistry, SparkEngine, get_engine +assert get_engine().name == 'polars' +assert get_engine(pd.DataFrame({'x': [1]})).name == 'pandas' +assert not SparkEngine.is_compatible(pd.DataFrame()) +assert not any(name.split('.')[0] in {'pyspark', 'mlflow'} for name in sys.modules) +for operation in (lambda: EngineRegistry.get('spark'), + lambda: EngineRegistry.set_active_engine('spark')): + try: + operation() + except ImportError as exc: + assert 'skyulf-core[spark]' in str(exc) + else: + raise AssertionError('missing optional dependency accepted') +assert get_engine().name == 'polars' +""" + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, timeout=30 + ) + assert result.returncode == 0, result.stderr + + +def test_spark_wrapper_rejects_local_frames(): + """Wrapping local data must not create an implicit Spark session.""" + with pytest.raises(TypeError, match="pyspark.sql.DataFrame"): + SparkEngine.wrap(pd.DataFrame({"x": [1]})) + + +def test_namespace_lookalike_requires_real_dataframe(monkeypatch): + """A matching module path must not authorize a non-dataframe Spark object.""" + monkeypatch.setattr(SparkEngine, "ensure_available", classmethod(lambda cls: None)) + monkeypatch.setattr(SparkEngine, "is_compatible", classmethod(lambda cls, data: False)) + lookalike = type("Lookalike", (), {"__module__": "pyspark.sql.dataframe"})() + with pytest.raises(TypeError, match="pyspark.sql.DataFrame"): + EngineRegistry.resolve(lookalike) From 2d8cd8e52724f49462006d5256a45219cea64483 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 20:32:32 +0300 Subject: [PATCH 04/85] documents --- .gitignore | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.gitignore b/.gitignore index daebbdf86..1111908b8 100644 --- a/.gitignore +++ b/.gitignore @@ -180,3 +180,12 @@ sast/xss-results.md .qoder/skills/modern-coding-standards/SKILL.md docs/reports/2026-09-21-spark-core-inventory.md docs/reports/2026-09-21-spark-databricks-readiness.md +initiatives/deep-learning/2026-09-20-delivery-design.md +initiatives/deep-learning/2026-09-20-foundation-implementation-plan.md +initiatives/deep-learning/TASK_QUEUE.md +initiatives/analysis/canvas-notebook-parity-2026-09-20.md +initiatives/analysis/notebook-runtime-validation-2026-09-20.md +initiatives/analysis/qwen_backend_ve_frontend_bug_sonuclari.md +initiatives/analysis/some_ideas.md +initiatives/reports/2026-09-21-spark-core-inventory.md +initiatives/reports/2026-09-21-spark-databricks-readiness.md From 44b5241e2466a6f0b129a6eaf631dcc29fc7b7e4 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 20:51:23 +0300 Subject: [PATCH 05/85] feat(core): add keyed Spark feature execution and capability preflight Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 7 + docs/user_guide/spark.md | 87 +++++- .../spark_and_mlflow/01-core-spark-plan.md | 8 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 48 +++- initiatives/spark_and_mlflow/README.md | 4 +- skyulf-core/skyulf/core/schema.py | 24 +- skyulf-core/skyulf/preprocessing/_spark.py | 250 +++++++++++++++++ .../skyulf/preprocessing/dispatcher.py | 123 ++++----- skyulf-core/skyulf/preprocessing/pipeline.py | 38 ++- skyulf-core/skyulf/utils.py | 22 ++ .../tests/spark/test_frame_contract.py | 254 ++++++++++++++++++ .../unit/test_feature_execution_options.py | 38 +++ .../unit/test_preprocessing_dispatcher.py | 10 +- 13 files changed, 831 insertions(+), 82 deletions(-) create mode 100644 skyulf-core/skyulf/preprocessing/_spark.py create mode 100644 skyulf-core/tests/spark/test_frame_contract.py create mode 100644 skyulf-core/tests/unit/test_feature_execution_options.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 5932a6386..28564bb6e 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -30,6 +30,13 @@ execution and MLflow adapters remain under development. caller-owned; base imports require neither PySpark nor MLflow. This adds no native FE node or model inference capability yet. +- Opt-in keyed Spark `FeatureEngineer` entry point: validates schema and composite + keys, excludes keys/target from feature selection, checks all node capabilities + before execution, and verifies key/target preservation after native steps. + Spark dispatcher preparation preserves distributed frames; local FE behavior + remains available. Unknown distributed metrics replace local profiling guesses. + Built-in Spark FE nodes remain unsupported pending their native implementations. + ### Planned scope — not yet available - Native Spark feature engineering with explicit fit/apply capabilities and diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 14c527f5e..205021b07 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -1,7 +1,8 @@ # Spark: development setup and current support Spark support is under development for 0.9.0. The optional dependency and -runtime tests and Spark engine adapter are available in the development checkout. +runtime tests, Spark engine adapter and keyed FeatureEngineer entry point are +available in the development checkout. **Native nodes and distributed model inference are not available yet.** Installing the extra does not convert a pandas/Polars pipeline to Spark. @@ -136,8 +137,82 @@ identity = FrameSpec(row_keys=("customer_id", "event_id"), target="label") Engine values are `pandas`, `polars` and `spark`; `databricks` names a platform, not an engine. Unknown configuration fields and nonpositive/noninteger limits are rejected. These immutable objects declare requirements; they do not apply -memory limits or validate the actual values in a dataframe. Runtime key-value -validation will arrive with the Spark FE dispatcher (SM-03). +memory limits themselves. The Spark FeatureEngineer entry point validates actual +key values as described below; state/model budgets belong to later execution stages. + +## Keyed Spark FeatureEngineer entry point + +Use a single Spark dataframe with explicit identity columns. The initial path +supports flat scalar schemas and native operations that preserve rows. Nested +array/map/struct, Decimal and other unsupported types are rejected. Column names +must be unambiguous under the session's case-sensitivity setting. + +This working example exercises the input boundary with an empty pipeline; +it does not perform feature transformations: + +```python +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.preprocessing.pipeline import FeatureEngineer + +data = spark.createDataFrame( + [(1, 10.0, 0), (2, 20.0, 1)], + ["customer_id", "amount", "label"], +).repartition(2) +engineer = FeatureEngineer( + [], + frame_spec=FrameSpec(row_keys=("customer_id",), target="label"), + execution_options=ExecutionOptions(engine="spark"), +) +training, metrics = engineer.fit_transform(data) +inference = engineer.transform(data.drop("label")) +assert inference.columns == ["customer_id", "amount"] +assert metrics["summary"]["rows_in"] is None +``` + +Both options are required for Spark. The target must exist during fit when +declared; it can be absent during transform. Composite keys must be unique and +non-null on each input. Separate Spark `(X, y)` pairs and `SplitDataset` inputs +are rejected; label alignment never depends on partition or row position. +`target_column`, if passed to fit, must agree with `FrameSpec.target`. +The `on_split` callback is unavailable on this single-frame entry point. + +Automatic feature selection excludes keys and target. Explicit `columns` cannot +select either. Names are exact and literal, including dots/backticks. Raw inputs +produce raw Spark outputs; wrapped inputs retain their wrapper convention. + +Every step must declare both fit and apply support before fitting starts. Apply +also checks all fitted steps before execution. This path accepts native, +row-preserving operations with row-local apply behavior. Worker Python, window, +filtering and expansion paths require later implementations. No built-in Spark +FE node is enabled yet; unsupported nodes fail before any validation action or fit. +Custom native nodes use the existing engine-keyed dispatcher mapping with a +`"spark"` implementation. It receives the full native frame, `y=None` and the +resolved feature names in `config["columns"]`; the returned frame retains keys +and any target. Fitted parameters must contain what its applier needs. + +### Validation actions and metrics + +Key validation performs a distributed group/count and returns at most one +invalid group to the driver. After each step, distributed multiset comparisons +check that the protected key/target projection is unchanged. These checks detect +changed labels, keys, dropped rows and duplicates even when a custom node claims +to preserve rows. They can scan/shuffle the data and execute the lazy plan again; +this initial correctness path is not a claim of optimized cluster performance. +Only a bounded validation result is collected, never the whole dataset. + +The default metrics do not run a separate dataframe `count()` or local memory +profiler. `rows_in`, `rows_out`, `fit_time` and `peak_memory_bytes` are `None`, +meaning unknown. Per-step `driver_elapsed_seconds` measures caller-observed time +including validation; it is not distributed CPU time or cluster peak memory. +Explicit distributed aggregate metrics are not implemented yet. +The local `get_data_stats` helper rejects Spark input; use the Spark FE metrics. + +Transform preserves key identity, not physical row order, including when +`preserve_rows=True`. Consumers must match outputs by keys. A successful refit +replaces fitted steps; a failed refit leaves the last successful fitted steps +available. Saving portable learned state follows in SM-04. + +### Inspecting declared support A capability check distinguishes fit and apply and never falls back to pandas: @@ -184,8 +259,10 @@ Spark code, certify compatibility or make a window transform batch-independent. - **Windows access denied at shutdown:** a process sandbox can prevent Spark's child-process cleanup. A passing calculation does not prove clean shutdown; use an environment that permits the owned JVM processes to terminate. -- **Engine not found:** this is expected before the Spark engine implementation - is delivered. Do not collect an entire distributed frame into pandas as a workaround. +- **Spark dependency unavailable:** install the optional `skyulf-core[spark]` + dependency in a suitable environment, or use the repository requirements above. +- **Unsupported node:** the keyed entry point is available, but built-in native + FE nodes are still being implemented. Installing Spark does not enable them. MLflow tracking, Unity Catalog registration, Databricks jobs, serving endpoints and Bundle templates are separate integration stages. This page will gain diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index 02bcdcd53..e75f4f04f 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -130,15 +130,15 @@ local engine regression testleri geçer. **Üretir:** FeatureEngineer'ın opt-in `frame_spec`/`execution_options` desteği; ayrı X/y Spark frame'i almayan, tek frame'de target/key koruyan fit/transform yolu. -- [ ] Repartition edilmiş frame'de key/target'ın aynı satırda kaldığı testi yaz. +- [x] Repartition edilmiş frame'de key/target'ın aynı satırda kaldığı testi yaz. Duplicate/null key, eksik kolon ve nested/Decimal unsupported hata testleri ekle. -- [ ] Spark input hazırlığını engine-keyed dispatcher mapping'e ekle; local +- [x] Spark input hazırlığını engine-keyed dispatcher mapping'e ekle; local tuple ve wrapper dönüşlerini değiştirme. Spark destek preflight bütün adımları kontrol etsin; ilk node çalışıp sonraki unsupported node'da geç kalınmasın. -- [ ] Default istatistik toplama Spark'ta count/NumPy conversion başlatmasın. +- [x] Default istatistik toplama Spark'ta count/NumPy conversion başlatmasın. İstenen distributed aggregate metrics ayrı seçilir; local RSS cluster belleği gibi raporlanmaz. Satır sayısı bilinmiyorsa unknown kalır. -- [ ] Feature listesi key/target'ı dışlasın. Kolon adlarında nokta/backtick için +- [x] Feature listesi key/target'ı dışlasın. Kolon adlarında nokta/backtick için doğru quoting ve collision testleri yaz; uydurma internal key ekleme. ```python diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 2ac8a1d68..06e3ad5c9 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-02 tamamlandı. Sonraki görev: SM-03. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-03 tamamlandı. Sonraki görev: SM-04. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -12,8 +12,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-00 | Baseline ve Spark test ortamı | — | DONE | Güncel master: 231 baseline; 2 Spark smoke; [kanıt](BASELINE.md) | | SM-01 | Execution/capability kuralları | SM-00 | DONE | Immutable config; registry operation desteği; aşağıda kanıt | | SM-02 | Spark engine ve conversion sınırı | SM-01 | DONE | Gerçek Spark adapter; conversion korumaları; aşağıda kanıt | -| SM-03 | Dispatcher, schema, row keys | SM-02 | READY | Key/target korunur; local API çalışır | -| SM-04 | Versioned portable state | SM-03 | WAIT | Limit/version kontrolü; state round-trip | +| SM-03 | Dispatcher, schema, row keys | SM-02 | DONE | Keyed Spark FE giriş/preflight; aşağıda kanıt | +| SM-04 | Versioned portable state | SM-03 | READY | Limit/version kontrolü; state round-trip | | SM-05 | Native SimpleImputer | SM-04 | WAIT | Mean/constant train-only fit, Spark apply | | SM-06 | Native StandardScaler | SM-05 | WAIT | Population variance ve flag parity | | SM-07 | Uçtan uca FE kapısı | SM-06 | WAIT | Üç engine çapraz fit/apply; kayıt/yükleme | @@ -139,3 +139,45 @@ ve MLflow entegrasyonu henüz yok. gerçek oturumda çalıştırıldı. Rehber ve 0.9.0 Unreleased changelog güncel. - Sınır: native FE node, Spark dispatcher veya model inference etkin değil. Databricks/Connect/uzak CI çalıştırılmadı. Sonraki görev SM-03. + +## SM-03 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `2d8cd8e5`; bu kayıt SM-03 çalışma ağacına aittir. +- FeatureEngineer `frame_spec` / `execution_options` ile Spark'a opt-in olur. + Yeni `_spark.py` native yürütmeyi local profiler'dan ayırır. Dispatcher input + hazırlığı engine-keyed mapping kullanır. `SkyulfSchema` Spark tiplerini okur. +- Key/target tek frame'de kalır; key null/duplicate ve desteklenmeyen dtype/schema + kontrolleri var. Bütün node fit/apply capability'leri action öncesi kontrol + edilir. Her node sonrası protected projection `exceptAll` karşılaştırması + key/label değişimini, row drop/expand'i reddeder. Validation sonucu limit(1)'dir; + full scan/shuffle maliyeti rehberde yazılıdır. Native node desteği ilan edilmez. +- Otomatik feature listesi key/target dışındadır. Literal dot/backtick kolonlar, + case-insensitive ambiguity ve internal aggregate alias collision testlidir. + Local get_data_stats Spark'ı açıkça reddeder; Spark FE metriklerinde row count, + fit_time ve peak_memory unknown (`None`). Driver süre ölçümü ayrı isimlidir. +- Planlanan base.py/data/dataset.py değişikliği gerekmedi: mevcut local profiler'a + girilmeden routing yapılır; tuple/SplitDataset Spark input sınırda reddedilir. + Local frame/tuple/split API'leri korunur; explicit engine seçimi her split'i denetler. +- TDD: ilk Spark contract koşusu **10 failed**; uygulama sonrası **10 passed**. + Ek güvence testlerinde case-insensitive isim hataları yeniden üretildi ve + düzeltildi. Bağımsız review internal alias bulgusunu verdi; son recheck temiz. +- Son Spark + dispatcher/optional import komutu: + `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, `SKYULF_REQUIRE_SPARK=1`; + `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark + skyulf-core/tests/unit/test_spark_optional_import.py + skyulf-core/tests/unit/test_preprocessing_dispatcher.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm03-spark-reviewed` + → **69 passed**, 61.59 saniye; PySpark 4.0.3/Python 3.12.10/Java 17, temiz kapanış. +- İlk full core **9875 passed, 107 skipped, 1077 warnings**, 170.97 saniye. + Ardından explicit local engine/split seçimindeki iki hata testle üretildi; + fix sonrası yeni 9 test + dispatcher/pipeline/base/optional import **124 passed**. + Son full core komutu: + `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q + --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm03-core-final` + → **9884 passed, 107 skipped, 1077 warnings**, 170.30 saniye. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Spark rehberindeki + beş Python örneği aynı gerçek session'da çalıştırıldı; beklenen unsupported + capability örneği de doğrulandı. Changelog/rehber birlikte güncellendi. +- Sınır: built-in native node, portable state codec, distributed model inference, + explicit aggregate metrics ve Databricks/Connect testi henüz yok. SM-04 sırada. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index 157818219..4549531b2 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-02 tamamlandı; sıradaki görev SM-03.** +Tarih: 2026-09-21. Durum: **SM-00–SM-03 tamamlandı; sıradaki görev SM-04.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-03**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-04**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/core/schema.py b/skyulf-core/skyulf/core/schema.py index e76443871..fde614a17 100644 --- a/skyulf-core/skyulf/core/schema.py +++ b/skyulf-core/skyulf/core/schema.py @@ -18,6 +18,8 @@ from dataclasses import dataclass, field, replace from typing import Any +from ..engines.spark_engine import SkyulfSparkWrapper, is_spark_input + logger = logging.getLogger(__name__) @@ -82,7 +84,27 @@ def from_columns( @classmethod def from_dataframe(cls, df: Any) -> "SkyulfSchema": - """Best-effort schema extraction from a Pandas/Polars/Wrapper frame.""" + """Extract schema metadata from local or Spark frames without collecting rows.""" + if is_spark_input(df): + native = df.to_native() if isinstance(df, SkyulfSparkWrapper) else df + labels = { + "byte": "int8", + "short": "int16", + "integer": "int32", + "long": "int64", + "float": "float32", + "double": "float64", + "boolean": "bool", + "timestamp": "datetime", + "timestamp_ntz": "datetime", + } + return cls( + tuple(native.columns), + { + field.name: labels.get(field.dataType.typeName(), field.dataType.simpleString()) + for field in native.schema.fields + }, + ) raw_cols = getattr(df, "columns", None) cols = list(raw_cols) if raw_cols is not None else [] dtypes = _extract_pandas_dtypes(df) diff --git a/skyulf-core/skyulf/preprocessing/_spark.py b/skyulf-core/skyulf/preprocessing/_spark.py new file mode 100644 index 000000000..38f18e2c8 --- /dev/null +++ b/skyulf-core/skyulf/preprocessing/_spark.py @@ -0,0 +1,250 @@ +"""Keyed native Spark FE execution, isolated from local profiling and X/y alignment.""" + +import importlib +import time +from copy import deepcopy +from functools import reduce +from typing import Any + +from ..core.capabilities import UnsupportedExecutionError, require_capability +from ..core.execution import ExecutionOptions, FrameSpec +from ..data.dataset import SplitDataset +from ..engines import SkyulfSparkWrapper, SparkEngine, get_engine +from ..registry import NodeRegistry +from ..utils import contains_spark_input + + +def use_spark(data: Any, options: ExecutionOptions | None, spec: FrameSpec | None) -> bool: + """Require explicit Spark context and reject engine overrides that contradict input.""" + requested = options is not None and options.engine == "spark" + if contains_spark_input(data) or requested: + if not requested or spec is None: + raise ValueError("Spark requires frame_spec and execution_options(engine='spark').") + if not SparkEngine.is_compatible(data): + raise TypeError( + "FeatureEngineer requires a single Spark dataframe containing keys/target." + ) + return True + if spec is not None: + raise ValueError("frame_spec is currently supported only for Spark execution.") + _validate_local_engine(data, options) + return False + + +def _validate_local_engine(data: Any, options: ExecutionOptions | None) -> None: + """Check opt-in local engine selection without changing legacy defaults.""" + if options is None: + return + if isinstance(data, SplitDataset): + for split in (data.train, data.test, data.validation): + if split is not None: + _validate_local_engine(split, options) + return + features = data[0] if isinstance(data, tuple) else data + if get_engine(features).name != options.engine: + raise ValueError("execution_options engine conflicts with the input engine.") + + +def _column(frame: Any, name: str) -> Any: + """Resolve a literal identifier, including dots and embedded backticks.""" + return frame["`" + name.replace("`", "``") + "`"] + + +def _native(data: Any) -> Any: + """Validate and unwrap a Spark dataframe without materializing it.""" + if not SparkEngine.is_compatible(data): + raise TypeError("Expected a single Spark dataframe from each native FE step.") + return data.to_native() if isinstance(data, SkyulfSparkWrapper) else data + + +def _validate_schema(frame: Any, spec: FrameSpec, *, training: bool) -> None: + """Reject ambiguous or unsupported schemas before any validation action.""" + names = frame.columns + resolved_names = _resolved_names(frame) + if len(set(resolved_names)) != len(names): + raise ValueError("Duplicate Spark column names are unsupported.") + required = set(spec.row_keys) + if training and spec.target is not None: + required.add(spec.target) + missing = required.difference(names) + if missing: + raise ValueError(f"Missing Spark columns: {sorted(missing)}") + supported = { + "byte", + "short", + "integer", + "long", + "float", + "double", + "string", + "boolean", + "date", + "timestamp", + "timestamp_ntz", + } + for field in frame.schema.fields: + if field.dataType.typeName() not in supported: + raise TypeError( + f"Unsupported Spark dtype for {field.name}: {field.dataType.simpleString()}" + ) + + +def _validate_keys(frame: Any, spec: FrameSpec) -> None: + """Check composite key uniqueness/nulls with one bounded validation result.""" + functions = importlib.import_module("pyspark.sql.functions") + count_name = "__skyulf_count" + existing = _resolved_names(frame) + while count_name in existing: + count_name += "_" + grouped = frame.groupBy(*[_column(frame, name) for name in spec.row_keys]).agg( + functions.count(functions.lit(1)).alias(count_name) + ) + invalid = reduce( + lambda a, b: a | b, [_column(grouped, name).isNull() for name in spec.row_keys] + ) + if grouped.filter(invalid | (_column(grouped, count_name) > 1)).limit(1).collect(): + raise ValueError("Spark row_keys must be unique and non-null.") + + +def _resolved_names(frame: Any) -> list[str]: + """Use session identifier rules for schema collisions and internal aliases.""" + if frame.sparkSession.conf.get("spark.sql.caseSensitive") == "true": + return frame.columns + return [name.lower() for name in frame.columns] + + +def _params(config: Any, spec: FrameSpec, frame: Any = None) -> dict[str, Any]: + """Protect identity/target columns while resolving explicit or automatic features.""" + params = deepcopy(dict(config)) + protected = set(spec.row_keys) | {spec.target} + columns = params.get("columns") + _validate_feature_names(columns) + if columns and any(name in protected for name in columns): + raise ValueError("Spark feature columns cannot include row_keys or target.") + if frame is not None: + selected = columns or [name for name in frame.columns if name not in protected] + if set(selected).difference(frame.columns): + raise ValueError("Spark feature columns are missing or duplicated.") + params["columns"] = selected + if spec.target is not None: + params["target_column"] = spec.target + return params + + +def _validate_feature_names(columns: Any) -> None: + """Reject malformed and duplicate explicit column declarations before actions.""" + if columns is None: + return + if not isinstance(columns, list): + raise ValueError("Spark columns must be a list of feature names.") + if any(not isinstance(name, str) for name in columns): + raise ValueError("Spark feature names must be strings.") + if len(set(columns)) != len(columns): + raise ValueError("Spark feature columns are missing or duplicated.") + + +def _supports_native(declarations: Any, operation: str, params: dict) -> bool: + """Match the implemented native preserving path, excluding worker/window paths.""" + for item in declarations: + if (item.engine, item.operation, item.execution_kind, item.row_effect) != ( + "spark", + operation, + "native", + "preserve", + ): + continue + if operation == "apply" and item.context != "row": + continue + if item.matches_config(params): + return True + return False + + +def _preflight(steps: Any, spec: FrameSpec, *, training: bool) -> None: + """Check every operation before any fit or distributed key-validation action.""" + operations = ("fit", "apply") if training else ("apply",) + for step in steps: + node_type = step["transformer"] if training else step["type"] + params = _params(step.get("params", {}), spec) + for operation in operations: + require_capability(node_type, operation, "spark", config=params) + declarations = vars(NodeRegistry.get_calculator(node_type))[ + "__execution_capabilities__" + ] + if not _supports_native(declarations, operation, params): + raise UnsupportedExecutionError( + node_type, + operation, + "spark", + "This entry point requires native row-preserving FE.", + ) + + +def _check_output(before: Any, output: Any, spec: FrameSpec) -> Any: + """Verify protected values and row identity after each declared preserving step.""" + after = _native(output) + _validate_schema(after, spec, training=spec.target in before.columns) + protected = list(spec.row_keys) + if spec.target is not None and spec.target in before.columns: + protected.append(spec.target) + left = before.select(*[_column(before, name) for name in protected]) + right = after.select(*[_column(after, name) for name in protected]) + # Nullable metadata can change harmlessly, but identity/label types cannot. + if left.dtypes != right.dtypes: + raise ValueError("Spark step changed row_keys/target dtypes.") + if left.exceptAll(right).unionByName(right.exceptAll(left)).limit(1).collect(): + raise ValueError("Spark step changed row_keys/target values or row membership.") + return after + + +def fit_spark(data: Any, steps: Any, spec: FrameSpec) -> tuple[Any, dict, list[dict]]: + """Fit/apply native steps transactionally, reporting unknown distributed metrics.""" + _preflight(steps, spec, training=True) + current = _native(data) + _validate_schema(current, spec, training=True) + _validate_keys(current, spec) + records = [] + step_metrics = {} + for index, step in enumerate(steps): + params = _params(step.get("params", {}), spec, current) + node_type = step["transformer"] + calculator = NodeRegistry.get_calculator(node_type)() + applier = NodeRegistry.get_applier(node_type)() + start = time.perf_counter() + artifact = dict(calculator.fit(current, params)) + current = _check_output(current, applier.apply(current, artifact), spec) + step_metrics[f"{index}:{step['name']}"] = { + "driver_elapsed_seconds": time.perf_counter() - start, + "rows_in": None, + "rows_out": None, + "peak_memory_bytes": None, + } + records.append( + { + "name": step["name"], + "type": node_type, + "applier": applier, + "artifact": artifact, + "params": params, + } + ) + summary = {"rows_in": None, "rows_out": None, "peak_memory_bytes": None, "fit_time": None} + metrics = {"summary": summary, "steps": step_metrics, **summary} + return _restore(current, data), metrics, records + + +def transform_spark(data: Any, steps: Any, spec: FrameSpec) -> Any: + """Apply fitted native steps to labeled or unlabeled data using key identity.""" + _preflight(steps, spec, training=False) + current = _native(data) + _validate_schema(current, spec, training=False) + _validate_keys(current, spec) + for step in steps: + _params(step["params"], spec, current) + current = _check_output(current, step["applier"].apply(current, step["artifact"]), spec) + return _restore(current, data) + + +def _restore(frame: Any, original: Any) -> Any: + """Preserve the caller's raw-versus-wrapper return convention.""" + return SkyulfSparkWrapper(frame) if isinstance(original, SkyulfSparkWrapper) else frame diff --git a/skyulf-core/skyulf/preprocessing/dispatcher.py b/skyulf-core/skyulf/preprocessing/dispatcher.py index c426a3b05..fdee2985e 100644 --- a/skyulf-core/skyulf/preprocessing/dispatcher.py +++ b/skyulf-core/skyulf/preprocessing/dispatcher.py @@ -1,7 +1,7 @@ """Dual-engine dispatch for preprocessing nodes. This module owns the *control flow* that lets a single node run on either the -Polars or the Pandas engine: ``apply_dual_engine`` (and its fit counterparts) +Polars, pandas or Spark engine: ``apply_dual_engine`` (and its fit counterparts) unpacks the pipeline input, selects the engine-specific implementation from a mapping keyed by engine name, and repacks the output. It is the single place that branches on the engine. @@ -23,7 +23,13 @@ import pandas as pd -from ..engines import EngineName, SkyulfDataFrame, SkyulfPolarsWrapper, get_engine +from ..engines import ( + EngineName, + SkyulfDataFrame, + SkyulfPolarsWrapper, + SkyulfSparkWrapper, + get_engine, +) from ..utils import pack_pipeline_output, unpack_pipeline_input logger = logging.getLogger(__name__) @@ -152,31 +158,13 @@ def apply_dual_engine( engine = get_engine(X) func = _resolve_impl(implementations, engine.name, "apply") - if engine.name == EngineName.POLARS: - # Unwrap SkyulfPolarsWrapper so the implementation sees a raw - # pl.DataFrame (native pl APIs crash on the wrapper, F-09); re-wrap - # afterwards so the output keeps the caller's engine. - X_prep, was_wrapped = _unwrap_polars_wrapper(X) - try: - X_out, y_out = func(X_prep, y, params) - except Exception as exc: - _log_dispatch_failure(exc, "Polars", "apply", func) - raise - X_out = _rewrap_polars_output(X_out, was_wrapped) - elif engine.name == EngineName.PANDAS: - # Ensure X is pandas - X_prep = X.to_pandas() if hasattr(X, "to_pandas") else X - try: - X_out, y_out = func(X_prep, y, params) - except Exception as exc: - _log_dispatch_failure(exc, "Pandas", "apply", func) - raise - else: - # Registered engine with an implementation but no input-preparation - # path: fail loudly rather than silently collecting to pandas (F-09). - raise NotImplementedError( - f"No '{engine.name}' input-preparation path in apply_dual_engine yet" - ) + X_prep, was_wrapped = _prepare_input(X, engine.name, "apply_dual_engine") + try: + X_out, y_out = func(X_prep, y, params) + except Exception as exc: + _log_dispatch_failure(exc, engine.name.capitalize(), "apply", func) + raise + X_out = _restore_output(X_out, was_wrapped, engine.name) return pack_pipeline_output(X_out, y_out, is_tuple) @@ -207,24 +195,12 @@ def fit_dual_engine( engine = get_engine(X) func = _resolve_impl(implementations, engine.name, "fit") - if engine.name == EngineName.POLARS: - X_prep, _ = _unwrap_polars_wrapper(X) - try: - return dict(func(X_prep, y, params)) - except Exception as exc: - _log_dispatch_failure(exc, "Polars", "fit", func) - raise - elif engine.name == EngineName.PANDAS: - X_prep = X.to_pandas() if hasattr(X, "to_pandas") else X - try: - return dict(func(X_prep, y, params)) - except Exception as exc: - _log_dispatch_failure(exc, "Pandas", "fit", func) - raise - else: - raise NotImplementedError( - f"No '{engine.name}' input-preparation path in fit_dual_engine yet" - ) + X_prep, _ = _prepare_input(X, engine.name, "fit_dual_engine") + try: + return dict(func(X_prep, y, params)) + except Exception as exc: + _log_dispatch_failure(exc, engine.name.capitalize(), "fit", func) + raise def fit_transform_train_dual_engine( @@ -250,24 +226,43 @@ def fit_transform_train_dual_engine( engine = get_engine(X) func = _resolve_impl(implementations, engine.name, "fit_transform_train") - if engine.name == EngineName.POLARS: - X_prep, was_wrapped = _unwrap_polars_wrapper(X) - try: - artifact, X_out, y_out = func(X_prep, y, params) - except Exception as exc: - _log_dispatch_failure(exc, "Polars", "fit_transform_train", func) - raise - X_out = _rewrap_polars_output(X_out, was_wrapped) - elif engine.name == EngineName.PANDAS: - X_prep = X.to_pandas() if hasattr(X, "to_pandas") else X - try: - artifact, X_out, y_out = func(X_prep, y, params) - except Exception as exc: - _log_dispatch_failure(exc, "Pandas", "fit_transform_train", func) - raise - else: - raise NotImplementedError( - f"No '{engine.name}' input-preparation path in fit_transform_train_dual_engine yet" - ) + X_prep, was_wrapped = _prepare_input(X, engine.name, "fit_transform_train_dual_engine") + try: + artifact, X_out, y_out = func(X_prep, y, params) + except Exception as exc: + _log_dispatch_failure(exc, engine.name.capitalize(), "fit_transform_train", func) + raise + X_out = _restore_output(X_out, was_wrapped, engine.name) return dict(artifact), pack_pipeline_output(X_out, y_out, is_tuple) + + +def _prepare_pandas(X: Any) -> tuple[Any, bool]: + """Preserve the local pandas conversion contract.""" + return (X.to_pandas() if hasattr(X, "to_pandas") else X), False + + +def _prepare_spark(X: Any) -> tuple[Any, bool]: + """Keep Spark input distributed and remember wrapper shape.""" + wrapped = isinstance(X, SkyulfSparkWrapper) + return (X.to_native() if wrapped else X), wrapped + + +def _prepare_input(X: Any, engine: str, caller: str) -> tuple[Any, bool]: + """Resolve input preparation by engine without a conversion fallback.""" + preparations = { + "pandas": _prepare_pandas, + "polars": _unwrap_polars_wrapper, + "spark": _prepare_spark, + } + prepare = preparations.get(engine) + if prepare is None: + raise NotImplementedError(f"No '{engine}' input-preparation path in {caller} yet") + return prepare(X) + + +def _restore_output(X: Any, was_wrapped: bool, engine: str) -> Any: + """Restore only the input wrapper convention, never collecting distributed output.""" + if engine == "spark" and was_wrapped: + return SkyulfSparkWrapper(X) + return _rewrap_polars_output(X, was_wrapped) diff --git a/skyulf-core/skyulf/preprocessing/pipeline.py b/skyulf-core/skyulf/preprocessing/pipeline.py index baec38c14..68cd18912 100644 --- a/skyulf-core/skyulf/preprocessing/pipeline.py +++ b/skyulf-core/skyulf/preprocessing/pipeline.py @@ -9,12 +9,14 @@ import polars as pl from ..config_validation import validate_preprocessing_steps +from ..core.execution import ExecutionOptions, FrameSpec from ..core.validation import prediction_row_count, validate_prediction_rows from ..data.dataset import SplitDataset from ..engines import SkyulfDataFrame from ..registry import NodeRegistry from ..types import PreprocessingStepConfig from ..utils import get_data_stats, pack_pipeline_output, unpack_pipeline_input +from ._spark import fit_spark, transform_spark, use_spark from .base import StatefulTransformer from .dispatcher import _check_xy_engine_parity from .time_series.lag import LagFeaturesApplier @@ -83,6 +85,8 @@ def __init__( steps_config: Sequence[PreprocessingStepConfig | dict[str, Any]], *, _validated: bool = False, + frame_spec: FrameSpec | None = None, + execution_options: ExecutionOptions | None = None, ): """Store the ordered step configuration, validating it unless the caller already did. @@ -92,24 +96,41 @@ def __init__( _validated: Skip ``validate_preprocessing_steps`` when ``True``; set by callers such as ``SkyulfPipeline`` that already validated the same structural rules via ``validate_pipeline_config``. + frame_spec: Explicit keys and optional target for a single Spark frame. + execution_options: Opt-in engine selection; must match the input engine. """ # `Sequence` (covariant) accepts list[dict] or list[PreprocessingStepConfig]. if not _validated: validate_preprocessing_steps(steps_config) self.steps_config = steps_config self.fitted_steps: list[dict[str, Any]] = [] + if frame_spec is not None and not isinstance(frame_spec, FrameSpec): + raise TypeError("frame_spec must be FrameSpec.") + if execution_options is not None and not isinstance(execution_options, ExecutionOptions): + raise TypeError("execution_options must be ExecutionOptions.") + self.frame_spec = frame_spec + self.execution_options = execution_options + self._spark_fitted = False def transform( self, data: pd.DataFrame | SkyulfDataFrame | Any, *, preserve_rows: bool = False ) -> Any: """Apply transformations, optionally rejecting row-count changes and temporal sorting. - Prediction callers set ``preserve_rows=True`` because their responses + Local prediction callers set ``preserve_rows=True`` because their responses have no input-row provenance. Each applied step is checked immediately; a later step cannot conceal filtering, expansion, or a built-in temporal permutation. Ordinary transform and fold scoring retain their configured filtering and sorting behavior. Custom appliers receive count checks only. + Spark execution always preserves key identity and optional target values; + physical row order is not guaranteed. Consumers must align by row keys. """ + spec = getattr(self, "frame_spec", None) + if use_spark(data, getattr(self, "execution_options", None), spec): + if not getattr(self, "_spark_fitted", False): + raise ValueError("Spark FeatureEngineer must be fitted before transform.") + assert spec is not None + return transform_spark(data, self.fitted_steps, spec) current_data = data for step in self.fitted_steps: @@ -159,7 +180,22 @@ def fit_transform( Returns: A pair containing the transformed data and per-step metrics. + + Spark execution validates all capabilities before any data action. Key + uniqueness and per-step identity checks run distributed queries with + bounded results; local row counts and memory metrics remain unknown. """ + spec = getattr(self, "frame_spec", None) + if use_spark(data, getattr(self, "execution_options", None), spec): + assert spec is not None + if target_column is not None and target_column != spec.target: + raise ValueError("target_column conflicts with frame_spec.target.") + if on_split is not None: + raise ValueError("Spark FE uses one frame; on_split is unsupported.") + result, metrics, records = fit_spark(data, self.steps_config, spec) + self.fitted_steps = records + self._spark_fitted = True + return result, metrics self.fitted_steps = [] # Reset fitted steps current_data = data split_captured = False diff --git a/skyulf-core/skyulf/utils.py b/skyulf-core/skyulf/utils.py index 5e4873b6a..fd41ad4a5 100644 --- a/skyulf-core/skyulf/utils.py +++ b/skyulf-core/skyulf/utils.py @@ -18,10 +18,22 @@ from .data.dataset import SplitDataset from .engines import POLARS_NUMERIC_DTYPES, SkyulfDataFrame, SkyulfPolarsWrapper, get_engine +from .engines.spark_engine import is_spark_input logger = logging.getLogger(__name__) +def contains_spark_input(data: Any) -> bool: + """Find distributed inputs even inside unsupported tuples or split containers.""" + if isinstance(data, tuple): + return any(contains_spark_input(value) for value in data) + if isinstance(data, SplitDataset): + return any( + contains_spark_input(value) for value in (data.train, data.test, data.validation) + ) + return is_spark_input(data) + + def _data_stats_from_tuple(data: tuple[Any, Any]) -> tuple[int, set[str]]: """Extract row count and column set from an (X, y) tuple's X element.""" rows = 0 @@ -77,6 +89,8 @@ def get_data_stats( Supports DataFrame, (X, y) tuple, and SplitDataset. """ + if contains_spark_input(data): + raise TypeError("Local data statistics do not support Spark; use distributed FE metrics.") # Check for DataFrame-like object (Pandas, Polars, Wrapper) if hasattr(data, "shape") and hasattr(data, "columns") and not isinstance(data, tuple): payload = cast(Any, data) @@ -102,6 +116,10 @@ def unpack_pipeline_input( `Series[Any] | ...`, poisoning every downstream `with_columns` / `to_pandas` call. The runtime contract is unchanged. """ + if contains_spark_input(data): + if not is_spark_input(data): + raise TypeError("Use a single Spark dataframe containing row keys and target.") + return data, None, False if isinstance(data, (pd.DataFrame, SkyulfDataFrame)): return data, None, False if isinstance(data, tuple): @@ -181,6 +199,10 @@ def pack_pipeline_output( numpy-backed frames interchangeably, and ty can't narrow the exact type through the engine dispatch below. """ + if contains_spark_input(X) or contains_spark_input(y): + if was_tuple or y is not None: + raise TypeError("Use a single Spark dataframe containing row keys and target.") + return X if was_tuple and y is None: # Caller said the input was a tuple but lost y along the way. # Surface this so wiring/upstream bugs don't silently degrade the diff --git a/skyulf-core/tests/spark/test_frame_contract.py b/skyulf-core/tests/spark/test_frame_contract.py new file mode 100644 index 000000000..47e9b19c1 --- /dev/null +++ b/skyulf-core/tests/spark/test_frame_contract.py @@ -0,0 +1,254 @@ +"""Exercise the single-frame, keyed Spark feature-engineering boundary.""" + +import pytest + +from skyulf.core.capabilities import ExecutionCapability, UnsupportedExecutionError +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.core.schema import SkyulfSchema +from skyulf.engines import EngineRegistry +from skyulf.preprocessing.dispatcher import apply_dual_engine, fit_dual_engine +from skyulf.preprocessing.pipeline import FeatureEngineer +from skyulf.registry import NodeRegistry + + +@pytest.fixture +def native_node(monkeypatch): + """A test-only native node proves routing without advertising built-in support.""" + calls = [] + + class Calculator: + """Record selected features without triggering a data action.""" + + def fit(self, frame, config): + """Keep only portable column metadata in fitted state.""" + calls.append(config) + return fit_dual_engine(frame, config, {"spark": lambda X, y, p: dict(p)}) + + class Applier: + """Exercise native expressions on a repartitioned frame.""" + + def apply(self, frame, params): + """Double selected features while retaining keys and labels in place.""" + + def apply_native(X, y, p): + """Use literal quoting to avoid dotted-name path interpretation.""" + for name in p["columns"]: + column = X["`" + name.replace("`", "``") + "`"] + X = X.withColumn(name, column * 2) + return X.repartition(2), None + + return apply_dual_engine(frame, params, {"spark": apply_native}) + + monkeypatch.setattr(NodeRegistry, "_calculators", dict(NodeRegistry._calculators)) + monkeypatch.setattr(NodeRegistry, "_appliers", dict(NodeRegistry._appliers)) + capabilities = tuple( + ExecutionCapability("spark", op, "native", "preserve", "row") for op in ("fit", "apply") + ) + NodeRegistry.register("TestSparkDouble", Applier, execution_capabilities=capabilities)( + Calculator + ) + return calls + + +def engineer(steps=None, target="label"): + """Build the explicitly opted-in Spark entry point used by these contracts.""" + return FeatureEngineer( + steps or [], + frame_spec=FrameSpec(("id",), target), + execution_options=ExecutionOptions("spark"), + ) + + +def test_key_target_alignment_and_unknown_metrics(spark, native_node): + """Repartitioning must not detach labels or introduce keys into the features.""" + frame = spark.createDataFrame([(1, 2.0, 0), (2, 3.0, 1)], ["id", "a.b", "label"]) + pipeline = engineer([{"name": "double", "transformer": "TestSparkDouble"}]) + result, metrics = pipeline.fit_transform(frame.repartition(2)) + assert sorted(tuple(row) for row in result.collect()) == [(1, 4.0, 0), (2, 6.0, 1)] + assert native_node[0]["columns"] == ["a.b"] + assert metrics["summary"]["rows_in"] is None + assert metrics["summary"]["peak_memory_bytes"] is None + assert sorted(tuple(row) for row in pipeline.transform(frame).collect()) == [ + (1, 4.0, 0), + (2, 6.0, 1), + ] + assert pipeline.transform(frame.drop("label")).columns == ["id", "a.b"] + + +@pytest.mark.parametrize("rows", [[(1, 2.0), (1, 3.0)], [(None, 2.0), (2, 3.0)]]) +def test_invalid_keys_rejected(spark, rows): + """Duplicate or null keys cannot identify predictions reliably.""" + frame = spark.createDataFrame(rows, "id long, value double") + with pytest.raises(ValueError, match="row_keys"): + engineer(target=None).fit_transform(frame) + + +@pytest.mark.parametrize("schema", ["id long, value array", "id long, value decimal(10,2)"]) +def test_unsupported_schema_rejected(spark, schema): + """Unsupported dtypes must fail before any native node executes.""" + with pytest.raises(TypeError, match="Unsupported Spark dtype"): + engineer(target=None).fit_transform(spark.createDataFrame([], schema)) + + +def test_missing_and_colliding_columns_rejected(spark): + """Schema ambiguity must not silently change identity or feature selection.""" + with pytest.raises(ValueError, match="Missing"): + engineer().fit_transform(spark.range(2)) + with pytest.raises(ValueError, match="Duplicate"): + engineer(target=None).fit_transform(spark.range(2).selectExpr("id", "id")) + + +def test_full_preflight_before_any_action(spark, native_node, monkeypatch): + """A later unsupported node must block the entire run before key validation or fit.""" + frame = spark.range(2) + + def forbidden(*args, **kwargs): + """Detect early work hidden by a later capability error.""" + pytest.fail("Spark action before preflight") + + for name in ("collect", "count", "toPandas"): + monkeypatch.setattr(type(frame), name, forbidden) + steps = [ + {"name": "first", "transformer": "TestSparkDouble"}, + {"name": "last", "transformer": "SimpleImputer"}, + ] + with pytest.raises(UnsupportedExecutionError, match="SimpleImputer"): + engineer(steps, target=None).fit_transform(frame) + assert native_node == [] + + +def test_spark_requires_opt_in_and_single_frame(spark): + """Separate distributed labels must never be aligned by row position.""" + frame = spark.range(2) + with pytest.raises(ValueError, match="frame_spec.*execution_options"): + FeatureEngineer([]).fit_transform(frame) + with pytest.raises(TypeError, match="single Spark"): + engineer(target=None).fit_transform((frame, frame)) + + +def test_schema_and_dispatcher_keep_native_data(spark): + """Schema extraction and dispatch must preserve Spark types and wrapper shape.""" + frame = spark.range(2) + wrapped = EngineRegistry.wrap(frame) + assert SkyulfSchema.from_dataframe(wrapped).dtypes == {"id": "int64"} + result = apply_dual_engine(wrapped, {}, {"spark": lambda X, y, p: (X, None)}) + assert result.to_native() is frame + with pytest.raises(TypeError, match="single Spark"): + fit_dual_engine((frame, frame), {}, {"spark": lambda X, y, p: {}}) + + +def test_special_key_names_are_literal(spark): + """Internal validation names must not collide with user keys or SQL quoting.""" + frame = spark.createDataFrame([(1, 2, 3.0)], ["a.b", "c`d", "__skyulf_count"]) + pipeline = FeatureEngineer( + [], frame_spec=FrameSpec(("a.b", "c`d")), execution_options=ExecutionOptions("spark") + ) + output, _ = pipeline.fit_transform(frame) + assert tuple(output.first()) == (1, 2, 3.0) + + +@pytest.mark.parametrize("mode", ["drop", "expand", "key", "target"]) +def test_false_preservation_declaration_rejected(spark, native_node, monkeypatch, mode): + """A custom declaration must not silently authorize identity or label corruption.""" + frame = spark.createDataFrame([(1, 2.0, 0), (2, 3.0, 1)], ["id", "value", "label"]) + applier = NodeRegistry.get_applier("TestSparkDouble") + + def corrupt(self, data, params): + """Deliberately violate the declared row-preserving contract.""" + if mode == "drop": + return data.limit(1) + if mode == "expand": + return data.unionByName(data) + name = "id" if mode == "key" else "label" + return data.withColumn(name, data[name] + 1) + + monkeypatch.setattr(applier, "apply", corrupt) + pipeline = engineer([{"name": "bad", "transformer": "TestSparkDouble"}]) + with pytest.raises(ValueError, match="changed row_keys/target"): + pipeline.fit_transform(frame) + assert pipeline.fitted_steps == [] + + +@pytest.mark.parametrize("column", ["id", "label"]) +def test_explicit_protected_features_rejected(spark, native_node, column): + """Explicit feature selection must not bypass key/target exclusion.""" + pipeline = engineer( + [{"name": "bad", "transformer": "TestSparkDouble", "params": {"columns": [column]}}] + ) + with pytest.raises(ValueError, match="cannot include row_keys or target"): + pipeline.fit_transform(spark.range(2)) + assert native_node == [] + + +def test_default_metrics_never_count_or_convert(spark, native_node, monkeypatch): + """Validation actions are explicit; normal profiling must not collect whole frames.""" + frame = spark.createDataFrame([(1, 2.0, 0)], ["id", "value", "label"]) + + def forbidden(*args, **kwargs): + """Catch the local profiler or any eager whole-frame conversion.""" + pytest.fail("Implicit count or local conversion") + + for name in ("count", "toPandas", "toArrow"): + monkeypatch.setattr(type(frame), name, forbidden) + pipeline = engineer([{"name": "double", "transformer": "TestSparkDouble"}]) + output, metrics = pipeline.fit_transform(EngineRegistry.wrap(frame)) + assert output.to_native().columns == frame.columns + assert metrics["rows_out"] is None + + +def test_transform_preflight_and_missing_features(spark, native_node, monkeypatch): + """Apply needs its own permission and all fitted feature columns.""" + frame = spark.createDataFrame([(1, 2.0, 0)], ["id", "value", "label"]) + pipeline = engineer([{"name": "double", "transformer": "TestSparkDouble"}]) + pipeline.fit_transform(frame) + with pytest.raises(ValueError, match="missing or duplicated"): + pipeline.transform(frame.drop("value")) + monkeypatch.setattr( + NodeRegistry.get_calculator("TestSparkDouble"), "__execution_capabilities__", () + ) + with pytest.raises(UnsupportedExecutionError, match="apply"): + pipeline.transform(frame) + + +def test_case_insensitive_collision_rejected(spark): + """Ambiguous SQL identifiers must produce an early schema error.""" + frame = spark.createDataFrame([(1, 2)], ["id", "ID"]) + with pytest.raises(ValueError, match="Duplicate"): + engineer(target=None).fit_transform(frame) + + +def test_internal_aggregate_alias_respects_case_insensitive_keys(spark): + """Validation must not collide with user keys under Spark's SQL resolver.""" + frame = spark.createDataFrame([(1,)], ["__SKYULF_COUNT"]) + pipeline = FeatureEngineer( + [], frame_spec=FrameSpec(("__SKYULF_COUNT",)), execution_options=ExecutionOptions("spark") + ) + output, _ = pipeline.fit_transform(frame) + assert output is frame + + +@pytest.mark.parametrize( + "kind,effect,context", + [ + ("python_batch", "preserve", "row"), + ("native", "filter", "row"), + ("native", "preserve", "window"), + ], +) +def test_only_native_preserving_apply_is_routed( + spark, native_node, monkeypatch, kind, effect, context +): + """Capability metadata for other paths must not activate this native entry point.""" + calculator = NodeRegistry.get_calculator("TestSparkDouble") + monkeypatch.setattr( + calculator, + "__execution_capabilities__", + ( + ExecutionCapability("spark", "fit", "native", "preserve", "global"), + ExecutionCapability("spark", "apply", kind, effect, context), + ), + ) + pipeline = engineer([{"name": "blocked", "transformer": "TestSparkDouble"}], target=None) + with pytest.raises(UnsupportedExecutionError, match="native row-preserving"): + pipeline.fit_transform(spark.range(2)) + assert native_node == [] diff --git a/skyulf-core/tests/unit/test_feature_execution_options.py b/skyulf-core/tests/unit/test_feature_execution_options.py new file mode 100644 index 000000000..72e2b4059 --- /dev/null +++ b/skyulf-core/tests/unit/test_feature_execution_options.py @@ -0,0 +1,38 @@ +"""Keep explicit execution selection compatible with existing local input shapes.""" + +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.data.dataset import SplitDataset +from skyulf.preprocessing.pipeline import FeatureEngineer + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize("shape", ["frame", "tuple", "split"]) +def test_explicit_local_engine_accepts_existing_input_shapes(engine, shape): + """Opting into an engine must preserve valid local frame and split APIs.""" + frame = pd.DataFrame({"x": [1, 2]}) if engine == "pandas" else pl.DataFrame({"x": [1, 2]}) + data = frame + if shape == "tuple": + data = (frame, [0, 1]) + elif shape == "split": + data = SplitDataset(train=frame, test=frame) + engineer = FeatureEngineer([], execution_options=ExecutionOptions(engine)) + output, _ = engineer.fit_transform(data) + assert output is data + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_explicit_engine_checks_each_split(engine): + """A local split must not conceal a frame conflicting with the requested engine.""" + data = SplitDataset(train=pd.DataFrame({"x": [1]}), test=pl.DataFrame({"x": [2]})) + with pytest.raises(ValueError, match="conflicts"): + FeatureEngineer([], execution_options=ExecutionOptions(engine)).fit_transform(data) + + +def test_frame_spec_is_not_silently_ignored_for_local_input(): + """Local row-key protection must not be advertised before its implementation.""" + with pytest.raises(ValueError, match="only for Spark"): + FeatureEngineer([], frame_spec=FrameSpec(("id",))).fit_transform(pd.DataFrame({"id": [1]})) diff --git a/skyulf-core/tests/unit/test_preprocessing_dispatcher.py b/skyulf-core/tests/unit/test_preprocessing_dispatcher.py index c1f0520ec..dba576788 100644 --- a/skyulf-core/tests/unit/test_preprocessing_dispatcher.py +++ b/skyulf-core/tests/unit/test_preprocessing_dispatcher.py @@ -286,8 +286,14 @@ def to_pandas(self): def test_apply_dual_engine_raises_for_engine_without_prep_path(monkeypatch): """A mapped engine with no input-preparation branch must fail loudly too.""" + + class UnsupportedEngine: + """Represent a future engine that has no dataframe preparation contract.""" + + name = "dask" + monkeypatch.setattr( - "skyulf.preprocessing.dispatcher.get_engine", lambda data=None: _StubSparkEngine + "skyulf.preprocessing.dispatcher.get_engine", lambda data=None: UnsupportedEngine ) called = [] @@ -298,7 +304,7 @@ def _spark_apply(X, y, params): df = pd.DataFrame({"a": [1, 2, 3]}) with pytest.raises(NotImplementedError, match="input-preparation path"): - apply_dual_engine(df, {}, {"spark": _spark_apply}) + apply_dual_engine(df, {}, {"dask": _spark_apply}) assert called == [] From 81216e16c582e07cb218a1f9c04b6e3213e5a6e8 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 21:05:45 +0300 Subject: [PATCH 06/85] feat(core): add versioned bounded portable preprocessing state Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 + docs/user_guide/spark.md | 63 +++- .../spark_and_mlflow/01-core-spark-plan.md | 8 +- initiatives/spark_and_mlflow/ARCHITECTURE.md | 16 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 49 ++- initiatives/spark_and_mlflow/README.md | 4 +- skyulf-core/skyulf/core/artifacts.py | 4 +- skyulf-core/skyulf/core/portable_state.py | 301 +++++++++++++++++ skyulf-core/tests/integration/test_scaling.py | 1 + .../tests/spark/test_portable_state.py | 304 ++++++++++++++++++ 10 files changed, 740 insertions(+), 16 deletions(-) create mode 100644 skyulf-core/skyulf/core/portable_state.py create mode 100644 skyulf-core/tests/spark/test_portable_state.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 28564bb6e..d61c7f795 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -37,6 +37,12 @@ execution and MLflow adapters remain under development. remains available. Unknown distributed metrics replace local profiling guesses. Built-in Spark FE nodes remain unsupported pending their native implementations. +- Versioned portable-state codec for StandardScaler and mean/constant + SimpleImputer artifacts. Tagged UTF-8 JSON preserves scalar types, non-finite + values and column order, with explicit byte limits, structural validation and + a semantic checksum. Arbitrary Python objects are rejected; existing pipeline + persistence and fingerprint behavior remain unchanged. + ### Planned scope — not yet available - Native Spark feature engineering with explicit fit/apply capabilities and diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 205021b07..c4d78ff4f 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -210,7 +210,68 @@ The local `get_data_stats` helper rejects Spark input; use the Spark FE metrics. Transform preserves key identity, not physical row order, including when `preserve_rows=True`. Consumers must match outputs by keys. A successful refit replaces fitted steps; a failed refit leaves the last successful fitted steps -available. Saving portable learned state follows in SM-04. +available. The portable learned-state codec is described below. + +## Portable learned state + +The development codec transports a small learned-parameter dictionary as +versioned UTF-8 JSON bytes. It currently supports `StandardScaler` and +`SimpleImputer` with `mean` or `constant` strategies, including empty no-op +artifacts. This example works in the base environment without Spark: + +```python +import pandas as pd + +from skyulf.core.execution import ExecutionOptions +from skyulf.core.portable_state import decode_state, encode_state +from skyulf.preprocessing.imputation.simple import ( + SimpleImputerApplier, + SimpleImputerCalculator, +) + +training = pd.DataFrame({"amount": [1.0, None, 5.0]}) +params = SimpleImputerCalculator().fit( + training, {"columns": ["amount"], "strategy": "mean"}, +) +budget = ExecutionOptions(engine="spark").state_max_bytes +payload = encode_state("SimpleImputer", params, max_bytes=budget) +node_type, restored = decode_state(payload, max_bytes=budget) +assert node_type == "SimpleImputer" +result = SimpleImputerApplier().apply(pd.DataFrame({"amount": [None]}), restored) +assert result["amount"].tolist() == [3.0] +``` + +The v1 envelope contains `format_version`, `codec_version`, `node_type`, +`ordered_columns`, `learned_parameters` and `semantic_digest`. The original +artifact retains its options, such as scaler centering/scaling flags. Unknown +versions, nodes, fields, malformed tags, duplicate columns and inconsistent +array lengths/counts are rejected. Actual input/output schemas and producer +metadata are not inferred from statistics; they belong to later bundle metadata. + +Scalar tags distinguish integers, floats, strings, booleans and nulls. Integer +tags use decimal strings to preserve large category values. Float tags preserve +finite values and negative zero with hexadecimal notation, and represent NaN +and positive/negative infinity explicitly. NumPy scalar equivalents normalize +to Python scalars; arrays, estimators, sessions and arbitrary objects are rejected. +NaN bit patterns are not separate learned semantics. Column/list order is +preserved; dictionary insertion order and JSON whitespace are not significant. + +The semantic SHA-256 checksum detects changed content; it is not a signature +or proof of a trusted producer. It uses canonical tagged values, with no +arbitrary-object `repr` or pickle fallback. Existing pipeline pickle save/load +and fingerprint algorithms remain unchanged. + +`encode_state` requires an explicit positive `max_bytes` budget. +`decode_state` defaults to 8 MiB and checks received byte length before parsing. +Pass the same custom budget at both ends when changing it. The limit applies to +wire bytes; it is not a bound on total Python process memory. The codec performs +no filesystem or network I/O. Callers own storage and transport of these bytes. + +This API does not enable Spark node execution or automatically package a +FeatureEngineer pipeline. Connecting these artifacts to native Spark imputer +and scaler implementations follows in SM-05/SM-06; worker model loading comes +later. Codec tests run in both base and Spark development environments without +starting a JVM. ### Inspecting declared support diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index e75f4f04f..79cb21a12 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -162,13 +162,13 @@ local FeatureEngineer regression testleri geçer. **Üretir:** `encode_state(node_type, params, *, max_bytes) -> bytes` ve `decode_state(payload: bytes) -> tuple[str, dict]`; envelope v1. -- [ ] StandardScaler ve SimpleImputer mevcut artifact dict fixture'larını +- [x] StandardScaler ve SimpleImputer mevcut artifact dict fixture'larını lossless round-trip test et; boş state/no-op davranışını ayrı kapsa. -- [ ] NaN/Infinity, integer/string kategori değerleri ve ordered_columns için +- [x] NaN/Infinity, integer/string kategori değerleri ve ordered_columns için tagged representation; semantic hash'te repr/pickle fallback olmaması testi yaz. -- [ ] Bozuk payload, bilinmeyen version/node, duplicate columns ve aşırı büyük +- [x] Bozuk payload, bilinmeyen version/node, duplicate columns ve aşırı büyük payload'ı decode/worker yüklemesinden önce reddet. -- [ ] Eski pipeline pickle save/load testlerini değiştirmeden geçir. Bu codec +- [x] Eski pipeline pickle save/load testlerini değiştirmeden geçir. Bu codec generic Python object serializer değildir; estimator nesnesi kabul etmez. ```python diff --git a/initiatives/spark_and_mlflow/ARCHITECTURE.md b/initiatives/spark_and_mlflow/ARCHITECTURE.md index 493979e2b..2ef391994 100644 --- a/initiatives/spark_and_mlflow/ARCHITECTURE.md +++ b/initiatives/spark_and_mlflow/ARCHITECTURE.md @@ -104,12 +104,11 @@ Yeni `NodeRegistry` kopyası oluşturulmaz; mevcut kayıt anahtarlarıyla ilişk Spark desteği ilan edilmemiş bütün kayıtlar açıkça unsupported sayılır. Operation-level öğrenme ve leakage metadata'sı mevcut mekanizma ile uyumlu kalır. -`skyulf/core/portable_state.py` planlanan envelope alanları: +`skyulf/core/portable_state.py` SM-04 v1 envelope alanları: ```text -format_version=1, node_type, codec_version, ordered_columns, -input_schema, output_schema, learned_parameters, semantic_options, -producer_engine, producer_version, compatibility, semantic_digest +format_version=1, node_type, codec_version=1, ordered_columns, +learned_parameters, semantic_digest ``` Envelope mevcut artifact dict'lerini codec üzerinden taşır; Calculator'ın tüm @@ -118,6 +117,15 @@ ve StandardScaler. JSON NaN/Infinity ve dtype değerleri için açık tagged enc kullanılır; `repr` veya pickle bytes üzerinden semantic digest üretilmez. Enum/version bilinmiyorsa deserialize etmeden hata verilir. +V1 API yalnız node_type ve mevcut params alır; gerçek input/output schema veya +producer bilgisi bu girdiden çıkarılamaz. Bu alanlar uydurulmaz. Semantic options +mevcut artifact içindeki with_mean/with_std/strategy gibi alanlarda korunur. +Schema, producer ve compatibility metadata daha sonraki bundle aşamasına aittir. +Mevcut pipeline seal formatı değiştirilmez; portable checksum ayrı versioned +tagged JSON üzerinden hesaplanır. Checksum imza/authenticity garantisi değildir. +Decode byte limiti parse öncesi gelen payload'a uygulanır; wire byte bütçesi +process memory bütçesi değildir. Codec herhangi bir Spark action veya I/O yapmaz. + Küçük state inline taşınabilir. Büyük kategori/group state için immutable tablo referansı, schema ve içerik kimliği gerekir; bu SM-17 kapsamıdır. Küçük state codec'i büyük tabloları driver'a indirmez. Python estimator nesneleri portable diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 06e3ad5c9..9380e3449 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-03 tamamlandı. Sonraki görev: SM-04. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-04 tamamlandı. Sonraki görev: SM-05. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -13,8 +13,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-01 | Execution/capability kuralları | SM-00 | DONE | Immutable config; registry operation desteği; aşağıda kanıt | | SM-02 | Spark engine ve conversion sınırı | SM-01 | DONE | Gerçek Spark adapter; conversion korumaları; aşağıda kanıt | | SM-03 | Dispatcher, schema, row keys | SM-02 | DONE | Keyed Spark FE giriş/preflight; aşağıda kanıt | -| SM-04 | Versioned portable state | SM-03 | READY | Limit/version kontrolü; state round-trip | -| SM-05 | Native SimpleImputer | SM-04 | WAIT | Mean/constant train-only fit, Spark apply | +| SM-04 | Versioned portable state | SM-03 | DONE | Tagged state, limit/version/schema kontrolü; aşağıda kanıt | +| SM-05 | Native SimpleImputer | SM-04 | READY | Mean/constant train-only fit, Spark apply | | SM-06 | Native StandardScaler | SM-05 | WAIT | Population variance ve flag parity | | SM-07 | Uçtan uca FE kapısı | SM-06 | WAIT | Üç engine çapraz fit/apply; kayıt/yükleme | | SM-08 | Ortak inference bundle | SM-07 | WAIT | Raw/features ayrımı; model metadata round-trip | @@ -181,3 +181,46 @@ ve MLflow entegrasyonu henüz yok. capability örneği de doğrulandı. Changelog/rehber birlikte güncellendi. - Sınır: built-in native node, portable state codec, distributed model inference, explicit aggregate metrics ve Databricks/Connect testi henüz yok. SM-04 sırada. + +## SM-04 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `44b5241e`; bu kayıt SM-04 çalışma ağacına aittir. +- `core/portable_state.py`: UTF-8 tagged JSON v1 encode/decode; explicit encode + byte bütçesi ve parse öncesi decode limiti (varsayılan 8 MiB). StandardScaler ve + mean/constant SimpleImputer gerçek artifact sözlükleri, boş no-op state dahil. +- Integer/string/bool/null ayrımı, non-finite float ve signed zero, kolon sırası + korunur. Unknown version/node/fields/tags, duplicate JSON/map keys/columns, + inconsistent state, unsupported Python objects ve aşırı nesting reddedilir. + Checksum canonical semantic content üzerinden SHA-256; imza değildir. +- `core/artifacts.py` StandardScaler mean/var alanları mevcut disabled-flag + davranışına uygun `None` kabul edecek şekilde düzeltildi. İlgili scaling testi + mean-enabled koşulda non-null assertion ile gerçek beklentiyi açıkça doğrular. +- `pipeline/seal.py` değişmedi: eski fingerprint ve pickle formatını değiştirmek + gerekmedi. Portable checksum kendi versioned vocabulary'sine sahiptir. + API'de bulunmayan producer/schema bilgisi uydurulmadı; mimari metadata sınırı + güncellendi. Future bundle bu bilgiyi gerçek input/execution bağlamından alacak. +- TDD ilk koşu eksik modül nedeniyle fail; ilk uygulama **44 passed**. UTF-16 + kabulü ve review'un compact Unicode byte-limit bulgusu ayrı red/green testlerle + düzeltildi. Review son recheck'te limit sınırlarını bağımsız doğruladı. +- Odaklı komut: `.venv/Scripts/python.exe -m pytest + skyulf-core/tests/spark/test_portable_state.py + skyulf-core/tests/unit/test_pipeline_seal.py skyulf-core/tests/unit/test_pipeline.py + skyulf-core/tests/unit/test_pipeline_threshold_fingerprint.py + skyulf-core/tests/integration/test_scaling.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm04-reviewed` + → **188 passed**, 5 mevcut numeric warning, 4.69 saniye. Eski save/load testleri + ve fingerprint golden testleri değişmeden geçti. İlk odaklı koşunun Windows + default temp erişim hatası workspace içindeki basetemp ile giderildi. +- Spark profile: `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark/test_portable_state.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm04-spark-codec` + → **61 passed**, 1.22 saniye. Codec JVM kullanmaz; bu sonuç Spark FE kanıtı değildir. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm04-core` + → **9945 passed, 107 skipped, 1077 warnings**, 168.18 saniye. + Ruff/format, tam repo ty ve + `mkdocs build --strict` geçti. Rehberdeki yeni codec örneği base ortamda çalıştı. +- Sınır: ayrı codec API'sidir; FeatureEngineer/model worker için otomatik paketleme + yok. Byte limiti toplam process memory limiti değildir. Native SimpleImputer + SM-05, StandardScaler SM-06; Spark runtime/Databricks bu görevde çalıştırılmadı. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index 4549531b2..d85d6b3f3 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-03 tamamlandı; sıradaki görev SM-04.** +Tarih: 2026-09-21. Durum: **SM-00–SM-04 tamamlandı; sıradaki görev SM-05.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-04**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-05**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/core/artifacts.py b/skyulf-core/skyulf/core/artifacts.py index aee501e0c..601e0b4f2 100644 --- a/skyulf-core/skyulf/core/artifacts.py +++ b/skyulf-core/skyulf/core/artifacts.py @@ -19,9 +19,9 @@ class StandardScalerArtifact(TypedDict, total=False): """Standard-scaling parameters (per-column mean, scale and variance).""" type: str - mean: list[float] + mean: list[float] | None scale: list[float] | None - var: list[float] + var: list[float] | None with_mean: bool with_std: bool columns: list[str] diff --git a/skyulf-core/skyulf/core/portable_state.py b/skyulf-core/skyulf/core/portable_state.py new file mode 100644 index 000000000..6a4193104 --- /dev/null +++ b/skyulf-core/skyulf/core/portable_state.py @@ -0,0 +1,301 @@ +"""Versioned, bounded JSON state for the initial portable preprocessing nodes. + +This codec accepts learned scalar state, never estimators, sessions or arbitrary +Python objects. It performs no filesystem access and imports no optional engine. +""" + +import hashlib +import json +import math +from collections.abc import Iterator +from typing import Any + +import numpy as np + +DEFAULT_MAX_STATE_BYTES = 8 * 1024 * 1024 +_NODE_TYPES = {"StandardScaler": "standard_scaler", "SimpleImputer": "simple_imputer"} +_ENVELOPE_FIELDS = { + "format_version", + "codec_version", + "node_type", + "ordered_columns", + "learned_parameters", + "semantic_digest", +} +_SCALER_FIELDS = {"type", "columns", "mean", "var", "scale", "with_mean", "with_std"} +_IMPUTER_FIELDS = {"type", "columns", "strategy", "fill_values", "missing_counts", "total_missing"} + + +def encode_state(node_type: str, params: Any, *, max_bytes: int) -> bytes: + """Encode supported fitted parameters with an exact UTF-8 envelope byte limit. + + NumPy scalar values normalize to their lossless Python equivalents. Dict + insertion order is immaterial; column/list order and scalar types matter. + Empty dictionaries remain no-op artifacts. Other objects are rejected. + """ + _validate_limit(max_bytes) + _validate_node(node_type) + normalized = _normalize(params) + _validate_state(node_type, normalized) + document = _envelope(node_type, normalized) + return _json_bytes(document, max_bytes) + + +def decode_state( + payload: bytes, *, max_bytes: int = DEFAULT_MAX_STATE_BYTES +) -> tuple[str, dict[str, Any]]: + """Reject oversized, unknown or corrupt state before returning parameters. + + Limits are checked before JSON parsing. The semantic checksum detects + corruption; it is not a signature or proof of a trusted producer. + """ + _validate_limit(max_bytes) + if type(payload) is not bytes: + raise TypeError("Portable state payload must be bytes.") + if len(payload) > max_bytes: + raise ValueError("Portable state exceeds max_bytes.") + try: + document = json.loads( + payload.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_bad_constant + ) + _validate_envelope(document) + node_type = document["node_type"] + params = _unpack(document["learned_parameters"]) + _validate_state(node_type, params) + if document["ordered_columns"] != params.get("columns", []): + raise ValueError("ordered_columns must match the learned columns in order.") + expected = _envelope(node_type, params)["semantic_digest"] + if document["semantic_digest"] != expected: + raise ValueError("Portable state semantic_digest mismatch.") + return node_type, params + except (RecursionError, UnicodeError, OverflowError) as exc: + raise ValueError("Invalid portable state encoding or nesting depth.") from exc + + +def _validate_limit(value: int) -> None: + """Require a positive byte budget without treating booleans as integers.""" + if type(value) is not int or value <= 0: + raise ValueError("max_bytes must be a positive integer.") + + +def _validate_node(node_type: str) -> None: + """Keep the format restricted to explicitly implemented node codecs.""" + if type(node_type) is not str or node_type not in _NODE_TYPES: + raise ValueError("Unsupported portable state node_type.") + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + """Reject duplicate JSON fields rather than choosing the last interpretation.""" + result = {} + for name, value in pairs: + if name in result: + raise ValueError("Duplicate JSON field in portable state.") + result[name] = value + return result + + +def _bad_constant(value: str) -> Any: + """Require explicit tags for non-finite floats instead of JSON extensions.""" + raise ValueError("Non-finite values require portable float tags.") + + +def _normalize(value: Any, depth: int = 0) -> Any: + """Copy the small scalar/container vocabulary, rejecting cycles and deep nesting.""" + if depth > 8: + raise ValueError("Portable state exceeds supported nesting depth.") + if isinstance(value, np.generic): + value = value.item() + if type(value) in (str, int, float, bool, type(None)): + return value + if type(value) is list: + return [_normalize(item, depth + 1) for item in value] + if type(value) is dict: + if any(type(key) is not str for key in value): + raise TypeError("Portable state dictionary keys must be strings.") + return {key: _normalize(item, depth + 1) for key, item in value.items()} + raise TypeError( + "Unsupported portable state value; only scalars, lists and dictionaries are allowed." + ) + + +def _validate_state(node_type: str, params: Any) -> None: + """Validate the exact node artifact schema without inferring missing semantics.""" + if type(params) is not dict: + raise ValueError("Learned parameters must be a dictionary.") + if not params: + return + fields = _SCALER_FIELDS if node_type == "StandardScaler" else _IMPUTER_FIELDS + if set(params) != fields or params.get("type") != _NODE_TYPES[node_type]: + raise ValueError("Portable state fields/type do not match the node codec.") + _validate_columns(params["columns"]) + if node_type == "StandardScaler": + _validate_scaler(params) + else: + _validate_imputer(params) + + +def _validate_columns(columns: Any) -> None: + """Retain ordered exact string names while rejecting ambiguous duplicates.""" + if type(columns) is not list or any(type(name) is not str for name in columns): + raise ValueError("columns must be a list of strings.") + if len(set(columns)) != len(columns): + raise ValueError("Duplicate columns in portable state.") + + +def _validate_scaler(params: dict[str, Any]) -> None: + """Pin scaler flags and aligned per-column numeric arrays, including disabled stats.""" + for name in ("with_mean", "with_std"): + if type(params[name]) is not bool: + raise ValueError("Scaler flags must be booleans.") + for name in ("mean", "var", "scale"): + values = params[name] + if values is not None: + _validate_statistics(values, len(params["columns"])) + if params["with_mean"] and params["mean"] is None: + raise ValueError("with_mean requires mean state.") + if params["with_std"] and (params["scale"] is None or params["var"] is None): + raise ValueError("with_std requires scale and var state.") + + +def _validate_statistics(values: Any, size: int) -> None: + """Reject shortened arrays and scalar types that would alter numeric semantics.""" + if type(values) is not list or len(values) != size: + raise ValueError("Statistic arrays must align with ordered columns.") + if any(type(value) not in (int, float) for value in values): + raise ValueError("Scaler statistics must contain numeric scalars.") + + +def _validate_imputer(params: dict[str, Any]) -> None: + """Validate supported strategies, scalar replacements and consistent missing counts.""" + if params["strategy"] not in ("mean", "constant"): + raise ValueError("Portable SimpleImputer currently supports mean and constant only.") + columns = set(params["columns"]) + for field in ("fill_values", "missing_counts"): + if type(params[field]) is not dict or set(params[field]) != columns: + raise ValueError(f"{field} must match the learned columns.") + if any( + type(value) not in (int, float, str, bool, type(None)) + for value in params["fill_values"].values() + ): + raise ValueError("Imputer fill values must be scalars.") + counts = [*params["missing_counts"].values(), params["total_missing"]] + if any(type(value) is not int or value < 0 for value in counts): + raise ValueError("Missing counts must be nonnegative integers.") + if sum(params["missing_counts"].values()) != params["total_missing"]: + raise ValueError("total_missing must equal the per-column missing counts.") + + +def _pack(value: Any) -> dict[str, Any]: + """Represent each scalar type explicitly and sort unordered dictionary entries.""" + if value is None: + return {"kind": "null"} + if type(value) is dict: + return {"kind": "dict", "items": [[key, _pack(value[key])] for key in sorted(value)]} + if type(value) is list: + return {"kind": "list", "items": [_pack(item) for item in value]} + if type(value) is float: + return {"kind": "float", "value": _float_token(value)} + tags = {str: "string", int: "int", bool: "bool"} + return {"kind": tags[type(value)], "value": str(value) if type(value) is int else value} + + +def _float_token(value: float) -> str: + """Preserve finite IEEE values and signed zero; canonicalize non-finite semantics.""" + if math.isnan(value): + return "nan" + if math.isinf(value): + return "+inf" if value > 0 else "-inf" + return float(value).hex() + + +def _unpack(value: Any, depth: int = 0) -> Any: + """Decode a closed tagged vocabulary without executing or importing user objects.""" + if depth > 8 or type(value) is not dict: + raise ValueError("Invalid tagged state or excessive nesting.") + kind = value.get("kind") + if kind == "null" and set(value) == {"kind"}: + return None + if kind in ("dict", "list") and set(value) == {"kind", "items"}: + return _unpack_container(kind, value["items"], depth) + if set(value) != {"kind", "value"}: + raise ValueError("Invalid tagged scalar fields.") + return _unpack_scalar(kind, value["value"]) + + +def _unpack_container(kind: str, items: Any, depth: int) -> Any: + """Validate list/map shape and reject duplicate learned-state dictionary keys.""" + if type(items) is not list: + raise ValueError("Tagged items must be a list.") + if kind == "list": + return [_unpack(item, depth + 1) for item in items] + pairs = [] + for pair in items: + if type(pair) is not list or len(pair) != 2 or type(pair[0]) is not str: + raise ValueError("Invalid tagged dictionary entry.") + pairs.append((pair[0], _unpack(pair[1], depth + 1))) + return _unique_object(pairs) + + +def _unpack_scalar(kind: Any, value: Any) -> Any: + """Require canonical scalar encodings, keeping integers separate from strings/bools.""" + if (kind == "string" and type(value) is str) or (kind == "bool" and type(value) is bool): + return value + if kind == "int" and type(value) is str: + result = int(value) + if str(result) == value: + return result + if kind == "float" and type(value) is str: + result = {"nan": math.nan, "+inf": math.inf, "-inf": -math.inf}.get(value) + if result is None: + result = float.fromhex(value) + if _float_token(result) == value: + return result + raise ValueError("Unknown or malformed portable scalar tag.") + + +def _validate_envelope(document: Any) -> None: + """Reject unknown versions/nodes before interpreting tagged learned parameters.""" + if type(document) is not dict: + raise ValueError("Portable state envelope must be a JSON object.") + for name in ("format_version", "codec_version"): + if type(document.get(name)) is not int or document[name] != 1: + raise ValueError(f"Unsupported {name} in portable state.") + if set(document) != _ENVELOPE_FIELDS: + raise ValueError("Invalid portable state envelope fields.") + _validate_node(document["node_type"]) + _validate_columns(document["ordered_columns"]) + if type(document["semantic_digest"]) is not str: + raise ValueError("semantic_digest must be a string.") + + +def _envelope(node_type: str, params: dict[str, Any]) -> dict[str, Any]: + """Hash only canonical versioned semantics, independently of Python object identity.""" + document = { + "format_version": 1, + "codec_version": 1, + "node_type": node_type, + "ordered_columns": params.get("columns", []), + "learned_parameters": _pack(params), + } + digest = hashlib.sha256() + for chunk in _json_chunks(document): + digest.update(chunk) + document["semantic_digest"] = digest.hexdigest() + return document + + +def _json_bytes(document: dict, max_bytes: int) -> bytes: + """Stop JSON output as soon as the complete wire representation exceeds its budget.""" + output = bytearray() + for encoded in _json_chunks(document): + if len(output) + len(encoded) > max_bytes: + raise ValueError("Portable state exceeds max_bytes.") + output.extend(encoded) + return bytes(output) + + +def _json_chunks(document: dict) -> Iterator[bytes]: + """Stream canonical UTF-8 chunks for serialization and semantic hashing.""" + encoder = json.JSONEncoder(sort_keys=True, separators=(",", ":"), allow_nan=False) + for chunk in encoder.iterencode(document): + yield chunk.encode("utf-8") diff --git a/skyulf-core/tests/integration/test_scaling.py b/skyulf-core/tests/integration/test_scaling.py index c5630a859..ec8da2953 100644 --- a/skyulf-core/tests/integration/test_scaling.py +++ b/skyulf-core/tests/integration/test_scaling.py @@ -212,6 +212,7 @@ def test_standard_scaler_nullable_numeric_round_trip( out = out.to_pandas() assert params["columns"] == columns + assert params["mean"] is not None np.testing.assert_allclose(params["mean"], reference.mean_) np.testing.assert_allclose(out[columns].to_numpy(), reference.transform(frame[columns])) assert all(pd.api.types.is_float_dtype(out[col]) for col in columns) diff --git a/skyulf-core/tests/spark/test_portable_state.py b/skyulf-core/tests/spark/test_portable_state.py new file mode 100644 index 000000000..16619d195 --- /dev/null +++ b/skyulf-core/tests/spark/test_portable_state.py @@ -0,0 +1,304 @@ +"""Portable learned-state contracts run without a Spark runtime.""" + +import hashlib +import json +import math + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.portable_state import decode_state, encode_state +from skyulf.pipeline.seal import artifact_digest +from skyulf.preprocessing.imputation.simple import SimpleImputerApplier, SimpleImputerCalculator +from skyulf.preprocessing.scaling.standard import StandardScalerApplier, StandardScalerCalculator + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize( + "with_mean,with_std", [(True, True), (True, False), (False, True), (False, False)] +) +def test_scaler_fitted_state_preserves_apply(engine, with_mean, with_std): + """The decoded artifact must produce exactly the same local transformation.""" + data = pd.DataFrame({"z": [1.0, 3.0, 5.0], "a": [4.0, 4.0, 4.0]}) + data = pl.from_pandas(data) if engine == "polars" else data + params = StandardScalerCalculator().fit( + data, + { + "columns": ["z", "a"], + "with_mean": with_mean, + "with_std": with_std, + }, + ) + node, restored = decode_state(encode_state("StandardScaler", params, max_bytes=8192)) + assert node == "StandardScaler" + assert artifact_digest(restored) == artifact_digest(params) + original = StandardScalerApplier().apply(data, params) + decoded = StandardScalerApplier().apply(data, restored) + np.testing.assert_equal(original.to_numpy(), decoded.to_numpy()) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize("strategy", ["mean", "constant"]) +def test_imputer_fitted_state_preserves_apply(engine, strategy): + """Encoding must retain fill values, counts and all-null column semantics.""" + data = pd.DataFrame({"x": [1.0, np.nan, 5.0], "empty": [np.nan] * 3}) + data = pl.from_pandas(data) if engine == "polars" else data + params = SimpleImputerCalculator().fit(data, {"columns": ["x", "empty"], "strategy": strategy}) + node, restored = decode_state(encode_state("SimpleImputer", params, max_bytes=8192)) + assert node == "SimpleImputer" + assert artifact_digest(restored) == artifact_digest(params) + np.testing.assert_equal( + SimpleImputerApplier().apply(data, params).to_numpy(), + SimpleImputerApplier().apply(data, restored).to_numpy(), + ) + + +def imputer_state(value): + """Create a valid one-column constant state without fitting an estimator.""" + return { + "type": "simple_imputer", + "columns": ["x"], + "strategy": "constant", + "fill_values": {"x": value}, + "missing_counts": {"x": 0}, + "total_missing": 0, + } + + +@pytest.mark.parametrize( + "value", + [ + None, + True, + 2**63 + 1, + "9007199254740993", + "λ", + -0.0, + float("nan"), + float("inf"), + -float("inf"), + ], +) +def test_scalar_types_and_nonfinite_values(value): + """Numbers and category text must stay distinct without nonstandard JSON floats.""" + payload = encode_state("SimpleImputer", imputer_state(value), max_bytes=8192) + document = json.loads(payload) + assert document["ordered_columns"] == ["x"] + assert b"NaN" not in payload and b"Infinity" not in payload + _, restored = decode_state(payload) + result = restored["fill_values"]["x"] + assert type(result) is type(value) + if isinstance(value, float) and math.isnan(value): + assert math.isnan(result) + elif isinstance(value, float): + assert result.hex() == value.hex() + else: + assert result == value + + +@pytest.mark.parametrize("node", ["SimpleImputer", "StandardScaler"]) +def test_empty_artifact_round_trip(node): + """No-op artifacts must not acquire learned statistics during decoding.""" + assert decode_state(encode_state(node, {}, max_bytes=8192)) == (node, {}) + + +def test_digest_is_order_independent_but_type_sensitive(): + """A semantic digest must reflect value types rather than dict insertion order.""" + state = imputer_state(np.int64(7)) + first = encode_state("SimpleImputer", state, max_bytes=8192) + assert first == encode_state( + "SimpleImputer", dict(reversed(list(state.items()))), max_bytes=8192 + ) + numeric = json.loads(first)["semantic_digest"] + textual = json.loads(encode_state("SimpleImputer", imputer_state("7"), max_bytes=8192))[ + "semantic_digest" + ] + assert numeric != textual + + +@pytest.mark.parametrize("limit", [0, -1, True, 1.5]) +def test_invalid_byte_limits_rejected(limit): + """Invalid resource limits must not silently disable state-size enforcement.""" + with pytest.raises(ValueError, match="max_bytes"): + encode_state("SimpleImputer", {}, max_bytes=limit) + with pytest.raises(ValueError, match="max_bytes"): + decode_state(b"{}", max_bytes=limit) + + +def test_payload_limit_is_enforced_in_both_directions(): + """Worker-side loading must reject oversized bytes before attempting JSON parsing.""" + state = imputer_state("λ" * 20) + payload = encode_state("SimpleImputer", state, max_bytes=8192) + assert encode_state("SimpleImputer", state, max_bytes=len(payload)) == payload + with pytest.raises(ValueError, match="max_bytes"): + encode_state("SimpleImputer", state, max_bytes=len(payload) - 1) + with pytest.raises(ValueError, match="max_bytes"): + decode_state(b"invalid-json" * 100, max_bytes=10) + + +@pytest.mark.parametrize( + "payload", + [ + b'{"format_version":999}', + b'{"format_version":true}', + b"garbage", + b"[]", + b"{}", + b"\xff", + b'{"format_version":1,"format_version":1}', + ], +) +def test_malformed_envelopes_rejected(payload): + """Unrecognized or ambiguous wire data must fail instead of guessing semantics.""" + with pytest.raises(ValueError): + decode_state(payload) + + +@pytest.mark.parametrize( + "field,value", + [ + ("codec_version", 999), + ("node_type", "Unknown"), + ("ordered_columns", ["x", "x"]), + ("semantic_digest", "0" * 64), + ], +) +def test_altered_envelope_rejected(field, value): + """A corrupt envelope must not reach an applier as apparently valid learned state.""" + document = json.loads(encode_state("SimpleImputer", imputer_state(3), max_bytes=8192)) + document[field] = value + with pytest.raises(ValueError): + decode_state(json.dumps(document).encode()) + + +@pytest.mark.parametrize("value", [object(), np.array([1]), {"nested": 2}]) +def test_non_scalar_fill_state_rejected(value): + """The codec must never serialize arbitrary Python objects or nested category state.""" + with pytest.raises((TypeError, ValueError)): + encode_state("SimpleImputer", imputer_state(value), max_bytes=8192) + + +def test_unknown_node_duplicate_columns_and_incomplete_state_rejected(): + """Only explicitly versioned, structurally valid node artifacts are portable.""" + with pytest.raises(ValueError, match="node"): + encode_state("KNNImputer", {}, max_bytes=8192) + state = imputer_state(3) + state["columns"] = ["x", "x"] + with pytest.raises(ValueError, match="columns"): + encode_state("SimpleImputer", state, max_bytes=8192) + with pytest.raises(ValueError): + encode_state("StandardScaler", {"columns": ["x"]}, max_bytes=8192) + + +def test_column_order_changes_digest_and_is_retained(): + """Column ordering must remain meaningful even when dictionary order is not.""" + frame = pd.DataFrame({"z": [1.0, 2.0], "a": [3.0, 4.0]}) + digests = [] + for columns in (["z", "a"], ["a", "z"]): + state = StandardScalerCalculator().fit(frame, {"columns": columns}) + payload = encode_state("StandardScaler", state, max_bytes=8192) + assert decode_state(payload)[1]["columns"] == columns + digests.append(json.loads(payload)["semantic_digest"]) + assert digests[0] != digests[1] + + +def resigned(document): + """Recompute the public checksum so malformed-state tests exercise schema validation.""" + document.pop("semantic_digest", None) + canonical = json.dumps(document, sort_keys=True, separators=(",", ":"), allow_nan=False) + document["semantic_digest"] = hashlib.sha256(canonical.encode()).hexdigest() + return json.dumps(document).encode() + + +@pytest.mark.parametrize( + "tag", + [ + {"kind": "object", "value": "module.Class"}, + {"kind": "int", "value": True}, + {"kind": "float", "value": "Infinity"}, + {"kind": "null", "value": None}, + {"kind": "dict", "items": [["x", {"kind": "null"}], ["x", {"kind": "null"}]]}, + ], +) +def test_malformed_tags_rejected_even_with_recomputed_checksum(tag): + """A checksum is not authorization to bypass the closed tagged vocabulary.""" + document = json.loads(encode_state("SimpleImputer", imputer_state(1), max_bytes=8192)) + document["learned_parameters"] = tag + with pytest.raises(ValueError): + decode_state(resigned(document)) + + +@pytest.mark.parametrize( + "changes", + [ + {"total_missing": -1}, + {"total_missing": 5}, + {"missing_counts": {"other": 0}}, + {"strategy": "median"}, + {"extra": "unknown"}, + ], +) +def test_invalid_node_fields_rejected(changes): + """Node validation must reject inconsistent counts and unsupported semantics.""" + state = imputer_state(1) | changes + with pytest.raises(ValueError): + encode_state("SimpleImputer", state, max_bytes=8192) + + +def test_no_arbitrary_repr_or_pickle_fallback(): + """Unsupported objects must fail without invoking their serialization hooks.""" + + class DangerousObject: + """Expose hooks that a generic serializer might accidentally invoke.""" + + def __repr__(self): + """Make implicit text serialization observable.""" + pytest.fail("repr fallback") + + def __reduce__(self): + """Make implicit pickle serialization observable.""" + pytest.fail("pickle fallback") + + with pytest.raises(TypeError, match="Unsupported portable"): + encode_state("SimpleImputer", imputer_state(DangerousObject()), max_bytes=8192) + + +def test_cycles_and_deeply_nested_payload_rejected(): + """Malformed nesting must fail within the bounded codec contract.""" + cycle = {} + cycle["cycle"] = cycle + with pytest.raises(ValueError, match="depth"): + encode_state("SimpleImputer", cycle, max_bytes=8192) + with pytest.raises(ValueError): + decode_state(b"[" * 2000 + b"0" + b"]" * 2000) + + +def test_plain_json_nan_rejected(): + """Nonstandard JSON constants must not bypass float tagging.""" + with pytest.raises(ValueError, match="float tags"): + decode_state(b'{"learned_parameters":NaN}') + + +def test_wire_encoding_requires_utf8(): + """Workers must interpret a single documented byte encoding across runtimes.""" + payload = encode_state("SimpleImputer", {}, max_bytes=8192) + with pytest.raises(ValueError): + decode_state(payload.decode("utf-8").encode("utf-16")) + + +def test_json_layout_does_not_change_semantic_checksum(): + """Whitespace and object member ordering must not become learned semantics.""" + original = encode_state("SimpleImputer", imputer_state(9), max_bytes=8192) + document = json.loads(original) + reformatted = json.dumps(dict(reversed(list(document.items()))), indent=2).encode() + assert decode_state(reformatted) == decode_state(original) + + +def test_decode_limit_measures_received_unicode_bytes(): + """Canonical checksum escaping must not reject a received envelope within budget.""" + payload = encode_state("SimpleImputer", imputer_state("λ" * 100), max_bytes=8192) + compact = json.dumps(json.loads(payload), ensure_ascii=False, separators=(",", ":")).encode() + assert len(compact) < len(payload) + assert decode_state(compact, max_bytes=len(compact)) == decode_state(payload) From 992d13b2d280f8196f5a5c0dde37f989b29cbeed Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 21:32:01 +0300 Subject: [PATCH 07/85] feat(core): add native Spark mean and constant imputation Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 13 +- docs/user_guide/spark.md | 116 +++++++- .../spark_and_mlflow/01-core-spark-plan.md | 8 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 49 +++- initiatives/spark_and_mlflow/README.md | 4 +- skyulf-core/skyulf/core/portable_state.py | 10 +- skyulf-core/skyulf/preprocessing/_spark.py | 57 +++- .../preprocessing/imputation/_spark_simple.py | 171 ++++++++++++ .../skyulf/preprocessing/imputation/simple.py | 69 ++++- skyulf-core/skyulf/preprocessing/pipeline.py | 16 +- .../tests/spark/test_frame_contract.py | 2 +- .../tests/spark/test_simple_imputer.py | 258 ++++++++++++++++++ 12 files changed, 727 insertions(+), 46 deletions(-) create mode 100644 skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py create mode 100644 skyulf-core/tests/spark/test_simple_imputer.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index d61c7f795..fb330e13a 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -35,7 +35,7 @@ execution and MLflow adapters remain under development. before execution, and verifies key/target preservation after native steps. Spark dispatcher preparation preserves distributed frames; local FE behavior remains available. Unknown distributed metrics replace local profiling guesses. - Built-in Spark FE nodes remain unsupported pending their native implementations. + Node support is enabled separately by native implementations. - Versioned portable-state codec for StandardScaler and mean/constant SimpleImputer artifacts. Tagged UTF-8 JSON preserves scalar types, non-finite @@ -43,10 +43,17 @@ execution and MLflow adapters remain under development. a semantic checksum. Arbitrary Python objects are rejected; existing pipeline persistence and fingerprint behavior remain unchanged. +- Native Spark SimpleImputer mean/constant fit and apply: one aggregate result + holds learned values and missing counts; apply uses Spark expressions without + pandas conversion or Python UDFs. Portable state supports cross-engine apply + with pandas/Polars. The keyed runner normalizes defaults, preserves explicit + empty selections and enforces configured state-byte limits. Median/mode remain + unsupported; the Spark guide includes pipeline and cross-engine examples. + ### Planned scope — not yet available -- Native Spark feature engineering with explicit fit/apply capabilities and - portable fitted state for supported pandas/Polars/Spark operations. +- Further native Spark nodes, beginning with StandardScaler, and broader + cross-engine fit/apply coverage. - Distributed Python inference: native Spark preprocessing followed by Python prediction, or a compatible Python preprocessing/model pipeline on workers. - Optional MLflow tracking/model packaging and Unity Catalog model resolution. diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index c4d78ff4f..d75dc7192 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -3,7 +3,8 @@ Spark support is under development for 0.9.0. The optional dependency and runtime tests, Spark engine adapter and keyed FeatureEngineer entry point are available in the development checkout. -**Native nodes and distributed model inference are not available yet.** +**Native SimpleImputer supports mean/constant fit and apply.** Other built-in +native nodes and distributed model inference remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. ## Why a separate environment? @@ -67,7 +68,7 @@ finally: spark.stop() ``` -Only one aggregate row is returned to Python. Future native FE operations will +Only one aggregate row is returned to Python. Supported native FE operations keep the dataset in Spark and transfer bounded learned state when supported. Python model inference on Spark workers is a separate capability from native Spark model training. @@ -138,7 +139,8 @@ Engine values are `pandas`, `polars` and `spark`; `databricks` names a platform, not an engine. Unknown configuration fields and nonpositive/noninteger limits are rejected. These immutable objects declare requirements; they do not apply memory limits themselves. The Spark FeatureEngineer entry point validates actual -key values as described below; state/model budgets belong to later execution stages. +key values as described below and enforces `state_max_bytes` for nodes declaring +the portable codec. Model budgets belong to later inference stages. ## Keyed Spark FeatureEngineer entry point @@ -183,8 +185,10 @@ produce raw Spark outputs; wrapped inputs retain their wrapper convention. Every step must declare both fit and apply support before fitting starts. Apply also checks all fitted steps before execution. This path accepts native, row-preserving operations with row-local apply behavior. Worker Python, window, -filtering and expansion paths require later implementations. No built-in Spark -FE node is enabled yet; unsupported nodes fail before any validation action or fit. +filtering and expansion paths require later implementations. SimpleImputer +mean/constant is available; unsupported nodes or strategies fail before any +validation action or fit. The runner normalizes registered node defaults before +checking capabilities, so an omitted SimpleImputer strategy means `mean`. Custom native nodes use the existing engine-keyed dispatcher mapping with a `"spark"` implementation. It receives the full native frame, `y=None` and the resolved feature names in `config["columns"]`; the returned frame retains keys @@ -212,6 +216,88 @@ Transform preserves key identity, not physical row order, including when replaces fitted steps; a failed refit leaves the last successful fitted steps available. The portable learned-state codec is described below. +## Native SimpleImputer: fit once, apply without relearning + +The following pipeline learns the mean on training data and applies that same +value to an unlabeled batch. Use a caller-owned Spark session as above: + +```python +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.preprocessing.pipeline import FeatureEngineer + +train = spark.createDataFrame( + [(1, 1.0, 0), (2, None, 1), (3, 3.0, 0)], + "customer_id long, amount double, label long", +).repartition(2) +engineer = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer", + "params": {"columns": ["amount"], "strategy": "mean"}}], + frame_spec=FrameSpec(row_keys=("customer_id",), target="label"), + execution_options=ExecutionOptions(engine="spark", state_max_bytes=8192), +) +training, metrics = engineer.fit_transform(train) +batch = spark.createDataFrame( + [(10, 100.0), (11, None)], "customer_id long, amount double", +) +output = engineer.transform(batch) +# Collect only this tiny demonstration; production output remains a Spark frame. +assert [row.amount for row in output.orderBy("customer_id").collect()] == [100.0, 2.0] +``` + +`mean` fit aggregates means and missing counts together, returning one statistics +row to the driver. `constant` fit also aggregates missing counts for the artifact; +the fill value itself is supplied in `fill_value`. Both null and floating NaN +count as missing. Direct node apply constructs native Spark expressions without +a data action, Python UDF or pandas conversion. FeatureEngineer additionally +performs the key/target validation actions described above. + +Selection and dtype rules: + +- Explicit `columns=[]` is a no-op. Omitted columns select numeric mean + candidates automatically, excluding all-missing, constant and binary columns. + Automatic detection adds min/max, distinct-count and binary checks to the same + aggregate query; Spark may shuffle data internally. Explicit columns avoid + this selection cost and can include binary or constant numeric columns. +- The pipeline protects keys and target. A direct calculator has no `FrameSpec`; + specify its feature columns explicitly to avoid learning from identifiers. +- Mean supports Spark byte/short/integer/long/float/double columns. Mean filling + can promote integers to double; it does not promise exact large-integer output. + Explicitly selected all-missing numeric columns retain an undefined mean and + remain missing. Spark/Polars use `None` for that mean; pandas can use NaN. +- Numeric constant defaults to zero. String and boolean columns require an + explicit compatible string or boolean value. Integer constants must fit + signed 64-bit integers; integer-only filling preserves large integer values. + Decimal, date/time and nested imputation are not supported. +- Non-finite computed means are rejected. Median and most-frequent/mode remain + unsupported on Spark; there is no local fallback. Exact feature names and + Spark's case-sensitivity setting must not produce ambiguous columns. + +Learned state can also cross engines explicitly. This example fits on pandas and +applies to Spark; swapping the fit/apply engines follows the same codec contract: + +```python +import pandas as pd +from skyulf.core.portable_state import encode_state, decode_state +from skyulf.preprocessing.imputation.simple import ( + SimpleImputerCalculator, SimpleImputerApplier, +) + +state = SimpleImputerCalculator().fit( + pd.DataFrame({"amount": [1.0, None, 3.0]}), + {"columns": ["amount"], "strategy": "mean"}, +) +payload = encode_state("SimpleImputer", state, max_bytes=8192) +_, restored = decode_state(payload, max_bytes=8192) +batch = spark.createDataFrame([(100.0,), (None,)], "amount double") +output = SimpleImputerApplier().apply(batch, restored) +assert [row.amount for row in output.collect()] == [100.0, 2.0] +``` + +Only the small artifact crosses engines. The Spark dataset remains distributed. +Existing input column order is retained; direct apply appends missing learned +columns when a usable fill value exists. The keyed pipeline requires configured +input feature columns to be present. Output rows must still be matched by keys. + ## Portable learned state The development codec transports a small learned-parameter dictionary as @@ -267,11 +353,12 @@ Pass the same custom budget at both ends when changing it. The limit applies to wire bytes; it is not a bound on total Python process memory. The codec performs no filesystem or network I/O. Callers own storage and transport of these bytes. -This API does not enable Spark node execution or automatically package a -FeatureEngineer pipeline. Connecting these artifacts to native Spark imputer -and scaler implementations follows in SM-05/SM-06; worker model loading comes -later. Codec tests run in both base and Spark development environments without -starting a JVM. +The Spark runner validates each declared v1 artifact through the codec and +enforces `ExecutionOptions.state_max_bytes` after fit and before transform +validation actions. Direct node calls validate state structure but leave wire +byte limits to explicit encode/decode callers. The codec does not automatically +package a FeatureEngineer pipeline. Native StandardScaler and worker model +loading come later. Codec tests also run without starting a JVM. ### Inspecting declared support @@ -280,13 +367,14 @@ A capability check distinguishes fit and apply and never falls back to pandas: ```python from skyulf.core.capabilities import UnsupportedExecutionError, require_capability +require_capability("SimpleImputer", "fit", "spark", config={"strategy": "mean"}) try: - require_capability("SimpleImputer", "fit", "spark", config={"strategy": "mean"}) + require_capability("SimpleImputer", "fit", "spark", config={"strategy": "median"}) except UnsupportedExecutionError as error: print(error.node_type, error.operation, error.engine, error.reason) ``` -This currently reports unsupported: no built-in Spark node has been enabled. +Mean succeeds; median reports unsupported. The query requires explicit defaults. Existing local pipelines continue to work; this new preflight is not yet wired into their execution. A local node without an explicit declaration also fails this new query, even though its existing local pipeline path remains available. @@ -322,8 +410,8 @@ Spark code, certify compatibility or make a window transform batch-independent. use an environment that permits the owned JVM processes to terminate. - **Spark dependency unavailable:** install the optional `skyulf-core[spark]` dependency in a suitable environment, or use the repository requirements above. -- **Unsupported node:** the keyed entry point is available, but built-in native - FE nodes are still being implemented. Installing Spark does not enable them. +- **Unsupported node:** SimpleImputer mean/constant is available. Other built-in + native FE nodes are still being implemented; installing Spark does not enable them. MLflow tracking, Unity Catalog registration, Databricks jobs, serving endpoints and Bundle templates are separate integration stages. This page will gain diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index 79cb21a12..174ad4953 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -191,14 +191,14 @@ def test_state_rejects_future_version(): **Tüketir/üretir:** Mevcut SimpleImputer artifact anahtarları; mean/constant Spark fit ve apply. Median/most_frequent Spark fit bu görevde unsupported kalır. -- [ ] Local ve Spark mean/constant fixture'ları: train/test dağılımları farklı, +- [x] Local ve Spark mean/constant fixture'ları: train/test dağılımları farklı, null/NaN, tamamen boş kolon, boş seçim ve geçersiz tip; öğrenme yalnız train'den. -- [ ] Mean fit için seçilen kolonlarda bounded aggregate; constant için veri +- [x] Mean fit için seçilen kolonlarda bounded aggregate; constant için veri istatistiği gerekmiyorsa action yok. Missing counts gerekiyorsa aynı aggregate'e birleştir. Mevcut local boş kolon politikasını baseline'dan aynen koru. -- [ ] Apply yalnız Spark expressions kullansın; keys/target'a dokunmasın. +- [x] Apply yalnız Spark expressions kullansın; keys/target'a dokunmasın. Capability stratejiye göre karar versin; median'ı mean'e dönüştürme. -- [ ] Apply planında Python UDF olmadığını, row/key setinin korunduğunu doğrula. +- [x] Apply planında Python UDF olmadığını, row/key setinin korunduğunu doğrula. ```python def test_spark_mean_uses_only_training_data(spark): diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 9380e3449..3458e0a3f 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-04 tamamlandı. Sonraki görev: SM-05. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-05 tamamlandı. Sonraki görev: SM-06. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -14,8 +14,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-02 | Spark engine ve conversion sınırı | SM-01 | DONE | Gerçek Spark adapter; conversion korumaları; aşağıda kanıt | | SM-03 | Dispatcher, schema, row keys | SM-02 | DONE | Keyed Spark FE giriş/preflight; aşağıda kanıt | | SM-04 | Versioned portable state | SM-03 | DONE | Tagged state, limit/version/schema kontrolü; aşağıda kanıt | -| SM-05 | Native SimpleImputer | SM-04 | READY | Mean/constant train-only fit, Spark apply | -| SM-06 | Native StandardScaler | SM-05 | WAIT | Population variance ve flag parity | +| SM-05 | Native SimpleImputer | SM-04 | DONE | Mean/constant train-only fit, Spark apply; aşağıda kanıt | +| SM-06 | Native StandardScaler | SM-05 | READY | Population variance ve flag parity | | SM-07 | Uçtan uca FE kapısı | SM-06 | WAIT | Üç engine çapraz fit/apply; kayıt/yükleme | | SM-08 | Ortak inference bundle | SM-07 | WAIT | Raw/features ayrımı; model metadata round-trip | | SM-09 | Native FE + worker model | SM-08 | WAIT | Spark tahmini local ile key bazında aynı | @@ -224,3 +224,46 @@ ve MLflow entegrasyonu henüz yok. - Sınır: ayrı codec API'sidir; FeatureEngineer/model worker için otomatik paketleme yok. Byte limiti toplam process memory limiti değildir. Native SimpleImputer SM-05, StandardScaler SM-06; Spark runtime/Databricks bu görevde çalıştırılmadı. + +## SM-05 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `81216e16`; bu kayıt SM-05 çalışma ağacına aittir. +- `imputation/_spark_simple.py`: mean/constant için native fit/apply. Mean, + missing counts ve otomatik seçim istatistikleri aynı aggregate sorgusunda; + driver'a tek istatistik satırı döner. Constant da mevcut artifact missing-count + sözleşmesi için aggregate kullanır. Boş kolon seçimi doğrudan no-op. +- Apply native expressions kullanır; veri action'ı, Python UDF veya pandas + fallback yok. FeatureEngineer'ın key/target doğrulama action'ları devam eder. + Integer constant hassasiyeti korunur; mean double promotion yapabilir. + All-null mean uydurulmaz; numeric/string/bool sabitlerin sınırları rehberde. +- Registry mean/constant için fit/apply capability ve codec v1 bildirir. + Runner node default'larını preflight öncesi normalize eder; açık `columns=[]` + korunur. `state_max_bytes` fit artifact'ında ve transform action'larından önce + uygulanır. Direct apply codec yapısal doğrulamasını wire limiti dayatmadan kullanır. +- pandas/Polars/Spark arasında 18 fit/apply kombinasyonu JSON round-trip ile + doğrulandı. Yeni test dosyasında 36 vaka: train-only öğrenme, null/NaN, + all-null, kolon seçimi, dtype, key/target, lazy plan, state bütçesi ve precision. +- İlk TDD koşusu **19 failed, 8 passed**; native uygulama sonrası **26 passed**, + bir fixture DDL quoting hatası düzeltildi. Bağımsız review üç yakın-binary + değerin yanlış elenmesini ve imported state'in `x`/`X` çakışmasını buldu. + Gerçek runtime tekrarları ve regresyonlarla düzeltildi; review recheck temiz. +- Gerçek Spark komutu: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + -q --tb=short -o addopts= -p no:cacheprovider + --basetemp .cache/sm05-spark-full` + → **157 passed, 2 warnings**, 112.97 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm05-core-full` + → **9945 passed, 143 skipped, 1077 warnings**, 185.45 saniye. + Base ortamda PySpark yok; 36 yeni runtime testi burada skip, üstte gerçek Spark'ta geçti. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Spark rehberindeki + session kurulumundan sonraki yedi Python snippet'i aynı gerçek session'da + çalıştırıldı: `.venv-spark/Scripts/python.exe -m pytest + .cache/sm05_docs/test_spark_examples.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm05-doc-examples` + → **1 passed**, 27.12 saniye; mevcut pandas fillna FutureWarning. +- Sınır: median/mode, StandardScaler native apply, distributed model inference, + MLflow ve Databricks/Connect entegrasyon kanıtı henüz yok. Sonraki görev SM-06. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index d85d6b3f3..d931e58b3 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-04 tamamlandı; sıradaki görev SM-05.** +Tarih: 2026-09-21. Durum: **SM-00–SM-05 tamamlandı; sıradaki görev SM-06.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-05**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-06**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/core/portable_state.py b/skyulf-core/skyulf/core/portable_state.py index 6a4193104..8fda68952 100644 --- a/skyulf-core/skyulf/core/portable_state.py +++ b/skyulf-core/skyulf/core/portable_state.py @@ -34,11 +34,17 @@ def encode_state(node_type: str, params: Any, *, max_bytes: int) -> bytes: Empty dictionaries remain no-op artifacts. Other objects are rejected. """ _validate_limit(max_bytes) + normalized = validate_state(node_type, params) + document = _envelope(node_type, normalized) + return _json_bytes(document, max_bytes) + + +def validate_state(node_type: str, params: Any) -> dict[str, Any]: + """Validate and copy learned scalars without serializing bytes or imposing a wire limit.""" _validate_node(node_type) normalized = _normalize(params) _validate_state(node_type, normalized) - document = _envelope(node_type, normalized) - return _json_bytes(document, max_bytes) + return normalized def decode_state( diff --git a/skyulf-core/skyulf/preprocessing/_spark.py b/skyulf-core/skyulf/preprocessing/_spark.py index 38f18e2c8..727c60f73 100644 --- a/skyulf-core/skyulf/preprocessing/_spark.py +++ b/skyulf-core/skyulf/preprocessing/_spark.py @@ -8,6 +8,7 @@ from ..core.capabilities import UnsupportedExecutionError, require_capability from ..core.execution import ExecutionOptions, FrameSpec +from ..core.portable_state import DEFAULT_MAX_STATE_BYTES, decode_state, encode_state from ..data.dataset import SplitDataset from ..engines import SkyulfSparkWrapper, SparkEngine, get_engine from ..registry import NodeRegistry @@ -122,7 +123,12 @@ def _params(config: Any, spec: FrameSpec, frame: Any = None) -> dict[str, Any]: if columns and any(name in protected for name in columns): raise ValueError("Spark feature columns cannot include row_keys or target.") if frame is not None: - selected = columns or [name for name in frame.columns if name not in protected] + params.setdefault("_auto_columns", columns is None) + selected = ( + columns + if columns is not None + else [name for name in frame.columns if name not in protected] + ) if set(selected).difference(frame.columns): raise ValueError("Spark feature columns are missing or duplicated.") params["columns"] = selected @@ -165,7 +171,7 @@ def _preflight(steps: Any, spec: FrameSpec, *, training: bool) -> None: operations = ("fit", "apply") if training else ("apply",) for step in steps: node_type = step["transformer"] if training else step["type"] - params = _params(step.get("params", {}), spec) + params = _params(_node_config(node_type, step.get("params", {})), spec) for operation in operations: require_capability(node_type, operation, "spark", config=params) declarations = vars(NodeRegistry.get_calculator(node_type))[ @@ -197,7 +203,9 @@ def _check_output(before: Any, output: Any, spec: FrameSpec) -> Any: return after -def fit_spark(data: Any, steps: Any, spec: FrameSpec) -> tuple[Any, dict, list[dict]]: +def fit_spark( + data: Any, steps: Any, spec: FrameSpec, *, state_max_bytes: int = DEFAULT_MAX_STATE_BYTES +) -> tuple[Any, dict, list[dict]]: """Fit/apply native steps transactionally, reporting unknown distributed metrics.""" _preflight(steps, spec, training=True) current = _native(data) @@ -206,12 +214,13 @@ def fit_spark(data: Any, steps: Any, spec: FrameSpec) -> tuple[Any, dict, list[d records = [] step_metrics = {} for index, step in enumerate(steps): - params = _params(step.get("params", {}), spec, current) node_type = step["transformer"] + params = _params(_node_config(node_type, step.get("params", {})), spec, current) calculator = NodeRegistry.get_calculator(node_type)() applier = NodeRegistry.get_applier(node_type)() start = time.perf_counter() artifact = dict(calculator.fit(current, params)) + artifact = _checked_state(node_type, artifact, params, state_max_bytes) current = _check_output(current, applier.apply(current, artifact), spec) step_metrics[f"{index}:{step['name']}"] = { "driver_elapsed_seconds": time.perf_counter() - start, @@ -233,18 +242,52 @@ def fit_spark(data: Any, steps: Any, spec: FrameSpec) -> tuple[Any, dict, list[d return _restore(current, data), metrics, records -def transform_spark(data: Any, steps: Any, spec: FrameSpec) -> Any: +def transform_spark( + data: Any, steps: Any, spec: FrameSpec, *, state_max_bytes: int = DEFAULT_MAX_STATE_BYTES +) -> Any: """Apply fitted native steps to labeled or unlabeled data using key identity.""" _preflight(steps, spec, training=False) + artifacts = [ + _checked_state(step["type"], step["artifact"], step["params"], state_max_bytes) + for step in steps + ] current = _native(data) _validate_schema(current, spec, training=False) _validate_keys(current, spec) - for step in steps: + for step, artifact in zip(steps, artifacts, strict=True): _params(step["params"], spec, current) - current = _check_output(current, step["applier"].apply(current, step["artifact"]), spec) + current = _check_output(current, step["applier"].apply(current, artifact), spec) return _restore(current, data) def _restore(frame: Any, original: Any) -> Any: """Preserve the caller's raw-versus-wrapper return convention.""" return SkyulfSparkWrapper(frame) if isinstance(original, SkyulfSparkWrapper) else frame + + +def _node_config(node_type: str, config: Any) -> dict[str, Any]: + """Normalize declared scalar defaults while keeping omitted columns distinct from [].""" + defaults = NodeRegistry.get_all_metadata().get(node_type, {}).get("params", {}) + return { + **{key: deepcopy(value) for key, value in defaults.items() if key != "columns"}, + **config, + } + + +def _checked_state(node_type: str, artifact: dict, config: dict, max_bytes: int) -> dict: + """Enforce the declared portable codec before apply or distributed input actions.""" + declarations = vars(NodeRegistry.get_calculator(node_type)).get( + "__execution_capabilities__", () + ) + versions = { + item.codec_version + for item in declarations + if item.engine == "spark" and item.operation == "apply" and item.matches_config(config) + } + if versions == {None}: + return artifact + if versions != {1}: + raise ValueError("Unsupported or ambiguous portable codec version.") + return decode_state( + encode_state(node_type, artifact, max_bytes=max_bytes), max_bytes=max_bytes + )[1] diff --git a/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py b/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py new file mode 100644 index 000000000..750d7cc8b --- /dev/null +++ b/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py @@ -0,0 +1,171 @@ +"""Native Spark SimpleImputer branches with one bounded fit aggregate.""" + +import importlib +import math +from typing import Any + +from ...core.capabilities import require_capability +from ...core.portable_state import validate_state +from .._spark import _column, _resolved_names + +_NUMERIC = {"byte", "short", "integer", "long", "float", "double"} +_FLOATING = {"float", "double"} + + +def _missing(frame: Any, name: str, dtype: str, functions: Any) -> Any: + """Treat both nulls and floating NaNs as missing using native expressions.""" + column = _column(frame, name) + return column.isNull() | functions.isnan(column) if dtype in _FLOATING else column.isNull() + + +def _columns(frame: Any, config: dict, strategy: str) -> tuple[list[str], dict[str, str], bool]: + """Resolve exact names and schema-eligible candidates without a data action.""" + names = _resolved_names(frame) + if len(set(names)) != len(names): + raise ValueError("Duplicate Spark column names.") + schema = {field.name: field.dataType.typeName() for field in frame.schema.fields} + automatic = config.get("_auto_columns", config.get("columns") is None) + cols = config.get("columns") + if cols is None: + cols = [name for name in frame.columns if name != config.get("target_column")] + if not isinstance(cols, list) or any(not isinstance(name, str) for name in cols): + raise ValueError("columns must be a list of names.") + if len(set(cols)) != len(cols) or set(cols).difference(schema): + raise ValueError("Spark imputer columns are missing or duplicated.") + if automatic and strategy == "mean": + cols = [name for name in cols if schema[name] in _NUMERIC] + return cols, schema, automatic + + +def _constant(value: Any, dtype: str) -> Any: + """Require unambiguous scalar constants, preserving integer precision.""" + if dtype in _NUMERIC: + value = 0 if value is None else value + if type(value) not in (int, float): + raise TypeError("Numeric Spark columns require a numeric fill_value.") + if type(value) is int and not -(2**63) <= value < 2**63: + raise ValueError("Spark integer fill_value must fit a signed 64-bit integer.") + return value + if dtype == "string": + if value is None: + raise ValueError("String constant imputation requires an explicit fill_value.") + if type(value) is str: + return value + if dtype == "boolean" and type(value) is bool: + return value + raise TypeError("Unsupported Spark imputer dtype or incompatible fill_value.") + + +def _aggregate_expressions( + frame: Any, cols: list[str], schema: dict, strategy: str, automatic: bool, functions: Any +) -> list[Any]: + """Combine missing counts, means and optional selection statistics in one query.""" + expressions = [] + for index, name in enumerate(cols): + missing = _missing(frame, name, schema[name], functions) + expressions.append( + functions.sum(functions.when(missing, 1).otherwise(0)).alias(f"n{index}") + ) + if strategy == "mean": + valid = functions.when(~missing, _column(frame, name)) + expressions.append(functions.avg(valid).alias(f"v{index}")) + if automatic: + expressions.extend(_selection_statistics(valid, index, functions)) + return expressions + + +def _selection_statistics(valid: Any, index: int, functions: Any) -> list[Any]: + """Mirror local binary/constant exclusion without collecting distinct values.""" + numeric = valid.cast("double") + binary = (functions.abs(numeric) <= 1e-8) | (functions.abs(numeric - 1) <= 1.001e-5) + return [ + functions.min(valid).alias(f"lo{index}"), + functions.max(valid).alias(f"hi{index}"), + functions.count_distinct(valid).alias(f"distinct{index}"), + functions.max(functions.when(~binary, 1).otherwise(0)).alias(f"other{index}"), + ] + + +def fit_spark_imputer(frame: Any, target: Any, config: dict) -> dict: + """Learn native mean/constant state, returning only one aggregate row to Python.""" + strategy = config.get("strategy", "mean") + require_capability("SimpleImputer", "fit", "spark", config={**config, "strategy": strategy}) + cols, schema, automatic = _columns(frame, config, strategy) + if not cols: + return {} + constants = {} + for name in cols: + if strategy == "mean" and schema[name] not in _NUMERIC: + raise TypeError("Spark mean imputation requires numeric columns.") + if strategy == "constant": + constants[name] = _constant(config.get("fill_value"), schema[name]) + functions = importlib.import_module("pyspark.sql.functions") + stats = frame.agg( + *_aggregate_expressions(frame, cols, schema, strategy, automatic, functions) + ).first() + return _artifact(cols, strategy, automatic, stats, constants) + + +def _artifact(cols: list[str], strategy: str, automatic: bool, stats: Any, constants: dict) -> dict: + """Build the existing artifact vocabulary without inventing all-null means.""" + fills = {} + counts = {} + for index, name in enumerate(cols): + value = constants[name] if strategy == "constant" else stats[f"v{index}"] + if strategy == "mean" and value is not None and not math.isfinite(value): + raise ValueError("Spark mean imputation requires finite observed values.") + if ( + strategy == "mean" + and automatic + and ( + stats[f"lo{index}"] == stats[f"hi{index}"] + or (stats[f"distinct{index}"] <= 2 and not stats[f"other{index}"]) + ) + ): + continue + fills[name] = value + counts[name] = int(stats[f"n{index}"] or 0) + if not fills: + return {} + return { + "type": "simple_imputer", + "strategy": strategy, + "columns": list(fills), + "fill_values": fills, + "missing_counts": counts, + "total_missing": sum(counts.values()), + } + + +def apply_spark_imputer(frame: Any, target: Any, params: dict) -> tuple[Any, Any]: + """Fill with native Spark expressions; do not refit or execute a data action.""" + if not params: + return frame, target + require_capability("SimpleImputer", "apply", "spark", config=params) + state = validate_state("SimpleImputer", params) + names = _resolved_names(frame) + if len(set(names)) != len(names): + raise ValueError("Duplicate Spark column names.") + combined = list(dict.fromkeys([*frame.columns, *state["columns"]])) + if frame.sparkSession.conf.get("spark.sql.caseSensitive") != "true": + combined = [name.lower() for name in combined] + if len(set(combined)) != len(combined): + raise ValueError("Fitted columns collide under Spark column name resolution.") + functions = importlib.import_module("pyspark.sql.functions") + schema = {field.name: field.dataType.typeName() for field in frame.schema.fields} + expressions = {name: _column(frame, name) for name in frame.columns} + for name in state["columns"]: + value = state["fill_values"][name] + if value is None or ( + state["strategy"] == "mean" and isinstance(value, float) and math.isnan(value) + ): + continue + replacement = functions.lit(value) + if name in schema: + _constant(value, schema[name]) + if state["strategy"] == "mean" and schema[name] not in _NUMERIC: + raise TypeError("Spark mean imputation requires numeric columns.") + missing = _missing(frame, name, schema[name], functions) + replacement = functions.when(missing, replacement).otherwise(_column(frame, name)) + expressions[name] = replacement.alias(name) + return frame.select(*expressions.values()), target diff --git a/skyulf-core/skyulf/preprocessing/imputation/simple.py b/skyulf-core/skyulf/preprocessing/imputation/simple.py index e5b1c58a0..7dbbe35e5 100644 --- a/skyulf-core/skyulf/preprocessing/imputation/simple.py +++ b/skyulf-core/skyulf/preprocessing/imputation/simple.py @@ -6,6 +6,7 @@ import polars as pl from sklearn.impute import SimpleImputer +from ...core.capabilities import ExecutionCapability from ...core.meta.decorators import node_meta from ...registry import NodeRegistry from ...utils import detect_numeric_columns, is_decimal_series, user_picked_no_columns @@ -23,6 +24,7 @@ _polars_missing_counts, _resolve_simple_columns, ) +from ._spark_simple import apply_spark_imputer, fit_spark_imputer class SimpleImputerApplier(BaseApplier): @@ -31,13 +33,21 @@ class SimpleImputerApplier(BaseApplier): The calculator artifact records per-column values for ``mean``, ``median``, ``most_frequent`` (also accepted as ``mode``), or ``constant`` strategies. Missing columns seen during fitting are restored with their stored value. + Spark supports only ``mean`` and ``constant`` artifacts and applies them + with native expressions. All-missing means leave existing columns untouched. """ @apply_method def apply(self, X: Any, _y: Any, params: dict[str, Any]) -> Any: # pylint: disable=arguments-differ """Fill nulls and NaNs with the fitted per-column values; ``y`` passes through.""" return apply_dual_engine( - X, params, {"polars": self._apply_polars, "pandas": self._apply_pandas} + X, + params, + { + "polars": self._apply_polars, + "pandas": self._apply_pandas, + "spark": apply_spark_imputer, + }, ) @staticmethod @@ -104,7 +114,23 @@ def _apply_pandas(X: Any, _y: Any, params: dict[str, Any]) -> tuple[Any, Any]: return X_out, _y -@NodeRegistry.register("SimpleImputer", SimpleImputerApplier) +@NodeRegistry.register( + "SimpleImputer", + SimpleImputerApplier, + execution_capabilities=tuple( + ExecutionCapability( + "spark", + operation, + "native", + "preserve", + "global" if operation == "fit" else "row", + codec_version=1, + config_match=(("strategy", strategy),), + ) + for operation in ("fit", "apply") + for strategy in ("mean", "constant") + ), +) @node_meta( id="SimpleImputer", name="Simple Imputer", @@ -121,6 +147,8 @@ class SimpleImputerCalculator(BaseCalculator): ``columns`` to select columns and ``fill_value`` with ``constant``. Mean and median auto-select numeric columns and reject explicitly selected non-numeric columns. The other strategies can operate on all selected columns. + Spark supports only ``mean`` and ``constant`` through a native aggregate; + string and boolean constants require explicit compatible fill values. """ def infer_output_schema( @@ -141,8 +169,24 @@ def fit(self, X: Any, _y: Any, config: dict[str, Any]) -> SimpleImputerArtifact: ``mode`` is accepted as an alias of ``most_frequent``; mean/median are restricted to numeric columns. """ + return cast( + SimpleImputerArtifact, + fit_dual_engine( + X, + config, + { + "polars": self._fit_polars_input, + "pandas": self._fit_pandas_input, + "spark": fit_spark_imputer, + }, + ), + ) + + @staticmethod + def _prepare_local(X: Any, config: dict[str, Any]) -> dict[str, Any] | None: + """Keep existing local column/strategy resolution separate from Spark preparation.""" if user_picked_no_columns(config): - return {} + return None strategy = config.get("strategy", "mean") if strategy == "mode": @@ -151,7 +195,7 @@ def fit(self, X: Any, _y: Any, config: dict[str, Any]) -> SimpleImputerArtifact: cols = _resolve_simple_columns(X, config, strategy) if not cols: - return {} + return None if strategy in {"mean", "median"}: numeric = set(auto_detect_numeric_columns(X)) @@ -168,10 +212,19 @@ def fit(self, X: Any, _y: Any, config: dict[str, Any]) -> SimpleImputerArtifact: merged["_resolved_cols"] = cols merged["_resolved_fill_value"] = fill_value - return cast( - SimpleImputerArtifact, - fit_dual_engine(X, merged, {"polars": self._fit_polars, "pandas": self._fit_pandas}), - ) + return merged + + @staticmethod + def _fit_polars_input(X: Any, y: Any, config: dict[str, Any]) -> dict[str, Any]: + """Prepare the existing Polars contract before its fit implementation.""" + prepared = SimpleImputerCalculator._prepare_local(X, config) + return {} if prepared is None else SimpleImputerCalculator._fit_polars(X, y, prepared) + + @staticmethod + def _fit_pandas_input(X: Any, y: Any, config: dict[str, Any]) -> dict[str, Any]: + """Prepare the existing pandas contract before its fit implementation.""" + prepared = SimpleImputerCalculator._prepare_local(X, config) + return {} if prepared is None else SimpleImputerCalculator._fit_pandas(X, y, prepared) @staticmethod def _fit_polars(X: Any, _y: Any, params: dict[str, Any]) -> dict[str, Any]: diff --git a/skyulf-core/skyulf/preprocessing/pipeline.py b/skyulf-core/skyulf/preprocessing/pipeline.py index 68cd18912..fbfb9366f 100644 --- a/skyulf-core/skyulf/preprocessing/pipeline.py +++ b/skyulf-core/skyulf/preprocessing/pipeline.py @@ -130,7 +130,13 @@ def transform( if not getattr(self, "_spark_fitted", False): raise ValueError("Spark FeatureEngineer must be fitted before transform.") assert spec is not None - return transform_spark(data, self.fitted_steps, spec) + assert self.execution_options is not None + return transform_spark( + data, + self.fitted_steps, + spec, + state_max_bytes=self.execution_options.state_max_bytes, + ) current_data = data for step in self.fitted_steps: @@ -192,7 +198,13 @@ def fit_transform( raise ValueError("target_column conflicts with frame_spec.target.") if on_split is not None: raise ValueError("Spark FE uses one frame; on_split is unsupported.") - result, metrics, records = fit_spark(data, self.steps_config, spec) + assert self.execution_options is not None + result, metrics, records = fit_spark( + data, + self.steps_config, + spec, + state_max_bytes=self.execution_options.state_max_bytes, + ) self.fitted_steps = records self._spark_fitted = True return result, metrics diff --git a/skyulf-core/tests/spark/test_frame_contract.py b/skyulf-core/tests/spark/test_frame_contract.py index 47e9b19c1..3c7766ea3 100644 --- a/skyulf-core/tests/spark/test_frame_contract.py +++ b/skyulf-core/tests/spark/test_frame_contract.py @@ -110,7 +110,7 @@ def forbidden(*args, **kwargs): monkeypatch.setattr(type(frame), name, forbidden) steps = [ {"name": "first", "transformer": "TestSparkDouble"}, - {"name": "last", "transformer": "SimpleImputer"}, + {"name": "last", "transformer": "SimpleImputer", "params": {"strategy": "median"}}, ] with pytest.raises(UnsupportedExecutionError, match="SimpleImputer"): engineer(steps, target=None).fit_transform(frame) diff --git a/skyulf-core/tests/spark/test_simple_imputer.py b/skyulf-core/tests/spark/test_simple_imputer.py new file mode 100644 index 000000000..cd5bb354e --- /dev/null +++ b/skyulf-core/tests/spark/test_simple_imputer.py @@ -0,0 +1,258 @@ +"""Native imputation must learn bounded state and keep distributed input in Spark.""" + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.capabilities import UnsupportedExecutionError +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.core.portable_state import decode_state, encode_state +from skyulf.preprocessing.imputation.simple import SimpleImputerApplier, SimpleImputerCalculator +from skyulf.preprocessing.pipeline import FeatureEngineer + + +@pytest.mark.parametrize("fit_engine", ["pandas", "polars", "spark"]) +@pytest.mark.parametrize("apply_engine", ["pandas", "polars", "spark"]) +@pytest.mark.parametrize("strategy", ["mean", "constant"]) +def test_cross_engine_state_uses_training_only(spark, fit_engine, apply_engine, strategy): + """Held-out values must never replace learned fill values during cross-engine apply.""" + local = pd.DataFrame({"x": [1.0, np.nan, 3.0]}) + train = { + "pandas": lambda: local, + "polars": lambda: pl.from_pandas(local), + "spark": lambda: spark.createDataFrame([(1.0,), (None,), (3.0,)], "x double"), + }[fit_engine]() + params = SimpleImputerCalculator().fit( + train, {"columns": ["x"], "strategy": strategy, "fill_value": 7.0} + ) + _, params = decode_state(encode_state("SimpleImputer", params, max_bytes=8192)) + held_out = pd.DataFrame({"x": [100.0, np.nan]}) + data = { + "pandas": lambda: held_out, + "polars": lambda: pl.from_pandas(held_out), + "spark": lambda: spark.createDataFrame([(100.0,), (None,)], "x double"), + }[apply_engine]() + out = SimpleImputerApplier().apply(data, params) + values = [row.x for row in out.collect()] if apply_engine == "spark" else out["x"].to_list() + assert values == [100.0, 2.0 if strategy == "mean" else 7.0] + assert params["missing_counts"] == {"x": 1} + + +def test_native_mean_counts_null_nan_and_preserves_all_empty(spark): + """All-missing numeric columns must remain missing rather than receive invented means.""" + train = spark.createDataFrame( + [(1.0, None), (None, None), (float("nan"), None), (3.0, None)], "x double, empty double" + ) + state = SimpleImputerCalculator().fit(train, {"columns": ["x", "empty"]}) + assert state["fill_values"] == {"x": 2.0, "empty": None} + assert state["missing_counts"] == {"x": 2, "empty": 4} + out = SimpleImputerApplier().apply(train, state).collect() + assert [row.x for row in out] == [1.0, 2.0, 2.0, 3.0] + assert all(row.empty is None for row in out) + + +def test_apply_is_lazy_and_contains_no_python_udf(spark, monkeypatch, capsys): + """Transform must consist of native expressions without an implicit data action.""" + frame = spark.createDataFrame([(None,), (5.0,)], "`a.b` double") + state = { + "type": "simple_imputer", + "strategy": "constant", + "columns": ["a.b"], + "fill_values": {"a.b": 4.0}, + "missing_counts": {"a.b": 1}, + "total_missing": 1, + } + + def forbidden(*args, **kwargs): + """Catch driver materialization while constructing the apply plan.""" + pytest.fail("Action in native apply") + + with monkeypatch.context() as patch: + for name in ("collect", "count", "toPandas", "toArrow", "first"): + patch.setattr(type(frame), name, forbidden) + output = SimpleImputerApplier().apply(frame, state) + output.explain(extended=True) + plan = capsys.readouterr().out + assert ( + "PythonUDF" not in plan and "BatchEvalPython" not in plan and "ArrowEvalPython" not in plan + ) + assert [row[0] for row in output.collect()] == [4.0, 5.0] + + +@pytest.mark.parametrize("strategy", ["median", "most_frequent", "mode"]) +def test_unsupported_strategy_fails_before_actions(spark, monkeypatch, strategy): + """Native mean must never stand in for unsupported fitting strategies.""" + frame = spark.range(2) + + def forbidden(*args, **kwargs): + """Make an early action observable.""" + pytest.fail("Action before unsupported rejection") + + monkeypatch.setattr(type(frame), "collect", forbidden) + with pytest.raises(UnsupportedExecutionError): + SimpleImputerCalculator().fit(frame, {"columns": ["id"], "strategy": strategy}) + + +def test_feature_engineer_defaults_keys_and_state_budget(spark): + """The default strategy must normalize before preflight and preserve keys and labels.""" + data = spark.createDataFrame([(1, None, 0), (2, 4.0, 1)], "id long, x double, label long") + steps = [{"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x"]}}] + engineer = FeatureEngineer( + steps, frame_spec=FrameSpec(("id",), "label"), execution_options=ExecutionOptions("spark") + ) + output, _ = engineer.fit_transform(data.repartition(2)) + assert sorted(tuple(row) for row in output.collect()) == [(1, 4.0, 0), (2, 4.0, 1)] + limited = FeatureEngineer( + steps, + frame_spec=FrameSpec(("id",), "label"), + execution_options=ExecutionOptions("spark", state_max_bytes=10), + ) + with pytest.raises(ValueError, match="max_bytes"): + limited.fit_transform(data) + + +def test_empty_selection_does_not_become_auto_selection(spark): + """An explicit deselection must remain a no-op even through the Spark runner.""" + data = spark.createDataFrame([(1, None), (2, 4.0)], "id long, x double") + engineer = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer", "params": {"columns": []}}], + frame_spec=FrameSpec(("id",)), + execution_options=ExecutionOptions("spark"), + ) + output, _ = engineer.fit_transform(data) + assert engineer.fitted_steps[0]["artifact"] == {} + assert output.orderBy("id").first().x is None + + +def test_auto_numeric_selection_matches_local_heuristics(spark): + """Automatic mean must skip strings, constants and binary columns without collecting raw data.""" + data = spark.createDataFrame( + [(1, 2.0, 1.0, "a"), (2, 4.0, 0.0, None), (3, None, None, "b")], + "id long, x double, binary double, text string", + ) + engineer = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer"}], + frame_spec=FrameSpec(("id",)), + execution_options=ExecutionOptions("spark"), + ) + output, _ = engineer.fit_transform(data) + assert engineer.fitted_steps[0]["artifact"]["columns"] == ["x"] + assert output.orderBy("id").collect()[2].x == 3.0 + + +def test_string_constant_and_invalid_mean(spark): + """String constants are explicit and cannot masquerade as numerical means.""" + data = spark.createDataFrame([(None,), ("a",)], "text string") + state = SimpleImputerCalculator().fit( + data, {"columns": ["text"], "strategy": "constant", "fill_value": "missing"} + ) + assert [r.text for r in SimpleImputerApplier().apply(data, state).collect()] == ["missing", "a"] + with pytest.raises(TypeError, match="numeric"): + SimpleImputerCalculator().fit(data, {"columns": ["text"], "strategy": "mean"}) + with pytest.raises(ValueError, match="explicit"): + SimpleImputerCalculator().fit(data, {"columns": ["text"], "strategy": "constant"}) + + +def test_fit_collects_one_aggregate_and_empty_selection_is_lazy(spark, monkeypatch): + """Learning may collect bounded statistics, but never the training frame itself.""" + data = spark.createDataFrame([(1.0,), (None,), (3.0,)], "x double") + original = type(data).first + schemas = [] + + def record_first(frame): + """Record the aggregate boundary without blocking its execution.""" + schemas.append(frame.columns) + return original(frame) + + monkeypatch.setattr(type(data), "first", record_first) + state = SimpleImputerCalculator().fit(data, {"columns": ["x"]}) + assert state["fill_values"] == {"x": 2.0} + assert schemas == [["n0", "v0"]] + assert SimpleImputerCalculator().fit(data, {"columns": []}) == {} + assert len(schemas) == 1 + + +def test_integer_constant_preserves_large_values_and_mean_promotes(spark): + """Constant filling must not round signed integers through a double conversion.""" + large = 2**53 + 1 + data = spark.createDataFrame([(large,), (None,)], "x long") + state = SimpleImputerCalculator().fit( + data, {"columns": ["x"], "strategy": "constant", "fill_value": large} + ) + out = SimpleImputerApplier().apply(data, state) + assert out.dtypes == [("x", "bigint")] + assert [row.x for row in out.collect()] == [large, large] + small = spark.createDataFrame([(1,), (2,), (None,)], "x long") + mean = SimpleImputerCalculator().fit(small, {"columns": ["x"]}) + assert [row.x for row in SimpleImputerApplier().apply(small, mean).collect()] == [1, 2, 1.5] + + +def test_apply_rejects_ambiguous_columns(spark): + """A direct applier must not silently collapse duplicate input column names.""" + data = spark.createDataFrame([(1.0, 2.0)], ["x", "x"]) + state = { + "type": "simple_imputer", + "strategy": "mean", + "columns": ["x"], + "fill_values": {"x": 2.0}, + "missing_counts": {"x": 1}, + "total_missing": 1, + } + with pytest.raises(ValueError, match="Duplicate"): + SimpleImputerApplier().apply(data, state) + + +def test_transform_state_budget_fails_before_validation_actions(spark, monkeypatch): + """Oversized fitted state must fail before distributed transform validation starts.""" + data = spark.createDataFrame([(1, None), (2, 4.0)], "id long, x double") + engineer = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x"]}}], + frame_spec=FrameSpec(("id",)), + execution_options=ExecutionOptions("spark"), + ) + engineer.fit_transform(data) + engineer.execution_options = ExecutionOptions("spark", state_max_bytes=10) + + def forbidden(*args, **kwargs): + """Make any data action preceding state validation fail the test.""" + pytest.fail("Action before state validation") + + monkeypatch.setattr(type(data), "collect", forbidden) + with pytest.raises(ValueError, match="max_bytes"): + engineer.transform(data) + + +@pytest.mark.parametrize("engine", ["pandas", "polars", "spark"]) +def test_auto_selection_keeps_three_near_binary_values(spark, engine): + """Tolerance near zero/one must not turn three distinct values into a binary feature.""" + local = pd.DataFrame({"x": [0.0, 1e-9, 1.0, np.nan]}) + data = { + "pandas": lambda: local, + "polars": lambda: pl.from_pandas(local), + "spark": lambda: spark.createDataFrame([(0.0,), (1e-9,), (1.0,), (None,)], "x double"), + }[engine]() + state = SimpleImputerCalculator().fit(data, {}) + assert state["columns"] == ["x"] + assert state["fill_values"]["x"] == pytest.approx((1 + 1e-9) / 3) + + +@pytest.mark.parametrize("fitted_columns", [["x"], ["x", "X"]]) +def test_apply_rejects_case_collisions_from_imported_state(spark, fitted_columns): + """Restoring learned columns must not create ambiguous Spark output names.""" + previous = spark.conf.get("spark.sql.caseSensitive") + spark.conf.set("spark.sql.caseSensitive", "false") + try: + data = spark.createDataFrame([(None,), (100.0,)], "X double") + state = { + "type": "simple_imputer", + "strategy": "mean", + "columns": fitted_columns, + "fill_values": dict.fromkeys(fitted_columns, 2.0), + "missing_counts": dict.fromkeys(fitted_columns, 1), + "total_missing": len(fitted_columns), + } + with pytest.raises(ValueError, match="collide"): + SimpleImputerApplier().apply(data, state) + finally: + spark.conf.set("spark.sql.caseSensitive", previous) From 802f60d34522767a142d2393814fe65117a8532f Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 21:55:35 +0300 Subject: [PATCH 08/85] feat(core): add native Spark StandardScaler fit and apply Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 11 +- docs/user_guide/spark.md | 95 ++++++- .../spark_and_mlflow/01-core-spark-plan.md | 8 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 59 +++- initiatives/spark_and_mlflow/README.md | 4 +- .../skyulf/preprocessing/_spark_numeric.py | 67 +++++ .../preprocessing/imputation/_spark_simple.py | 90 ++---- .../preprocessing/scaling/_spark_standard.py | 163 +++++++++++ .../skyulf/preprocessing/scaling/standard.py | 49 +++- .../tests/spark/test_standard_scaler.py | 262 ++++++++++++++++++ 10 files changed, 716 insertions(+), 92 deletions(-) create mode 100644 skyulf-core/skyulf/preprocessing/_spark_numeric.py create mode 100644 skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py create mode 100644 skyulf-core/tests/spark/test_standard_scaler.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index fb330e13a..f135f4cf5 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -50,10 +50,17 @@ execution and MLflow adapters remain under development. empty selections and enforces configured state-byte limits. Median/mode remain unsupported; the Spark guide includes pipeline and cross-engine examples. +- Native Spark StandardScaler with population variance, all four centering/scaling + options and portable pandas/Polars/Spark state. Two bounded aggregate results + compute statistics relative to a numeric reference to avoid large-offset mean + errors; apply uses native Spark expressions. Null/NaN, constant/near-constant, + empty and single-row inputs have explicit tested behavior. Numeric selection + and name validation are shared with the native imputer. + ### Planned scope — not yet available -- Further native Spark nodes, beginning with StandardScaler, and broader - cross-engine fit/apply coverage. +- Full feature-pipeline state export/import, further native Spark nodes and + broader cross-engine fit/apply coverage. - Distributed Python inference: native Spark preprocessing followed by Python prediction, or a compatible Python preprocessing/model pipeline on workers. - Optional MLflow tracking/model packaging and Unity Catalog model resolution. diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index d75dc7192..88fd549d3 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -3,8 +3,8 @@ Spark support is under development for 0.9.0. The optional dependency and runtime tests, Spark engine adapter and keyed FeatureEngineer entry point are available in the development checkout. -**Native SimpleImputer supports mean/constant fit and apply.** Other built-in -native nodes and distributed model inference remain under development. +**Native SimpleImputer (mean/constant) and StandardScaler support fit and apply.** +Other built-in native nodes and distributed model inference remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. ## Why a separate environment? @@ -186,9 +186,10 @@ Every step must declare both fit and apply support before fitting starts. Apply also checks all fitted steps before execution. This path accepts native, row-preserving operations with row-local apply behavior. Worker Python, window, filtering and expansion paths require later implementations. SimpleImputer -mean/constant is available; unsupported nodes or strategies fail before any +mean/constant and StandardScaler are available; unsupported nodes or strategies fail before any validation action or fit. The runner normalizes registered node defaults before -checking capabilities, so an omitted SimpleImputer strategy means `mean`. +checking capabilities, so an omitted SimpleImputer strategy means `mean`, and +StandardScaler defaults to `with_mean=True, with_std=True`. Custom native nodes use the existing engine-keyed dispatcher mapping with a `"spark"` implementation. It receives the full native frame, `y=None` and the resolved feature names in `config["columns"]`; the returned frame retains keys @@ -298,6 +299,81 @@ Existing input column order is retained; direct apply appends missing learned columns when a usable fill value exists. The keyed pipeline requires configured input feature columns to be present. Output rows must still be matched by keys. +## Native StandardScaler: center and scale + +StandardScaler learns per-column statistics on Spark and applies them with native +expressions. Its population variance matches the local node's `ddof=0` convention, +as documented by [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html). +It uses Spark's native +[`var_pop`](https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.var_pop.html) +on shifted values to reduce numerical error. + +```python +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.preprocessing.pipeline import FeatureEngineer + +train = spark.createDataFrame( + [(1, 1.0, 0), (2, 3.0, 1)], "id long, amount double, label long", +).repartition(2) +scaler = FeatureEngineer( + [{"name": "scale", "transformer": "StandardScaler", + "params": {"columns": ["amount"], "with_mean": True, "with_std": True}}], + frame_spec=FrameSpec(row_keys=("id",), target="label"), + execution_options=ExecutionOptions(engine="spark", state_max_bytes=8192), +) +scaled_train, _ = scaler.fit_transform(train) +assert [r.amount for r in scaled_train.orderBy("id").collect()] == [-1.0, 1.0] +batch = spark.createDataFrame([(10, 5.0)], "id long, amount double") +assert scaler.transform(batch).first().amount == 3.0 +``` + +The same mean/variance/scale artifact can be encoded with +`encode_state("StandardScaler", state, max_bytes=...)` and applied using +`StandardScalerApplier` on pandas, Polars or Spark. State list positions follow +`columns`; apply matches names and retains input column order. Row order is not +an identity guarantee. + +| `with_mean` | `with_std` | Apply formula | Learned statistics | +| --- | --- | --- | --- | +| True | True | `(x - mean) / scale` | mean, population variance, scale | +| True | False | `x - mean` | mean; variance/scale are None | +| False | True | `x / scale` | mean, population variance, scale | +| False | False | unchanged | mean/variance/scale are None | + +Fit performs at most two distributed aggregate queries. The first finds numeric +reference values and validates selected input; the second calculates means and +population variances of deviations from those references. This avoids accumulating +the same large offset in every addition. A range spanning zero keeps a zero +reference; a same-sign range uses its endpoint nearest zero. Each query returns one O(columns) row, +never training samples. With both flags disabled, only the first query is needed. +Automatic selection adds the same binary/constant checks as the imputer. These +queries and the pipeline's identity checks can scan or shuffle data; this is not +a single-pass training algorithm. + +- Null/NaN observations are excluded from fitting. Apply preserves missing + values. Explicit all-missing columns learn NaN statistics; later observed + values become NaN when an enabled operation uses those statistics. +- Constant and numerically near-constant features receive unit scale using the + local sklearn error-bound rule. A single observation has zero variance and + unit scale. Imported zero scales are also treated as one during apply. +- `columns=[]` is a no-op. Explicit feature selection on zero training rows + raises an error; automatic selection on empty data has no eligible features. + Direct apply skips absent learned columns, matching the local scaler; the + keyed pipeline requires its configured feature columns to exist. +- Primitive numeric Spark types and explicitly selected booleans are supported. + Enabled operations produce double columns; disabling both retains original + types. Automatic selection skips booleans. Strings, Decimal and nested feature + types are rejected, without casting text or falling back to pandas. +- Selected training infinities and overflowing aggregates are rejected. Double + conversion can lose precision for very large integers. Distributed reduction + order can still cause floating-point differences: ordinary parity fixtures use + `rtol=1e-10, atol=1e-12`; the large-offset/small-spread fixture allows `rtol=0.002` + because representable spacing near `1e12` is significant relative to its spread. + +Direct apply is lazy, with no Python UDF or data action. FeatureEngineer still +executes the identity checks described above. This implementation has been tested +on the local PySpark runtime; Databricks/Connect validation remains a later gate. + ## Portable learned state The development codec transports a small learned-parameter dictionary as @@ -357,8 +433,8 @@ The Spark runner validates each declared v1 artifact through the codec and enforces `ExecutionOptions.state_max_bytes` after fit and before transform validation actions. Direct node calls validate state structure but leave wire byte limits to explicit encode/decode callers. The codec does not automatically -package a FeatureEngineer pipeline. Native StandardScaler and worker model -loading come later. Codec tests also run without starting a JVM. +package a FeatureEngineer pipeline. Full pipeline state export/import and worker +model loading come later. Codec tests also run without starting a JVM. ### Inspecting declared support @@ -368,13 +444,16 @@ A capability check distinguishes fit and apply and never falls back to pandas: from skyulf.core.capabilities import UnsupportedExecutionError, require_capability require_capability("SimpleImputer", "fit", "spark", config={"strategy": "mean"}) +require_capability("StandardScaler", "apply", "spark", config={ + "with_mean": True, "with_std": True, +}) try: require_capability("SimpleImputer", "fit", "spark", config={"strategy": "median"}) except UnsupportedExecutionError as error: print(error.node_type, error.operation, error.engine, error.reason) ``` -Mean succeeds; median reports unsupported. The query requires explicit defaults. +Mean and StandardScaler succeed; median reports unsupported. The query requires explicit defaults. Existing local pipelines continue to work; this new preflight is not yet wired into their execution. A local node without an explicit declaration also fails this new query, even though its existing local pipeline path remains available. @@ -410,7 +489,7 @@ Spark code, certify compatibility or make a window transform batch-independent. use an environment that permits the owned JVM processes to terminate. - **Spark dependency unavailable:** install the optional `skyulf-core[spark]` dependency in a suitable environment, or use the repository requirements above. -- **Unsupported node:** SimpleImputer mean/constant is available. Other built-in +- **Unsupported node:** SimpleImputer mean/constant and StandardScaler are available. Other built-in native FE nodes are still being implemented; installing Spark does not enable them. MLflow tracking, Unity Catalog registration, Databricks jobs, serving endpoints diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index 174ad4953..aaa3e8755 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -223,14 +223,14 @@ FeatureEngineer girişinden de test edilir. **Oluştur:** `tests/spark/test_standard_scaler.py`. **Tüketir/üretir:** Mevcut mean/var/scale/columns/with_mean/with_std artifact'i. -- [ ] Dört with_mean/with_std kombinasyonu, sabit kolon, null/NaN, boş veri, +- [x] Dört with_mean/with_std kombinasyonu, sabit kolon, null/NaN, boş veri, tek satır, büyük offset/küçük varyans ve kolon sırası için parity testleri yaz. -- [ ] Dağıtık population variance ile ddof=0 semantiğini koru. NaN'ın aggregate +- [x] Dağıtık population variance ile ddof=0 semantiğini koru. NaN'ın aggregate davranışını local node'la eşleştir. Spark ML StandardScaler'ı aynı isim diye doğrudan kullanma. O(kolon) sonuç topla; stabil varyans kullan. -- [ ] Apply `(x - mean) / scale` ifadelerini flag'lere göre kur; sıfır scale +- [x] Apply `(x - mean) / scale` ifadelerini flag'lere göre kur; sıfır scale ve gerekli olmayan None state'i mevcut node davranışına göre ele al. -- [ ] Floating tolerance küçük normal fixture'da rtol=1e-10/atol=1e-12; +- [x] Floating tolerance küçük normal fixture'da rtol=1e-10/atol=1e-12; adversarial sayısal fixture'da gerekçeli ayrı tolerance, sonuç farkını gizleme. ```python diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 3458e0a3f..760da289c 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-05 tamamlandı. Sonraki görev: SM-06. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-06 tamamlandı. Sonraki görev: SM-07. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -15,8 +15,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-03 | Dispatcher, schema, row keys | SM-02 | DONE | Keyed Spark FE giriş/preflight; aşağıda kanıt | | SM-04 | Versioned portable state | SM-03 | DONE | Tagged state, limit/version/schema kontrolü; aşağıda kanıt | | SM-05 | Native SimpleImputer | SM-04 | DONE | Mean/constant train-only fit, Spark apply; aşağıda kanıt | -| SM-06 | Native StandardScaler | SM-05 | READY | Population variance ve flag parity | -| SM-07 | Uçtan uca FE kapısı | SM-06 | WAIT | Üç engine çapraz fit/apply; kayıt/yükleme | +| SM-06 | Native StandardScaler | SM-05 | DONE | Population variance, dört flag ve numeric parity; aşağıda kanıt | +| SM-07 | Uçtan uca FE kapısı | SM-06 | READY | Üç engine çapraz fit/apply; kayıt/yükleme | | SM-08 | Ortak inference bundle | SM-07 | WAIT | Raw/features ayrımı; model metadata round-trip | | SM-09 | Native FE + worker model | SM-08 | WAIT | Spark tahmini local ile key bazında aynı | | SM-10 | Worker Python FE + model | SM-09 | WAIT | Batch-safe pipeline; window gibi yollar açık ret | @@ -267,3 +267,56 @@ ve MLflow entegrasyonu henüz yok. → **1 passed**, 27.12 saniye; mevcut pandas fillna FutureWarning. - Sınır: median/mode, StandardScaler native apply, distributed model inference, MLflow ve Databricks/Connect entegrasyon kanıtı henüz yok. Sonraki görev SM-06. + +## SM-06 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `992d13b2`; bu kayıt SM-06 çalışma ağacına aittir. +- `scaling/_spark_standard.py`: native fit/apply, population variance (`ddof=0`), + dört with_mean/with_std kombinasyonu, portable codec v1 capability. Mean/std + seçeneklerine bağlı None alanları mevcut artifact sözlüğüyle uyumlu. +- Fit en fazla iki distributed aggregate sorgusu çalıştırır; her biri tek + O(kolon) istatistik satırı döndürür. İlk sorgu min/max referansları, infinity + ve satır/otomatik seçim kontrolleri; ikinci sorgu referanstan farkların + mean/var_pop/count değerleri. İki flag kapalıysa ikinci sorgu gerekmez. + Sıfırı kapsayan aralık referans 0; diğerlerinde sıfıra yakın uç değer kullanılır. +- Null/NaN fit'te dışlanır. All-missing istatistikler NaN; tek gözlem/sabit + varyans 0 ve scale 1. Near-constant scale için sklearn'in float64 hata sınırı + uygulanır. Seçili infinity/overflow reddedilir; Spark double precision sınırı + ve sayısal tolerance rehberde açık. Decimal/string/nested scaling unsupported. +- Apply native ifadelerle lazy; Python UDF/action/pandas dönüşümü yok. Kolon + adları literal, input kolon sırası korunur; keyed runner key/target'ı doğrular. + Doğrudan apply eksik kolonları local scaler gibi atlar; pipeline mevcut giriş + kolon sözleşmesini korur. Integer/bool seçili kolonlar enabled apply'da double olur. +- `_spark_numeric.py`: imputer ile ortak kolon çözümleme, null/NaN, otomatik + seçim istatistikleri ve case-sensitive isim kontrolü. Mevcut imputer davranışı + regresyon testleriyle korundu; local pandas/Polars uygulaması değiştirilmedi. +- 57 scaler testi: 36 çapraz engine/flag kombinasyonu, held-out veri, column order, + null/NaN, sabit/tek/boş veri, dtype, key/target, lazy plan ve bounded collection. + Normal fixture rtol=1e-10/atol=1e-12; 1e12 offset ve küçük spread fixture'ında + temsil aralığına bağlı rtol=0.002, repartition 1/2/7. +- TDD başlangıcı **33 failed, 16 passed**; ilk scaler+imputer koşusu **85 passed**. + Bağımsız review doğrudan avg'nin büyük sabit kolonda 0 yerine 0.0968 + üretmesini, ardından koşulsuz min-reference'ın mixed-sign küçük katkıyı + kaybetmesini buldu. Her bulgu iki red regresyonla yeniden üretildi; son tam + Spark koşusunda düzeltmeler geçti. Review son recheck'te önemli bulgu kalmadı. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + -q --tb=short -o addopts= -p no:cacheprovider + --basetemp .cache/sm06-spark-full` + → **214 passed, 2 warnings**, 197.25 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm06-core-full` + → **9945 passed, 198 skipped, 1077 warnings**, 186.87 saniye. + Bu koşu 55 yeni scaler runtime testini PySpark olmayan base ortamda skip etti; + sonradan eklenen iki mixed-sign testi dahil tüm 57 vaka üstte gerçek Spark'ta geçti. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Rehberdeki session + kurulumundan sonraki sekiz Python snippet'i aynı gerçek session'da çalıştı: + `.venv-spark/Scripts/python.exe -m pytest .cache/sm06_docs/test_spark_examples.py + -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm06-doc-examples` + → **1 passed**, 32.00 saniye; mevcut pandas fillna FutureWarning. +- Sınır: FeatureEngineer export_state/from_state, tüm zincirin persistence + kapısı ve örnek script SM-07'de. Distributed model inference, MLflow ve + Databricks/Connect entegrasyon doğrulaması henüz yok. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index d931e58b3..67540a2fa 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-05 tamamlandı; sıradaki görev SM-06.** +Tarih: 2026-09-21. Durum: **SM-00–SM-06 tamamlandı; sıradaki görev SM-07.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-06**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-07**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/preprocessing/_spark_numeric.py b/skyulf-core/skyulf/preprocessing/_spark_numeric.py new file mode 100644 index 000000000..1af7b4e74 --- /dev/null +++ b/skyulf-core/skyulf/preprocessing/_spark_numeric.py @@ -0,0 +1,67 @@ +"""Shared native Spark column selection and bounded numeric selection statistics.""" + +from typing import Any + +from ._spark import _column, _resolved_names + +NUMERIC_DTYPES = {"byte", "short", "integer", "long", "float", "double"} + + +def validate_names(frame: Any, extra: tuple | list = ()) -> None: + """Reject ambiguous input and learned names under the session's identifier rules.""" + names = _resolved_names(frame) + if len(set(names)) != len(names): + raise ValueError("Duplicate Spark column names.") + combined = list(dict.fromkeys([*frame.columns, *extra])) + if frame.sparkSession.conf.get("spark.sql.caseSensitive") != "true": + combined = [name.lower() for name in combined] + if len(set(combined)) != len(combined): + raise ValueError("Fitted columns collide under Spark column name resolution.") + + +def select_columns( + frame: Any, config: dict, *, numeric_only: bool +) -> tuple[list[str], dict[str, str], bool]: + """Resolve exact names and automatic schema candidates without a data action.""" + validate_names(frame) + schema = {field.name: field.dataType.typeName() for field in frame.schema.fields} + automatic = config.get("_auto_columns", config.get("columns") is None) + cols = config.get("columns") + if cols is None: + cols = [name for name in frame.columns if name != config.get("target_column")] + if not isinstance(cols, list) or any(not isinstance(name, str) for name in cols): + raise ValueError("columns must be a list of names.") + if len(set(cols)) != len(cols) or set(cols).difference(schema): + raise ValueError("Spark feature columns are missing or duplicated.") + if automatic and numeric_only: + cols = [name for name in cols if schema[name] in NUMERIC_DTYPES] + return cols, schema, automatic + + +def missing(frame: Any, name: str, dtype: str, functions: Any) -> Any: + """Treat nulls and floating NaNs as missing using native expressions.""" + column = _column(frame, name) + return ( + column.isNull() | functions.isnan(column) + if dtype in {"float", "double"} + else column.isNull() + ) + + +def selection_statistics(valid: Any, index: int, functions: Any) -> list[Any]: + """Mirror local binary/constant exclusion without returning distinct values.""" + numeric = valid.cast("double") + binary = (functions.abs(numeric) <= 1e-8) | (functions.abs(numeric - 1) <= 1.001e-5) + return [ + functions.min(valid).alias(f"lo{index}"), + functions.max(valid).alias(f"hi{index}"), + functions.count_distinct(valid).alias(f"distinct{index}"), + functions.max(functions.when(~binary, 1).otherwise(0)).alias(f"other{index}"), + ] + + +def excluded(stats: Any, index: int) -> bool: + """Identify empty, constant or at-most-two-value binary automatic candidates.""" + return stats[f"lo{index}"] == stats[f"hi{index}"] or ( + stats[f"distinct{index}"] <= 2 and not stats[f"other{index}"] + ) diff --git a/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py b/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py index 750d7cc8b..bdb082229 100644 --- a/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py +++ b/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py @@ -6,40 +6,20 @@ from ...core.capabilities import require_capability from ...core.portable_state import validate_state -from .._spark import _column, _resolved_names - -_NUMERIC = {"byte", "short", "integer", "long", "float", "double"} -_FLOATING = {"float", "double"} - - -def _missing(frame: Any, name: str, dtype: str, functions: Any) -> Any: - """Treat both nulls and floating NaNs as missing using native expressions.""" - column = _column(frame, name) - return column.isNull() | functions.isnan(column) if dtype in _FLOATING else column.isNull() - - -def _columns(frame: Any, config: dict, strategy: str) -> tuple[list[str], dict[str, str], bool]: - """Resolve exact names and schema-eligible candidates without a data action.""" - names = _resolved_names(frame) - if len(set(names)) != len(names): - raise ValueError("Duplicate Spark column names.") - schema = {field.name: field.dataType.typeName() for field in frame.schema.fields} - automatic = config.get("_auto_columns", config.get("columns") is None) - cols = config.get("columns") - if cols is None: - cols = [name for name in frame.columns if name != config.get("target_column")] - if not isinstance(cols, list) or any(not isinstance(name, str) for name in cols): - raise ValueError("columns must be a list of names.") - if len(set(cols)) != len(cols) or set(cols).difference(schema): - raise ValueError("Spark imputer columns are missing or duplicated.") - if automatic and strategy == "mean": - cols = [name for name in cols if schema[name] in _NUMERIC] - return cols, schema, automatic +from .._spark import _column +from .._spark_numeric import ( + NUMERIC_DTYPES, + excluded, + missing, + select_columns, + selection_statistics, + validate_names, +) def _constant(value: Any, dtype: str) -> Any: """Require unambiguous scalar constants, preserving integer precision.""" - if dtype in _NUMERIC: + if dtype in NUMERIC_DTYPES: value = 0 if value is None else value if type(value) not in (int, float): raise TypeError("Numeric Spark columns require a numeric fill_value.") @@ -62,40 +42,26 @@ def _aggregate_expressions( """Combine missing counts, means and optional selection statistics in one query.""" expressions = [] for index, name in enumerate(cols): - missing = _missing(frame, name, schema[name], functions) - expressions.append( - functions.sum(functions.when(missing, 1).otherwise(0)).alias(f"n{index}") - ) + absent = missing(frame, name, schema[name], functions) + expressions.append(functions.sum(functions.when(absent, 1).otherwise(0)).alias(f"n{index}")) if strategy == "mean": - valid = functions.when(~missing, _column(frame, name)) + valid = functions.when(~absent, _column(frame, name)) expressions.append(functions.avg(valid).alias(f"v{index}")) if automatic: - expressions.extend(_selection_statistics(valid, index, functions)) + expressions.extend(selection_statistics(valid, index, functions)) return expressions -def _selection_statistics(valid: Any, index: int, functions: Any) -> list[Any]: - """Mirror local binary/constant exclusion without collecting distinct values.""" - numeric = valid.cast("double") - binary = (functions.abs(numeric) <= 1e-8) | (functions.abs(numeric - 1) <= 1.001e-5) - return [ - functions.min(valid).alias(f"lo{index}"), - functions.max(valid).alias(f"hi{index}"), - functions.count_distinct(valid).alias(f"distinct{index}"), - functions.max(functions.when(~binary, 1).otherwise(0)).alias(f"other{index}"), - ] - - def fit_spark_imputer(frame: Any, target: Any, config: dict) -> dict: """Learn native mean/constant state, returning only one aggregate row to Python.""" strategy = config.get("strategy", "mean") require_capability("SimpleImputer", "fit", "spark", config={**config, "strategy": strategy}) - cols, schema, automatic = _columns(frame, config, strategy) + cols, schema, automatic = select_columns(frame, config, numeric_only=strategy == "mean") if not cols: return {} constants = {} for name in cols: - if strategy == "mean" and schema[name] not in _NUMERIC: + if strategy == "mean" and schema[name] not in NUMERIC_DTYPES: raise TypeError("Spark mean imputation requires numeric columns.") if strategy == "constant": constants[name] = _constant(config.get("fill_value"), schema[name]) @@ -114,14 +80,7 @@ def _artifact(cols: list[str], strategy: str, automatic: bool, stats: Any, const value = constants[name] if strategy == "constant" else stats[f"v{index}"] if strategy == "mean" and value is not None and not math.isfinite(value): raise ValueError("Spark mean imputation requires finite observed values.") - if ( - strategy == "mean" - and automatic - and ( - stats[f"lo{index}"] == stats[f"hi{index}"] - or (stats[f"distinct{index}"] <= 2 and not stats[f"other{index}"]) - ) - ): + if strategy == "mean" and automatic and excluded(stats, index): continue fills[name] = value counts[name] = int(stats[f"n{index}"] or 0) @@ -143,14 +102,7 @@ def apply_spark_imputer(frame: Any, target: Any, params: dict) -> tuple[Any, Any return frame, target require_capability("SimpleImputer", "apply", "spark", config=params) state = validate_state("SimpleImputer", params) - names = _resolved_names(frame) - if len(set(names)) != len(names): - raise ValueError("Duplicate Spark column names.") - combined = list(dict.fromkeys([*frame.columns, *state["columns"]])) - if frame.sparkSession.conf.get("spark.sql.caseSensitive") != "true": - combined = [name.lower() for name in combined] - if len(set(combined)) != len(combined): - raise ValueError("Fitted columns collide under Spark column name resolution.") + validate_names(frame, state["columns"]) functions = importlib.import_module("pyspark.sql.functions") schema = {field.name: field.dataType.typeName() for field in frame.schema.fields} expressions = {name: _column(frame, name) for name in frame.columns} @@ -163,9 +115,9 @@ def apply_spark_imputer(frame: Any, target: Any, params: dict) -> tuple[Any, Any replacement = functions.lit(value) if name in schema: _constant(value, schema[name]) - if state["strategy"] == "mean" and schema[name] not in _NUMERIC: + if state["strategy"] == "mean" and schema[name] not in NUMERIC_DTYPES: raise TypeError("Spark mean imputation requires numeric columns.") - missing = _missing(frame, name, schema[name], functions) - replacement = functions.when(missing, replacement).otherwise(_column(frame, name)) + absent = missing(frame, name, schema[name], functions) + replacement = functions.when(absent, replacement).otherwise(_column(frame, name)) expressions[name] = replacement.alias(name) return frame.select(*expressions.values()), target diff --git a/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py b/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py new file mode 100644 index 000000000..e4a8bad5e --- /dev/null +++ b/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py @@ -0,0 +1,163 @@ +"""Native Spark StandardScaler with population variance and bounded learned state.""" + +import importlib +import math +import sys +from typing import Any + +from ...core.capabilities import require_capability +from ...core.portable_state import validate_state +from .._spark import _column +from .._spark_numeric import ( + NUMERIC_DTYPES, + excluded, + missing, + select_columns, + selection_statistics, + validate_names, +) + + +def fit_spark_standard(frame: Any, target: Any, config: dict) -> dict: + """Learn shifted statistics from bounded aggregates without materializing samples.""" + flags = {key: config.get(key, True) for key in ("with_mean", "with_std")} + require_capability("StandardScaler", "fit", "spark", config=flags) + cols, schema, automatic = select_columns(frame, config, numeric_only=True) + if not cols: + return {} + for name in cols: + _validate_dtype(schema[name]) + functions = importlib.import_module("pyspark.sql.functions") + expressions = [functions.count(functions.lit(1)).alias("rows")] + for index, name in enumerate(cols): + valid = functions.when(~missing(frame, name, schema[name], functions), _column(frame, name)) + numeric = valid.cast("double") + expressions.extend( + [ + functions.min(numeric).alias(f"min{index}"), + functions.max(numeric).alias(f"max{index}"), + functions.max( + functions.when(functions.abs(numeric) == float("inf"), 1).otherwise(0) + ).alias(f"inf{index}"), + ] + ) + if automatic: + expressions.extend(selection_statistics(valid, index, functions)) + references = frame.agg(*expressions).first() + selected = [i for i in range(len(cols)) if not automatic or not excluded(references, i)] + if not selected: + return {} + if not references["rows"]: + raise ValueError("Cannot fit StandardScaler on empty training data.") + if any(references[f"inf{index}"] for index in selected): + raise ValueError("Spark StandardScaler requires finite training values; infinity found.") + expressions = [] + if flags["with_mean"] or flags["with_std"]: + for index in selected: + name = cols[index] + valid = functions.when( + ~missing(frame, name, schema[name], functions), _column(frame, name) + ) + shifted = valid.cast("double") - _reference(references, index) + expressions.extend(_statistics(shifted, index, flags, functions)) + stats = frame.agg(*expressions).first() if expressions else None + return _artifact(cols, selected, references, stats, flags) + + +def _validate_dtype(dtype: str) -> None: + """Allow primitive numbers and explicitly selected booleans without string parsing.""" + if dtype not in NUMERIC_DTYPES | {"boolean"}: + raise TypeError("Spark StandardScaler requires numeric columns or explicit booleans.") + + +def _reference(stats: Any, index: int) -> float: + """Shift same-sign offsets toward zero without erasing mixed-sign small values.""" + lower, upper = stats[f"min{index}"], stats[f"max{index}"] + if lower is None or lower <= 0 <= upper: + return 0.0 + return lower if lower > 0 else upper + + +def _statistics(shifted: Any, index: int, flags: dict, functions: Any) -> list[Any]: + """Aggregate deviations so repeated large offsets do not accumulate rounding error.""" + result = [functions.avg(shifted).alias(f"mean{index}")] + if flags["with_std"]: + result.extend( + [ + functions.var_pop(shifted).alias(f"var{index}"), + functions.count(shifted).alias(f"n{index}"), + ] + ) + return result + + +def _artifact( + cols: list[str], selected: list[int], references: Any, stats: Any, flags: dict +) -> dict: + """Keep local flag-dependent None statistics and NaN all-missing statistics.""" + means = [] if flags["with_mean"] or flags["with_std"] else None + variances = [] if flags["with_std"] else None + scales = [] if flags["with_std"] else None + for index in selected: + mean = ( + _statistic(stats[f"mean{index}"]) + _reference(references, index) + if means is not None + else None + ) + if means is not None: + means.append(mean) + if variances is not None and scales is not None: + assert mean is not None + variance = _statistic(stats[f"var{index}"]) + variances.append(variance) + scales.append(_scale(variance, mean, stats[f"n{index}"])) + return { + "type": "standard_scaler", + "columns": [cols[index] for index in selected], + "mean": means, + "var": variances, + "scale": scales, + **flags, + } + + +def _statistic(value: Any) -> float: + """Represent missing statistics as NaN and reject overflowing aggregates.""" + if value is None: + return float("nan") + if not math.isfinite(value): + raise ValueError("Spark StandardScaler aggregate is non-finite; rescale training values.") + return float(value) + + +def _scale(variance: float, mean: float, count: int) -> float: + """Match sklearn's float64 constant-feature error bound using observed counts.""" + epsilon = sys.float_info.epsilon + error = count * mean * epsilon + upper_bound = count * epsilon * variance + error * error + return 1.0 if variance <= upper_bound else math.sqrt(variance) + + +def apply_spark_standard(frame: Any, target: Any, params: dict) -> tuple[Any, Any]: + """Apply learned statistics with literal native expressions and no data actions.""" + if not params: + return frame, target + state = validate_state("StandardScaler", params) + require_capability("StandardScaler", "apply", "spark", config=state) + validate_names(frame, state["columns"]) + if not (state["with_mean"] or state["with_std"]): + return frame, target + schema = {field.name: field.dataType.typeName() for field in frame.schema.fields} + expressions = {name: _column(frame, name) for name in frame.columns} + for index, name in enumerate(state["columns"]): + if name not in schema: + continue + _validate_dtype(schema[name]) + expr = _column(frame, name).cast("double") + if state["with_mean"]: + expr = expr - state["mean"][index] + if state["with_std"]: + scale = state["scale"][index] + expr = expr / (scale if scale != 0 else 1.0) + expressions[name] = expr.alias(name) + return frame.select(*expressions.values()), target diff --git a/skyulf-core/skyulf/preprocessing/scaling/standard.py b/skyulf-core/skyulf/preprocessing/scaling/standard.py index 565985325..7f954320a 100644 --- a/skyulf-core/skyulf/preprocessing/scaling/standard.py +++ b/skyulf-core/skyulf/preprocessing/scaling/standard.py @@ -7,6 +7,7 @@ import polars as pl from sklearn.preprocessing import StandardScaler +from ...core.capabilities import ExecutionCapability from ...core.meta.decorators import node_meta from ...engines.sklearn_bridge import SklearnBridge from ...registry import NodeRegistry @@ -22,6 +23,7 @@ from ..base import BaseApplier, BaseCalculator, apply_method, fit_method from ..dispatcher import apply_dual_engine, fit_dual_engine from ._common import _select_subset_pandas, _select_subset_polars +from ._spark_standard import apply_spark_standard, fit_spark_standard logger = logging.getLogger(__name__) @@ -49,13 +51,21 @@ class StandardScalerApplier(BaseApplier): Honors ``with_mean``/``with_std``; ``X`` passes through unchanged when the enabled flags have no fitted statistics, and ``y`` is never modified. + Spark validates portable state and applies native expressions without a + data action. Its selected numeric columns become double when scaling is enabled. """ @apply_method def apply(self, X: Any, _y: Any, params: dict[str, Any]) -> Any: # pylint: disable=arguments-differ """Center and scale ``X`` with the fitted statistics on the active engine.""" return apply_dual_engine( - X, params, {"polars": self._apply_polars, "pandas": self._apply_pandas} + X, + params, + { + "polars": self._apply_polars, + "pandas": self._apply_pandas, + "spark": apply_spark_standard, + }, ) @staticmethod @@ -111,7 +121,24 @@ def _apply_pandas(X: Any, _y: Any, params: dict[str, Any]) -> tuple[Any, Any]: return X_out, _y -@NodeRegistry.register("StandardScaler", StandardScalerApplier) +@NodeRegistry.register( + "StandardScaler", + StandardScalerApplier, + execution_capabilities=tuple( + ExecutionCapability( + "spark", + operation, + "native", + "preserve", + "global" if operation == "fit" else "row", + codec_version=1, + config_match=(("with_mean", with_mean), ("with_std", with_std)), + ) + for operation in ("fit", "apply") + for with_mean in (True, False) + for with_std in (True, False) + ), +) @node_meta( id="StandardScaler", name="Standard Scaler", @@ -121,7 +148,13 @@ def _apply_pandas(X: Any, _y: Any, params: dict[str, Any]) -> tuple[Any, Any]: learns_from_data=True, ) class StandardScalerCalculator(BaseCalculator): - """Fit per-column mean/scale statistics with sklearn's ``StandardScaler``.""" + """Fit per-column statistics using sklearn locally or native Spark aggregates. + + Spark uses population variance (``ddof=0``), ignores null/NaN observations, + and returns at most two statistics rows to the driver. Both options default + to True. Empty explicit training selections produce a no-op artifact; + selected features with zero training rows cannot be fitted. + """ def infer_output_schema( self, input_schema: SkyulfSchema, config: dict[str, Any] @@ -138,7 +171,15 @@ def fit(self, X: Any, _y: Any, config: dict[str, Any]) -> StandardScalerArtifact return cast(StandardScalerArtifact, {}) return cast( StandardScalerArtifact, - fit_dual_engine(X, config, {"polars": self._fit_polars, "pandas": self._fit_pandas}), + fit_dual_engine( + X, + config, + { + "polars": self._fit_polars, + "pandas": self._fit_pandas, + "spark": fit_spark_standard, + }, + ), ) @staticmethod diff --git a/skyulf-core/tests/spark/test_standard_scaler.py b/skyulf-core/tests/spark/test_standard_scaler.py new file mode 100644 index 000000000..518e799c2 --- /dev/null +++ b/skyulf-core/tests/spark/test_standard_scaler.py @@ -0,0 +1,262 @@ +"""Native scaling must preserve learned statistics and distributed execution.""" + +import math + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.core.portable_state import decode_state, encode_state +from skyulf.preprocessing.pipeline import FeatureEngineer +from skyulf.preprocessing.scaling.standard import StandardScalerApplier, StandardScalerCalculator + + +@pytest.mark.parametrize("fit_engine", ["pandas", "polars", "spark"]) +@pytest.mark.parametrize("apply_engine", ["pandas", "polars", "spark"]) +@pytest.mark.parametrize( + "with_mean,with_std", [(True, True), (True, False), (False, True), (False, False)] +) +def test_cross_engine_flags_population_variance_and_order( + spark, fit_engine, apply_engine, with_mean, with_std +): + """Sample variance, relearning or positional column mapping would change held-out outputs.""" + local = pd.DataFrame({"x": [1.0, 3.0, np.nan], "z": [10.0, 14.0, np.nan]}) + train = { + "pandas": lambda: local, + "polars": lambda: pl.from_pandas(local), + "spark": lambda: spark.createDataFrame( + [(1.0, 10.0), (3.0, 14.0), (None, None)], "x double, z double" + ), + }[fit_engine]() + state = StandardScalerCalculator().fit( + train, {"columns": ["z", "x"], "with_mean": with_mean, "with_std": with_std} + ) + _, state = decode_state(encode_state("StandardScaler", state, max_bytes=8192)) + assert state["columns"] == ["z", "x"] + assert state["mean"] == ([12.0, 2.0] if with_mean or with_std else None) + assert state["var"] == ([4.0, 1.0] if with_std else None) + assert state["scale"] == ([2.0, 1.0] if with_std else None) + held = pd.DataFrame({"id": [20, 10], "x": [100.0, np.nan], "z": [20.0, np.nan]}) + batch = { + "pandas": lambda: held, + "polars": lambda: pl.from_pandas(held), + "spark": lambda: spark.createDataFrame( + [(20, 100.0, 20.0), (10, None, None)], "id long, x double, z double" + ).repartition(2), + }[apply_engine]() + output = StandardScalerApplier().apply(batch, state) + records = { + "pandas": lambda: output.to_dict("records"), + "polars": lambda: output.to_dicts(), + "spark": lambda: [row.asDict() for row in output.collect()], + }[apply_engine]() + rows = {row["id"]: row for row in records} + expected = { + (True, True): [98.0, 4.0], + (True, False): [98.0, 8.0], + (False, True): [100.0, 10.0], + (False, False): [100.0, 20.0], + }[(with_mean, with_std)] + np.testing.assert_allclose([rows[20]["x"], rows[20]["z"]], expected, rtol=1e-10, atol=1e-12) + assert pd.isna(rows[10]["x"]) and pd.isna(rows[10]["z"]) + assert list(output.columns) == ["id", "x", "z"] + + +def test_null_nan_constant_and_single_observation(spark): + """Missing values are ignored for learning; zero variance uses unit scale.""" + train = spark.createDataFrame( + [ + (1.0, 5.0, None, 7.0), + (3.0, 5.0, None, None), + (None, 5.0, None, None), + (float("nan"), None, None, None), + ], + "x double, constant double, empty double, single double", + ) + state = StandardScalerCalculator().fit(train, {"columns": train.columns}) + assert state["mean"] is not None and state["var"] is not None and state["scale"] is not None + np.testing.assert_allclose(state["mean"], [2, 5, np.nan, 7], equal_nan=True) + np.testing.assert_allclose(state["var"], [1, 0, np.nan, 0], equal_nan=True) + np.testing.assert_allclose(state["scale"], [1, 1, np.nan, 1], equal_nan=True) + batch = spark.createDataFrame([(3.0, 10.0, 4.0, 8.0)], train.schema) + row = StandardScalerApplier().apply(batch, state).first() + assert [row.x, row.constant, row.single] == [1.0, 5.0, 1.0] + assert math.isnan(row.empty) + + +@pytest.mark.parametrize("partitions", [1, 2, 7]) +def test_large_offset_small_variance(spark, partitions): + """Stable distributed variance must retain spread hidden by E[x*x] - E[x]**2.""" + values = [1e12 + offset for offset in (0.0, 0.125, 0.25, 0.375)] + frame = spark.createDataFrame([(value,) for value in values], "x double").repartition( + partitions + ) + state = StandardScalerCalculator().fit(frame, {"columns": ["x"]}) + # Double rounding at this offset is about 1e-4, appreciable versus a 0.14 std. + assert state["var"] == pytest.approx([0.01953125], rel=0.002, abs=1e-12) + reference = StandardScalerCalculator().fit(pd.DataFrame({"x": values}), {"columns": ["x"]}) + held = spark.createDataFrame([(1e12 + 0.5,)], "x double") + actual = StandardScalerApplier().apply(held, state).first().x + expected = ( + StandardScalerApplier().apply(pd.DataFrame({"x": [1e12 + 0.5]}), reference).iloc[0, 0] + ) + assert actual == pytest.approx(expected, rel=0.002, abs=1e-12) + + +def test_near_constant_uses_sklearn_error_bound(spark): + """Almost constant high-offset features must not be amplified by tiny scales.""" + values = [1e12, 1e12 + 0.0001220703125] + state = StandardScalerCalculator().fit( + spark.createDataFrame([(v,) for v in values], "x double"), {"columns": ["x"]} + ) + assert state["var"] is not None and state["var"][0] > 0 + assert state["scale"] == [1.0] + + +@pytest.mark.parametrize("with_std", [True, False]) +def test_large_constant_mean_does_not_accumulate_roundoff(spark, with_std): + """Summation error must not turn a constant training feature into a nonzero output.""" + value = 1e12 + 0.125 + frame = spark.range(10000, numPartitions=2).selectExpr("1000000000000.125D AS x") + state = StandardScalerCalculator().fit(frame, {"columns": ["x"], "with_std": with_std}) + assert state["mean"] == [value] + assert StandardScalerApplier().apply(frame, state).first().x == 0.0 + + +@pytest.mark.parametrize("large,small", [(1e16, 1.0), (1e8, 1e-8)]) +def test_mixed_sign_mean_does_not_lose_small_observations(spark, large, small): + """Reference shifting must not discard near-zero values in a mixed-sign distribution.""" + frame = spark.createDataFrame([(-large,), (large,), (small,)], "x double").coalesce(1) + state = StandardScalerCalculator().fit(frame, {"columns": ["x"], "with_std": False}) + assert state["mean"] == pytest.approx([small / 3], rel=1e-10, abs=1e-20) + held = spark.createDataFrame([(small,)], "x double") + assert StandardScalerApplier().apply(held, state).first().x == pytest.approx(2 * small / 3) + + +def test_explicit_empty_training_fails_but_empty_selection_is_noop(spark): + """Zero rows cannot produce fitted statistics; explicit deselection remains valid.""" + frame = spark.createDataFrame([], "x double") + with pytest.raises(ValueError, match="empty|0 sample"): + StandardScalerCalculator().fit(frame, {"columns": ["x"]}) + assert StandardScalerCalculator().fit(frame, {"columns": []}) == {} + + +def test_native_apply_is_lazy_quotes_names_and_guards_zero_scale(spark, monkeypatch, capsys): + """Literal names and zero scales must work without actions or Python UDFs.""" + frame = spark.createDataFrame([(4, 9.0)], "`a.b` long, `a``b` double") + state = { + "type": "standard_scaler", + "columns": ["a`b", "a.b"], + "mean": [1.0, 2.0], + "var": [0.0, 0.0], + "scale": [0.0, 0.0], + "with_mean": True, + "with_std": True, + } + + def forbidden(*args, **kwargs): + """Any action during plan construction would violate lazy native apply.""" + pytest.fail("Action in native apply") + + with monkeypatch.context() as patch: + for name in ("collect", "count", "first", "toPandas", "toArrow"): + patch.setattr(type(frame), name, forbidden) + output = StandardScalerApplier().apply(frame, state) + output.explain(extended=True) + plan = capsys.readouterr().out + assert not any(name in plan for name in ("PythonUDF", "BatchEvalPython", "ArrowEvalPython")) + assert tuple(output.first()) == (2.0, 8.0) + + +def test_pipeline_auto_selection_and_protected_columns(spark): + """Automatic scaling must exclude keys, target, strings, binary and constant features.""" + data = spark.createDataFrame( + [(1, 2.0, 1.0, 5.0, "a", 10.0), (2, 4.0, 0.0, 5.0, "b", 20.0)], + "id long, x double, binary double, fixed double, text string, label double", + ) + engineer = FeatureEngineer( + [{"name": "scale", "transformer": "StandardScaler"}], + frame_spec=FrameSpec(("id",), "label"), + execution_options=ExecutionOptions("spark"), + ) + output, _ = engineer.fit_transform(data.repartition(2)) + assert engineer.fitted_steps[0]["artifact"]["columns"] == ["x"] + assert [tuple(row) for row in output.orderBy("id").collect()] == [ + (1, -1.0, 1.0, 5.0, "a", 10.0), + (2, 1.0, 0.0, 5.0, "b", 20.0), + ] + assert engineer.transform(data.drop("label")).columns == data.columns[:-1] + + +@pytest.mark.parametrize("value", [float("inf"), -float("inf")]) +@pytest.mark.parametrize("flags", [(True, True), (False, False)]) +def test_infinite_training_rejected(spark, value, flags): + """Disabled centering/scaling must not hide invalid training observations.""" + frame = spark.createDataFrame([(1.0,), (value,)], "x double") + with pytest.raises(ValueError, match="finite|infinity"): + StandardScalerCalculator().fit( + frame, {"columns": ["x"], "with_mean": flags[0], "with_std": flags[1]} + ) + + +def test_invalid_dtype_fails_before_action(spark, monkeypatch): + """String parsing must not silently enter a numeric Spark scaling pipeline.""" + frame = spark.createDataFrame([("1",), ("3",)], "x string") + + def forbidden(*args, **kwargs): + """No distributed work should precede schema rejection.""" + pytest.fail("Action before dtype rejection") + + monkeypatch.setattr(type(frame), "first", forbidden) + with pytest.raises(TypeError, match="numeric"): + StandardScalerCalculator().fit(frame, {"columns": ["x"]}) + + +def test_fit_collects_only_bounded_statistics(spark, monkeypatch): + """Learning must aggregate in Spark and transfer O(columns) state instead of input rows.""" + frame = spark.range(10000).selectExpr("CAST(id AS DOUBLE) AS x", "CAST(id + 5 AS DOUBLE) AS z") + original_first = type(frame).first + shapes = [] + + def record_first(aggregate): + """Observe the materialization boundary without replacing Spark computation.""" + row = original_first(aggregate) + shapes.append(len(row)) + return row + + def forbidden(*args, **kwargs): + """Direct local conversion must never occur inside fitting.""" + pytest.fail("Local conversion during native fit") + + with monkeypatch.context() as patch: + patch.setattr(type(frame), "first", record_first) + patch.setattr(type(frame), "toPandas", forbidden) + patch.setattr(type(frame), "toArrow", forbidden) + state = StandardScalerCalculator().fit(frame, {"columns": ["x", "z"]}) + assert len(shapes) == 2 and all(width <= 10 for width in shapes) + assert state["mean"] == [4999.5, 5004.5] + assert state["var"] == pytest.approx([8333333.25, 8333333.25], rel=1e-10, abs=1e-12) + + +def test_single_row_and_explicit_boolean(spark): + """Explicit booleans and one-observation features follow local numeric scaling.""" + frame = spark.createDataFrame([(True, 7)], "flag boolean, x long") + state = StandardScalerCalculator().fit(frame, {"columns": ["x", "flag"]}) + assert state["mean"] == [7.0, 1.0] + assert state["scale"] == [1.0, 1.0] + assert tuple(StandardScalerApplier().apply(frame, state).first()) == (0.0, 0.0) + + +@pytest.mark.parametrize("columns", [["x", "x"], ["x", "X"]]) +def test_ambiguous_input_names_fail_before_actions(spark, columns): + """Spark identifier resolution must not silently select or drop the wrong feature.""" + previous = spark.conf.get("spark.sql.caseSensitive") + spark.conf.set("spark.sql.caseSensitive", "false") + try: + frame = spark.createDataFrame([(1.0, 3.0)], columns) + with pytest.raises(ValueError, match="Duplicate"): + StandardScalerCalculator().fit(frame, {"columns": ["x"]}) + finally: + spark.conf.set("spark.sql.caseSensitive", previous) From 7099733c2d00cc9be5f8bba0d3acefac2b0018ec Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 22:22:09 +0300 Subject: [PATCH 09/85] feat(core): add portable feature pipeline export and restore Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 11 +- docs/user_guide/spark.md | 96 ++++++- .../spark_and_mlflow/01-core-spark-plan.md | 12 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 60 ++++- initiatives/spark_and_mlflow/README.md | 4 +- initiatives/spark_and_mlflow/VALIDATION.md | 4 +- .../examples/spark_feature_engineering.py | 80 ++++++ skyulf-core/skyulf/core/portable_pipeline.py | 114 +++++++++ skyulf-core/skyulf/core/portable_state.py | 36 +-- skyulf-core/skyulf/pipeline/_pipeline.py | 2 + .../skyulf/preprocessing/_feature_state.py | 58 +++++ skyulf-core/skyulf/preprocessing/pipeline.py | 39 +++ .../tests/spark/test_feature_pipeline.py | 171 +++++++++++++ .../tests/spark/test_portable_state.py | 4 +- skyulf-core/tests/unit/test_feature_state.py | 237 ++++++++++++++++++ 15 files changed, 898 insertions(+), 30 deletions(-) create mode 100644 skyulf-core/examples/spark_feature_engineering.py create mode 100644 skyulf-core/skyulf/core/portable_pipeline.py create mode 100644 skyulf-core/skyulf/preprocessing/_feature_state.py create mode 100644 skyulf-core/tests/spark/test_feature_pipeline.py create mode 100644 skyulf-core/tests/unit/test_feature_state.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index f135f4cf5..fd1f0f60a 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -57,10 +57,17 @@ execution and MLflow adapters remain under development. empty and single-row inputs have explicit tested behavior. Numeric selection and name validation are shared with the native imputer. +- Portable `FeatureEngineer.export_state()` / `from_state()` for ordered imputer + and StandardScaler chains. Versioned JSON freezes learned column selection, + validates the total byte budget and rebinds caller-supplied Spark keys/runtime. + Full-chain tests cover all nine pandas/Polars/Spark fit/apply combinations, + persistence, repartitioning and bounded driver collection. A runnable Spark + example and guide demonstrate saving and loading the fitted chain. Successful + tuned pipelines can export their supported FE; failed model fits invalidate it. + ### Planned scope — not yet available -- Full feature-pipeline state export/import, further native Spark nodes and - broader cross-engine fit/apply coverage. +- Further native Spark nodes and broader portable-state coverage. - Distributed Python inference: native Spark preprocessing followed by Python prediction, or a compatible Python preprocessing/model pipeline on workers. - Optional MLflow tracking/model packaging and Unity Catalog model resolution. diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 88fd549d3..58903b4d1 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -4,6 +4,7 @@ Spark support is under development for 0.9.0. The optional dependency and runtime tests, Spark engine adapter and keyed FeatureEngineer entry point are available in the development checkout. **Native SimpleImputer (mean/constant) and StandardScaler support fit and apply.** +Their fitted pipeline can be exported and restored across pandas, Polars and Spark. Other built-in native nodes and distributed model inference remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. @@ -432,9 +433,98 @@ no filesystem or network I/O. Callers own storage and transport of these bytes. The Spark runner validates each declared v1 artifact through the codec and enforces `ExecutionOptions.state_max_bytes` after fit and before transform validation actions. Direct node calls validate state structure but leave wire -byte limits to explicit encode/decode callers. The codec does not automatically -package a FeatureEngineer pipeline. Full pipeline state export/import and worker -model loading come later. Codec tests also run without starting a JVM. +byte limits to explicit encode/decode callers. Use the FeatureEngineer methods +below to package an ordered pipeline. Worker model loading remains a later stage. +Codec tests also run without starting a JVM. + +## Save and restore a fitted feature pipeline + +`FeatureEngineer.export_state()` returns bytes for the complete supported FE +chain. `FeatureEngineer.from_state(...)` validates those bytes and restores the +learned transformations without fitting. Both methods work without Spark installed +when the destination is local. With a caller-owned `spark` session: + +```python +import math +import pandas as pd + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.preprocessing.pipeline import FeatureEngineer + +engineer = FeatureEngineer([ + {"name": "fill", "transformer": "SimpleImputer", + "params": {"columns": ["amount"], "strategy": "mean"}}, + {"name": "scale", "transformer": "StandardScaler", + "params": {"columns": ["amount"]}}, +]) +engineer.fit_transform(pd.DataFrame({"amount": [1.0, None, 3.0]})) +payload = engineer.export_state() +# Application code may persist these bytes with Path(...).write_bytes(payload). +restored = FeatureEngineer.from_state( + payload, + frame_spec=FrameSpec(row_keys=("customer_id",)), + execution_options=ExecutionOptions(engine="spark"), +) +batch = spark.createDataFrame( + [(20, 3.0), (10, 1.0), (30, None)], "customer_id long, amount double", +) +output = restored.transform(batch.repartition(7)) +# Collect only this three-row example; a production caller can write output as a table. +actual = {row.customer_id: row.amount for row in output.collect()} +expected = {10: -math.sqrt(1.5), 20: math.sqrt(1.5), 30: 0.0} +assert actual.keys() == expected.keys() +assert all(math.isclose(actual[key], value, abs_tol=1e-12) + for key, value in expected.items()) +assert restored.export_state() == payload +``` + +For pandas or Polars apply, omit `frame_spec` and either omit `execution_options` +or select that local engine explicitly. For Spark fit, pass `FrameSpec` and +`ExecutionOptions("spark")` to the initial FeatureEngineer as in the native +examples above. The training engine does not lock the saved rules to that engine. +Only learned parameters move; Spark apply keeps the batch distributed. + +The envelope retains step order, names, resolved configuration and each node's +validated state. Learned column selection is frozen, including selections originally +made automatically. Restoring and then refitting uses these explicit columns; +create a new FeatureEngineer from the original configuration to rediscover features. +Statistics follow the saved column names/order; transforms retain input column order. +Match output rows by keys, since Spark does not guarantee physical row order. + +Keys, target declarations and runtime objects are not saved. Spark loading requires +fresh row keys, optionally a target, and explicit execution options. These columns +cannot overlap learned features. Transform validates actual keys and the required +input schema before applying the saved rules. Neither loading nor exporting creates +a session, reads files, contacts a registry or runs a model. + +The current supported chain contains only SimpleImputer `mean`/`constant` and +StandardScaler, including intentionally fitted empty/no-op pipelines. Unsupported +nodes, custom appliers, partial local fits and arbitrary Python objects fail +explicitly. This API exports feature transformations only; it is not a model bundle +or a general replacement for existing pipeline pickle persistence. + +`ExecutionOptions.state_max_bytes` limits the entire pipeline envelope, not only +individual node artifacts. The default is 8 MiB; loading checks received byte length +before parsing. Compact UTF-8 wire encoding and escaped JSON have the same semantic +checksum. Unknown versions, malformed fields, configuration/state disagreement and +checksum mismatches are rejected. The checksum covers step order and configuration; +it detects corruption but does not authenticate a producer. + +The runnable repository example also exercises Spark fit and application-owned +file persistence. From the repository root, with Java configured as above: + +```powershell +.venv-spark/Scripts/python.exe skyulf-core/examples/spark_feature_engineering.py --state-path features.json +``` + +`skyulf-core/examples/spark_feature_engineering.py` owns and closes its local Spark +session. Its `run_example(spark, state_path)` function accepts an existing session. +The automated gate covers all nine fit/apply engine combinations, file round-trips, +repartitioning to 1/2/7 partitions, reversed inputs, repeated apply and a 10,000-row +fixture that rejects unbounded driver collection. Validation currently uses local +PySpark; Databricks/Connect validation is still pending. + +## Capability declarations ### Inspecting declared support diff --git a/initiatives/spark_and_mlflow/01-core-spark-plan.md b/initiatives/spark_and_mlflow/01-core-spark-plan.md index aaa3e8755..9a1dbb289 100644 --- a/initiatives/spark_and_mlflow/01-core-spark-plan.md +++ b/initiatives/spark_and_mlflow/01-core-spark-plan.md @@ -263,13 +263,13 @@ Public state API'si `FeatureEngineer.export_state() -> bytes` ve olarak eklenir. Ordered step config + codec payload dizisi saklanır; keys ve runtime tercihi yeni çağrıdan alınır, SparkSession kaydedilmez. -- [ ] Frame projection ile key/target/feature listesini oluştur; yeni bir node +- [x] Frame projection ile key/target/feature listesini oluştur; yeni bir node tipi gereksizse sırf demo için registry node'u ekleme. -- [ ] Her destekli node için pandas/Polars/Spark fit × üç apply engine'i test et; +- [x] Her destekli node için pandas/Polars/Spark fit × üç apply engine'i test et; sıralı output yerine key join ile karşılaştır. State kaydet/yüklemeyi araya koy. -- [ ] Repartition(1/2/7), ters girdi sırası ve ikinci transform çağrısında +- [x] Repartition(1/2/7), ters girdi sırası ve ikinci transform çağrısında öğrenilmiş state'in değişmemesini doğrula. -- [ ] Baseline local pipeline ve leakage suite'leri + Spark suite çalıştır. +- [x] Baseline local pipeline ve leakage suite'leri + Spark suite çalıştır. Büyük veri testinde input collect yasak, sadece bounded aggregate izinli; terminal test collect'i sınırlı fixture için ayrı işaretlenir. @@ -295,3 +295,7 @@ pandas/Polars fit edilmiş state için de uygulanır. **Komut:** `python -m pytest skyulf-core/tests/spark -q` **Kabul:** G1: çalışan native FE, taşınabilir küçük state, local regresyon yok. Sonraki dilim [inference](02-inference-plan.md); henüz endpoint veya template yok. + +2026-09-21: G1 tamamlandı. Çalışan public API, örnek, runtime ve local test +kanıtları [SM-07 tamamlanma kaydında](OPEN_QUEUE.md). +Gerçek engine-parametrized fixture `tests/spark/test_feature_pipeline.py` içindedir. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 760da289c..526824704 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-06 tamamlandı. Sonraki görev: SM-07. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-00–SM-07 tamamlandı; sıradaki SM-08. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -16,8 +16,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-04 | Versioned portable state | SM-03 | DONE | Tagged state, limit/version/schema kontrolü; aşağıda kanıt | | SM-05 | Native SimpleImputer | SM-04 | DONE | Mean/constant train-only fit, Spark apply; aşağıda kanıt | | SM-06 | Native StandardScaler | SM-05 | DONE | Population variance, dört flag ve numeric parity; aşağıda kanıt | -| SM-07 | Uçtan uca FE kapısı | SM-06 | READY | Üç engine çapraz fit/apply; kayıt/yükleme | -| SM-08 | Ortak inference bundle | SM-07 | WAIT | Raw/features ayrımı; model metadata round-trip | +| SM-07 | Uçtan uca FE kapısı | SM-06 | DONE | Üç engine çapraz fit/apply; kayıt/yükleme; aşağıda kanıt | +| SM-08 | Ortak inference bundle | SM-07 | READY | Raw/features ayrımı; model metadata round-trip | | SM-09 | Native FE + worker model | SM-08 | WAIT | Spark tahmini local ile key bazında aynı | | SM-10 | Worker Python FE + model | SM-09 | WAIT | Batch-safe pipeline; window gibi yollar açık ret | | SM-11 | Classification ve ölçek kapısı | SM-10 | WAIT | Class/proba/threshold parity; worker kanıtı | @@ -320,3 +320,57 @@ ve MLflow entegrasyonu henüz yok. - Sınır: FeatureEngineer export_state/from_state, tüm zincirin persistence kapısı ve örnek script SM-07'de. Distributed model inference, MLflow ve Databricks/Connect entegrasyon doğrulaması henüz yok. + +## SM-07 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `802f60d3`; bu kayıt SM-07 çalışma ağacına aittir. +- Public `FeatureEngineer.export_state() -> bytes` ve `from_state(...)`: + sıralı step isimleri/config'leri ve mevcut node codec envelope'ları tek + versioned JSON paketinde. İlk destek mean/constant imputer ve StandardScaler. + Öğrenilmiş kolon seçimi explicit hale gelir; auto-selection yeniden çalışmaz. + Session/keys/target runtime'dan yeniden alınır; core dosya I/O yapmaz. +- `core/portable_pipeline.py` toplam wire bütçesini parse öncesinde kontrol eder; + step sırası, config ve nested state checksum kapsamındadır. Bilinmeyen + node/version, custom applier, bozuk veya eksik fit state'i açıkça reddedilir. + `_feature_state.py` yalnız bilinen applier'ları kurar; Spark key/target ile + öğrenilmiş feature çakışmasını execution başlamadan reddeder. +- Node ve pipeline wire JSON compact UTF-8; semantic checksum'ın mevcut ASCII + canonical biçimi değişmedi. Unicode kolonlarda re-encoding kaynaklı yanlış + bütçe aşımı giderildi; escaped surrogate isimler eski codec ile uyumlu. +- Başarılı tuning'in adopted FE state'i export edilebilir. Başarısız local/model + refit export'u kapatır; boş pipeline da buna dahildir. Spark'ın başarısız refit'i + önceki başarılı state'i koruma sözleşmesi değişmedi. Legacy pickle ve pipeline + fingerprint hesapları mevcut regresyonlarla korundu. +- `tests/spark/test_feature_pipeline.py`: gerçek üç fit × üç apply engine, + dosyada JSON round-trip, repartition 1/2/7, ters girdi ve tekrar transform. + Key bazlı sonuçlar aynı; train-only learned state değişmez. 10.000 satırlı + imputer→scaler testinde unbounded collect ve local conversion yasak; yalnız + bounded aggregate/validation satırları driver'a döner. Fixture dosya içindedir. +- Bağımsız review Unicode byte limiti ve tuning fitted-state aktarımını buldu. + Gerçek Spark Unicode testi düzeltmeden önce failed, sonra passed. Tuning/model + × boş/scaler dört regresyonu önce failed, sonra passed; exception sonrası boş + pipeline'ın yanlış export edilmesi de düzeltildi. Son review recheck temiz. +- Dar local state/codec/lifecycle koşusu: **101 passed, 28 warnings**, 1.75 saniye. + Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm07-base-full` + → **9969 passed, 223 skipped, 1077 warnings**, 192.35 saniye. Base ortamda + PySpark yok; runtime skip'leri gerçek Spark lane'inden ayrı değerlendirilir. +- `skyulf-core/examples/spark_feature_engineering.py --state-path + .cache/sm07-example-features.json` gerçek PySpark 4.0.3/Java 17 ile çalıştı: + **1949 byte**, üç keyed feature beklenen ±sqrt(1.5)/0; dosya save/load ve + JVM kapanışı başarılı. Rehber kullanım, frozen columns ve runtime sınırlarını açıklar. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm07-spark-full` + → **261 passed, 2 warnings**, 345.28 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Rehberde session + kurulumundan sonraki dokuz Python snippet'i aynı gerçek session'da çalıştı: + `.venv-spark/Scripts/python.exe -m pytest .cache/sm07_docs/test_spark_examples.py + -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm07-doc-examples` + → **1 passed, 1 warning**, 38.00 saniye; mevcut pandas fillna FutureWarning. +- Sınır: G1 feature engineering içindir; model bundle/inference, MLflow, + Databricks/Connect ve endpoint/template doğrulaması değildir. Sonraki görev SM-08. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index 67540a2fa..d0f90bd4f 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-06 tamamlandı; sıradaki görev SM-07.** +Tarih: 2026-09-21. Durum: **SM-00–SM-07 tamamlandı; sıradaki görev SM-08.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-07**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-08**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/initiatives/spark_and_mlflow/VALIDATION.md b/initiatives/spark_and_mlflow/VALIDATION.md index 1377574da..009fb572c 100644 --- a/initiatives/spark_and_mlflow/VALIDATION.md +++ b/initiatives/spark_and_mlflow/VALIDATION.md @@ -74,7 +74,9 @@ veya mkdocs build yapmak gerekmez; doküman linkleri doğrulanır. ## Kapılar -- G1 / SM-07: native FE ve portable state; local API regresyonu yok. +- G1 / SM-07: native FE ve portable state; local API regresyonu yok. **Tamamlandı + (2026-09-21):** 261 Spark lane testi; 9969 local geçti, 223 skip. + [Komutlar ve sınırlar](OPEN_QUEUE.md). - G2 / SM-11: iki inference yolu + classification + worker/ölçek kanıtı. - G3 / SM-14: opsiyonel MLflow model/run/registry; UC gerçek kanıtı G4'te. - G4 / SM-16: gerçek Databricks job + UC load + idempotent Delta batch. diff --git a/skyulf-core/examples/spark_feature_engineering.py b/skyulf-core/examples/spark_feature_engineering.py new file mode 100644 index 000000000..b516930e6 --- /dev/null +++ b/skyulf-core/examples/spark_feature_engineering.py @@ -0,0 +1,80 @@ +"""Fit, persist and restore native Spark FE; run with the optional Spark environment. + +Use --state-path features.json to retain the portable bytes. The application owns +the Spark session and file I/O; the core API only exports/imports bytes. This demo +uses local[2] and a tiny fixture; Databricks callers supply their own session. +""" + +import argparse +import importlib +import math +import os +import sys +from pathlib import Path + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.preprocessing.pipeline import FeatureEngineer + + +def run_example(spark, state_path: Path | None = None) -> None: + """Demonstrate training-only state and key-based parity after reload/repartition.""" + train = spark.createDataFrame( + [(1, 1.0, 0, "unused"), (2, None, 1, "unused"), (3, 3.0, 0, "unused")], + "id long, amount double, label long, extra string", + ).select("id", "amount", "label") + options = ExecutionOptions("spark", state_max_bytes=64 * 1024) + engineer = FeatureEngineer( + [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["amount"], "strategy": "mean"}, + }, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["amount"]}}, + ], + frame_spec=FrameSpec(("id",), "label"), + execution_options=options, + ) + engineer.fit_transform(train) + payload = engineer.export_state() + if state_path is not None: + state_path.write_bytes(payload) + payload = state_path.read_bytes() + restored = FeatureEngineer.from_state( + payload, frame_spec=FrameSpec(("id",)), execution_options=options + ) + batch = spark.createDataFrame([(10, 3.0), (20, None), (30, 1.0)], "id long, amount double") + # Only this three-row demonstration result is collected; production can write a Spark table. + rows = {row.id: row.amount for row in restored.transform(batch.repartition(2)).collect()} + expected = {10: math.sqrt(1.5), 20: 0.0, 30: -math.sqrt(1.5)} + assert all( + math.isclose(rows[key], value, rel_tol=1e-10, abs_tol=1e-12) + for key, value in expected.items() + ) + assert restored.export_state() == payload + print(f"Portable bytes: {len(payload)}; keyed features: {rows}") + + +def main() -> None: + """Own the local session lifecycle and optional example artifact path.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--state-path", type=Path) + args = parser.parse_args() + os.environ["PYSPARK_PYTHON"] = sys.executable + os.environ["PYSPARK_DRIVER_PYTHON"] = sys.executable + spark_sql = importlib.import_module("pyspark.sql") + spark = ( + spark_sql.SparkSession.builder.master("local[2]") + .appName("skyulf-feature-state-example") + .config("spark.sql.shuffle.partitions", "2") + .config("spark.ui.enabled", "false") + .getOrCreate() + ) + try: + run_example(spark, args.state_path) + finally: + spark.stop() + + +if __name__ == "__main__": + main() diff --git a/skyulf-core/skyulf/core/portable_pipeline.py b/skyulf-core/skyulf/core/portable_pipeline.py new file mode 100644 index 000000000..e905d3244 --- /dev/null +++ b/skyulf-core/skyulf/core/portable_pipeline.py @@ -0,0 +1,114 @@ +"""Bounded ordered FE envelopes composed from the existing scalar node codecs.""" + +import hashlib +import json +from typing import Any + +from . import portable_state as codec + +_FIELDS = {"kind", "format_version", "steps", "semantic_digest"} +_STEP_FIELDS = {"name", "node_type", "config", "state"} + + +def encode_pipeline(records: list[dict], *, max_bytes: int) -> bytes: + """Encode resolved configurations and learned artifacts under one total wire budget.""" + codec._validate_limit(max_bytes) + steps = [] + for record in records: + node = record["type"] + state = codec.validate_state(node, record["artifact"]) + params = _config(node, record["params"], state) + if type(record["name"]) is not str: + raise ValueError("Portable step names must be strings.") + steps.append( + { + "name": record["name"], + "node_type": node, + "config": codec._pack(params), + "state": codec._envelope(node, state), + } + ) + document = {"kind": "skyulf.feature_engineer", "format_version": 1, "steps": steps} + document["semantic_digest"] = _digest(document) + return codec._json_bytes(document, max_bytes) + + +def decode_pipeline(payload: bytes, *, max_bytes: int) -> list[dict[str, Any]]: + """Validate the entire envelope before creating or resolving any runnable appliers.""" + codec._validate_limit(max_bytes) + if type(payload) is not bytes: + raise TypeError("Portable pipeline payload must be bytes.") + if len(payload) > max_bytes: + raise ValueError("Portable pipeline exceeds max_bytes.") + try: + document = json.loads( + payload.decode("utf-8"), + object_pairs_hook=codec._unique_object, + parse_constant=codec._bad_constant, + ) + _validate_envelope(document) + content = {key: value for key, value in document.items() if key != "semantic_digest"} + if document["semantic_digest"] != _digest(content): + raise ValueError("Portable pipeline semantic_digest mismatch.") + return [_decode_step(step) for step in document["steps"]] + except (RecursionError, UnicodeError, OverflowError) as exc: + raise ValueError("Invalid portable pipeline encoding or nesting depth.") from exc + + +def _decode_step(step: Any) -> dict[str, Any]: + """Validate each node payload and its corresponding resolved configuration.""" + if type(step) is not dict or set(step) != _STEP_FIELDS or type(step["name"]) is not str: + raise ValueError("Invalid portable pipeline step fields.") + node, artifact = codec._decode_envelope(step["state"]) + if node != step["node_type"]: + raise ValueError("Pipeline step node_type differs from its state.") + params = codec._unpack(step["config"]) + resolved = _config(node, params, artifact) + if codec._pack(resolved) != codec._pack(params): + raise ValueError("Portable pipeline config must match resolved learned columns/defaults.") + return {"name": step["name"], "type": node, "params": resolved, "artifact": artifact} + + +def _config(node: str, raw: Any, state: dict) -> dict[str, Any]: + """Freeze learned feature selection while removing caller-specific frame context.""" + params = codec._normalize(raw) + if type(params) is not dict: + raise ValueError("Portable pipeline config must be a dictionary.") + params.pop("target_column", None) + params.pop("_auto_columns", None) + params["columns"] = state.get("columns", []) + defaults = ( + {"strategy": "mean", "fill_value": None} + if node == "SimpleImputer" + else {"with_mean": True, "with_std": True} + ) + params = {**defaults, **params} + keys = ("strategy",) if node == "SimpleImputer" else ("with_mean", "with_std") + for key in keys: + if state and (type(params[key]) is not type(state[key]) or params[key] != state[key]): + raise ValueError("Portable config disagrees with fitted state.") + if node == "SimpleImputer" and params["strategy"] not in ("mean", "constant"): + raise ValueError("Unsupported portable SimpleImputer strategy.") + if node == "StandardScaler" and any(type(params[key]) is not bool for key in keys): + raise ValueError("Scaler flags must be booleans.") + return params + + +def _validate_envelope(document: Any) -> None: + """Reject unknown formats, versions and top-level fields before interpreting steps.""" + if type(document) is not dict or set(document) != _FIELDS: + raise ValueError("Invalid portable pipeline envelope fields.") + if document["kind"] != "skyulf.feature_engineer": + raise ValueError("Unsupported portable pipeline kind.") + if type(document["format_version"]) is not int or document["format_version"] != 1: + raise ValueError("Unsupported portable pipeline format_version.") + if type(document["steps"]) is not list or type(document["semantic_digest"]) is not str: + raise ValueError("Invalid portable pipeline steps/digest.") + + +def _digest(document: dict) -> str: + """Cover ordered node envelopes and configurations with a canonical content checksum.""" + digest = hashlib.sha256() + for chunk in codec._json_chunks(document): + digest.update(chunk) + return digest.hexdigest() diff --git a/skyulf-core/skyulf/core/portable_state.py b/skyulf-core/skyulf/core/portable_state.py index 8fda68952..abaef09cc 100644 --- a/skyulf-core/skyulf/core/portable_state.py +++ b/skyulf-core/skyulf/core/portable_state.py @@ -64,20 +64,25 @@ def decode_state( document = json.loads( payload.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_bad_constant ) - _validate_envelope(document) - node_type = document["node_type"] - params = _unpack(document["learned_parameters"]) - _validate_state(node_type, params) - if document["ordered_columns"] != params.get("columns", []): - raise ValueError("ordered_columns must match the learned columns in order.") - expected = _envelope(node_type, params)["semantic_digest"] - if document["semantic_digest"] != expected: - raise ValueError("Portable state semantic_digest mismatch.") - return node_type, params + return _decode_envelope(document) except (RecursionError, UnicodeError, OverflowError) as exc: raise ValueError("Invalid portable state encoding or nesting depth.") from exc +def _decode_envelope(document: Any) -> tuple[str, dict[str, Any]]: + """Validate a parsed node envelope inside an already byte-bounded document.""" + _validate_envelope(document) + node_type = document["node_type"] + params = _unpack(document["learned_parameters"]) + _validate_state(node_type, params) + if document["ordered_columns"] != params.get("columns", []): + raise ValueError("ordered_columns must match the learned columns in order.") + expected = _envelope(node_type, params)["semantic_digest"] + if document["semantic_digest"] != expected: + raise ValueError("Portable state semantic_digest mismatch.") + return node_type, params + + def _validate_limit(value: int) -> None: """Require a positive byte budget without treating booleans as integers.""" if type(value) is not int or value <= 0: @@ -293,15 +298,18 @@ def _envelope(node_type: str, params: dict[str, Any]) -> dict[str, Any]: def _json_bytes(document: dict, max_bytes: int) -> bytes: """Stop JSON output as soon as the complete wire representation exceeds its budget.""" output = bytearray() - for encoded in _json_chunks(document): + for encoded in _json_chunks(document, ensure_ascii=False): if len(output) + len(encoded) > max_bytes: raise ValueError("Portable state exceeds max_bytes.") output.extend(encoded) return bytes(output) -def _json_chunks(document: dict) -> Iterator[bytes]: +def _json_chunks(document: dict, *, ensure_ascii: bool = True) -> Iterator[bytes]: """Stream canonical UTF-8 chunks for serialization and semantic hashing.""" - encoder = json.JSONEncoder(sort_keys=True, separators=(",", ":"), allow_nan=False) + encoder = json.JSONEncoder( + sort_keys=True, separators=(",", ":"), allow_nan=False, ensure_ascii=ensure_ascii + ) for chunk in encoder.iterencode(document): - yield chunk.encode("utf-8") + # Lone surrogates retain their JSON escape spelling, as in the original codec. + yield chunk.encode("utf-8", errors="backslashreplace") diff --git a/skyulf-core/skyulf/pipeline/_pipeline.py b/skyulf-core/skyulf/pipeline/_pipeline.py index c4bcbd74b..ea23dd880 100644 --- a/skyulf-core/skyulf/pipeline/_pipeline.py +++ b/skyulf-core/skyulf/pipeline/_pipeline.py @@ -270,6 +270,7 @@ def _fit_tuning_pipeline( # new prediction requests or changing their row order. _record_tuning_column_drops(adapter._engineer, raw_train[0], adapter.input_columns) self.feature_engineer.fitted_steps = prefix.fitted_steps + adapter._engineer.fitted_steps + self.feature_engineer._portable_fitted = True transformed = SplitDataset( train=adapter.training_payload, test=self._transform_tuning_split(adapter, raw_dataset.test, target_column), @@ -346,6 +347,7 @@ def fit( # A failure can occur after model fitting, while transforming or # predicting held-out data. Never expose that partial replacement. self.feature_engineer.fitted_steps = [] + self.feature_engineer._portable_fitted = False if self.model_estimator is not None: self.model_estimator.model = None raise diff --git a/skyulf-core/skyulf/preprocessing/_feature_state.py b/skyulf-core/skyulf/preprocessing/_feature_state.py new file mode 100644 index 000000000..10b99c9be --- /dev/null +++ b/skyulf-core/skyulf/preprocessing/_feature_state.py @@ -0,0 +1,58 @@ +"""Bind validated portable FE records to known implementations and fresh runtime context.""" + +from typing import Any + +from ..core.execution import ExecutionOptions, FrameSpec +from ..core.portable_pipeline import decode_pipeline, encode_pipeline +from ..core.portable_state import DEFAULT_MAX_STATE_BYTES +from ._spark import _preflight +from .imputation.simple import SimpleImputerApplier +from .scaling.standard import StandardScalerApplier + +_APPLIERS = {"SimpleImputer": SimpleImputerApplier, "StandardScaler": StandardScalerApplier} + + +def export_feature_state(engineer: Any) -> bytes: + """Reject incomplete or unsupported execution histories before serializing learned state.""" + if not getattr(engineer, "_portable_fitted", bool(engineer.fitted_steps)): + raise ValueError("FeatureEngineer must be successfully fitted before exporting state.") + if len(engineer.fitted_steps) != len(engineer.steps_config): + raise ValueError("Unsupported or incomplete portable pipeline step history.") + records = [] + for record, config in zip(engineer.fitted_steps, engineer.steps_config, strict=True): + node = record["type"] + if node not in _APPLIERS or type(record["applier"]) is not _APPLIERS[node]: + raise ValueError("Unsupported portable pipeline node or custom applier.") + records.append({**record, "params": record.get("params", config.get("params", {}))}) + return encode_pipeline(records, max_bytes=_budget(getattr(engineer, "execution_options", None))) + + +def restore_feature_state( + payload: bytes, options: ExecutionOptions | None, spec: FrameSpec | None +) -> tuple[list[dict], list[dict]]: + """Rebind explicit Spark keys and instantiate only known node appliers after validation.""" + if options is not None and not isinstance(options, ExecutionOptions): + raise TypeError("execution_options must be ExecutionOptions.") + if spec is not None and not isinstance(spec, FrameSpec): + raise TypeError("frame_spec must be FrameSpec.") + spark = options is not None and options.engine == "spark" + if spark and spec is None: + raise ValueError("Spark requires frame_spec when loading portable state.") + if not spark and spec is not None: + raise ValueError("frame_spec is currently supported only for Spark execution.") + records = decode_pipeline(payload, max_bytes=_budget(options)) + if spark: + assert spec is not None + _preflight(records, spec, training=False) + configs = [ + {"name": step["name"], "transformer": step["type"], "params": step["params"]} + for step in records + ] + for step in records: + step["applier"] = _APPLIERS[step["type"]]() + return configs, records + + +def _budget(options: ExecutionOptions | None) -> int: + """Apply one total byte limit independently of the destination runtime.""" + return options.state_max_bytes if options is not None else DEFAULT_MAX_STATE_BYTES diff --git a/skyulf-core/skyulf/preprocessing/pipeline.py b/skyulf-core/skyulf/preprocessing/pipeline.py index fbfb9366f..d07f6605f 100644 --- a/skyulf-core/skyulf/preprocessing/pipeline.py +++ b/skyulf-core/skyulf/preprocessing/pipeline.py @@ -16,6 +16,7 @@ from ..registry import NodeRegistry from ..types import PreprocessingStepConfig from ..utils import get_data_stats, pack_pipeline_output, unpack_pipeline_input +from ._feature_state import export_feature_state, restore_feature_state from ._spark import fit_spark, transform_spark, use_spark from .base import StatefulTransformer from .dispatcher import _check_xy_engine_parity @@ -111,6 +112,40 @@ def __init__( self.frame_spec = frame_spec self.execution_options = execution_options self._spark_fitted = False + self._portable_fitted = False + + def export_state(self) -> bytes: + """Export supported fitted steps as bounded, versioned UTF-8 JSON bytes. + + SimpleImputer mean/constant and StandardScaler are supported. Learned + column selection is frozen; row keys, target and runtime objects are + supplied again when loading. The complete payload must fit the execution + state byte budget (8 MiB by default). Callers own storage and transport. + """ + return export_feature_state(self) + + @classmethod + def from_state( + cls, + payload: bytes, + *, + frame_spec: FrameSpec | None = None, + execution_options: ExecutionOptions | None = None, + ) -> "FeatureEngineer": + """Restore supported fitted steps without fitting, I/O or creating a Spark session. + + Spark requires explicit frame_spec and execution_options. Local callers + may omit both and let input frames select pandas or Polars. Malformed, + oversized, unsupported or corrupt envelopes are rejected before execution. + """ + configs, records = restore_feature_state(payload, execution_options, frame_spec) + engineer = cls(configs, frame_spec=frame_spec, execution_options=execution_options) + engineer.fitted_steps = records + engineer._portable_fitted = True + engineer._spark_fitted = ( + execution_options is not None and execution_options.engine == "spark" + ) + return engineer def transform( self, data: pd.DataFrame | SkyulfDataFrame | Any, *, preserve_rows: bool = False @@ -207,7 +242,9 @@ def fit_transform( ) self.fitted_steps = records self._spark_fitted = True + self._portable_fitted = True return result, metrics + self._portable_fitted = False self.fitted_steps = [] # Reset fitted steps current_data = data split_captured = False @@ -299,6 +336,7 @@ def fit_transform( metrics["rows_in"] = metrics["summary"]["rows_in"] metrics["rows_out"] = metrics["summary"]["rows_out"] + self._portable_fitted = True return current_data, metrics @staticmethod @@ -401,6 +439,7 @@ def _run_step( "type": transformer_type, "applier": applier, "artifact": fitted_params, + "params": dict(params), } ) return current_data, fitted_params, transformer diff --git a/skyulf-core/tests/spark/test_feature_pipeline.py b/skyulf-core/tests/spark/test_feature_pipeline.py new file mode 100644 index 000000000..892aaadf2 --- /dev/null +++ b/skyulf-core/tests/spark/test_feature_pipeline.py @@ -0,0 +1,171 @@ +"""Portable native FE must retain keyed predictions through engine and partition changes.""" + +import json +import math + +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.preprocessing.pipeline import FeatureEngineer + + +def test_compact_unicode_pipeline_runs_with_received_budget(spark): + """Spark apply must not expand Unicode escaping and reject an already bounded pipeline.""" + column = "ölçüm" * 50 + fe = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer", "params": {"columns": [column]}}] + ) + fe.fit_transform(pd.DataFrame({column: [1.0, 3.0]})) + payload = json.dumps( + json.loads(fe.export_state()), ensure_ascii=False, separators=(",", ":") + ).encode() + restored = FeatureEngineer.from_state( + payload, + frame_spec=FrameSpec(("id",)), + execution_options=ExecutionOptions("spark", state_max_bytes=len(payload)), + ) + frame = spark.createDataFrame([(1, float("nan"))], ["id", column]) + assert restored.transform(frame).first()[column] == 2.0 + + +@pytest.fixture(scope="module", params=["pandas", "polars", "spark"]) +def fitted_payload(request, spark): + """Fit once per source engine so every destination sees the same training-only state.""" + local = pd.DataFrame({"id": [1, 2, 3], "x": [1.0, float("nan"), 3.0], "label": [0, 1, 0]}) + data = local if request.param == "pandas" else pl.from_pandas(local) + if request.param == "spark": + data = spark.createDataFrame( + [(1, 1.0, 0), (2, None, 1), (3, 3.0, 0)], "id long, x double, label long" + ) + fe = FeatureEngineer( + [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x"]}}, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}, + ], + frame_spec=FrameSpec(("id",), "label") if request.param == "spark" else None, + execution_options=ExecutionOptions("spark") if request.param == "spark" else None, + ) + fe.fit_transform(data) + return fe.export_state() + + +@pytest.mark.parametrize("apply_engine", ["pandas", "polars", "spark"]) +def test_full_chain_cross_engine_round_trip(spark, fitted_payload, apply_engine, tmp_path): + """Byte persistence must preserve train-only imputation then scaling across all engines.""" + path = tmp_path / "features.json" + path.write_bytes(fitted_payload) + fe = FeatureEngineer.from_state( + path.read_bytes(), + frame_spec=FrameSpec(("key",)) if apply_engine == "spark" else None, + execution_options=ExecutionOptions(apply_engine), + ) + local = pd.DataFrame({"key": [20, 10, 30], "x": [3.0, 1.0, float("nan")]}) + data = { + "pandas": lambda: local, + "polars": lambda: pl.from_pandas(local), + "spark": lambda: spark.createDataFrame( + [(20, 3.0), (10, 1.0), (30, None)], "key long, x double" + ).repartition(2), + }[apply_engine]() + output = fe.transform(data) + rows = { + "pandas": lambda: output.to_dict("records"), + "polars": lambda: output.to_dicts(), + "spark": lambda: [r.asDict() for r in output.collect()], + }[apply_engine]() + assert {row["key"]: row["x"] for row in rows} == pytest.approx( + {10: -math.sqrt(1.5), 20: math.sqrt(1.5), 30: 0.0} + ) + assert fe.export_state() == fitted_payload + + +@pytest.mark.parametrize("partitions", [1, 2, 7]) +def test_repartition_reversal_and_repeated_transform(spark, fitted_payload, partitions): + """Rows are identified by keys and repeated apply must leave learned state untouched.""" + fe = FeatureEngineer.from_state( + fitted_payload, frame_spec=FrameSpec(("id",)), execution_options=ExecutionOptions("spark") + ) + data = spark.createDataFrame([(1, 1.0), (2, 3.0), (3, None)], "id long, x double") + expected = {1: -math.sqrt(1.5), 2: math.sqrt(1.5), 3: 0.0} + for frame in ( + data.repartition(partitions), + data.orderBy("id", ascending=False).repartition(partitions), + ): + actual = {row.id: row.x for row in fe.transform(frame).collect()} + assert actual == pytest.approx(expected, rel=1e-10, abs=1e-12) + assert fe.export_state() == fitted_payload + + +def test_spark_failed_refit_preserves_exported_pipeline(spark, fitted_payload): + """The last successful Spark fit must remain exportable after a failed refit.""" + fe = FeatureEngineer.from_state( + fitted_payload, frame_spec=FrameSpec(("id",)), execution_options=ExecutionOptions("spark") + ) + duplicate = spark.createDataFrame([(1, 1.0), (1, 3.0)], "id long, x double") + with pytest.raises(ValueError, match="unique"): + fe.fit_transform(duplicate) + assert fe.export_state() == fitted_payload + + +def test_large_pipeline_forbids_unbounded_collection(spark, monkeypatch): + """Only bounded aggregate or validation rows may cross the driver boundary.""" + data = spark.range(10000).selectExpr( + "id", "CASE WHEN id % 3 = 0 THEN NULL ELSE CAST(id AS DOUBLE) END AS x" + ) + original_collect = type(data).collect + original_first = type(data).first + bounded_depth = 0 + returned_sizes = [] + + def bounded_first(frame): + """The node's first() boundary limits aggregate results to one row.""" + nonlocal bounded_depth + bounded_depth += 1 + try: + return original_first(frame) + finally: + bounded_depth -= 1 + + def guarded_collect(frame): + """Permit only explicit one-row validation limits or the bounded aggregate path.""" + plan = frame._jdf.queryExecution().logical().toString() + assert bounded_depth or plan.startswith("GlobalLimit 1"), "Unbounded input collection" + rows = original_collect(frame) + returned_sizes.append(len(rows)) + assert len(rows) <= 1 + return rows + + def forbidden(*args, **kwargs): + """Distributed frames cannot enter local preprocessing during this gate.""" + pytest.fail("Local conversion in native pipeline") + + with monkeypatch.context() as patch: + patch.setattr(type(data), "collect", guarded_collect) + patch.setattr(type(data), "first", bounded_first) + for name in ("toPandas", "toArrow", "toLocalIterator"): + patch.setattr(type(data), name, forbidden) + fe = FeatureEngineer( + [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x"]}}, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}, + ], + frame_spec=FrameSpec(("id",)), + execution_options=ExecutionOptions("spark"), + ) + trained, _ = fe.fit_transform(data) + restored = FeatureEngineer.from_state( + fe.export_state(), + frame_spec=FrameSpec(("id",)), + execution_options=ExecutionOptions("spark"), + ) + output = restored.transform(data.repartition(7)) + # Explicit terminal aggregate remains distributed; no training samples are collected. + stats = output.selectExpr( + "count(*) AS rows", "avg(x) AS mean", "var_pop(x) AS variance" + ).first() + assert stats.rows == 10000 + assert stats.mean == pytest.approx(0.0, abs=1e-12) + assert stats.variance == pytest.approx(1.0, rel=1e-10, abs=1e-12) + assert returned_sizes and trained.columns == ["id", "x"] diff --git a/skyulf-core/tests/spark/test_portable_state.py b/skyulf-core/tests/spark/test_portable_state.py index 16619d195..83fe0d07f 100644 --- a/skyulf-core/tests/spark/test_portable_state.py +++ b/skyulf-core/tests/spark/test_portable_state.py @@ -300,5 +300,7 @@ def test_decode_limit_measures_received_unicode_bytes(): """Canonical checksum escaping must not reject a received envelope within budget.""" payload = encode_state("SimpleImputer", imputer_state("λ" * 100), max_bytes=8192) compact = json.dumps(json.loads(payload), ensure_ascii=False, separators=(",", ":")).encode() - assert len(compact) < len(payload) + escaped = json.dumps(json.loads(payload), ensure_ascii=True, separators=(",", ":")).encode() + assert len(compact) < len(escaped) assert decode_state(compact, max_bytes=len(compact)) == decode_state(payload) + assert decode_state(escaped) == decode_state(payload) diff --git a/skyulf-core/tests/unit/test_feature_state.py b/skyulf-core/tests/unit/test_feature_state.py new file mode 100644 index 000000000..1b33915a2 --- /dev/null +++ b/skyulf-core/tests/unit/test_feature_state.py @@ -0,0 +1,237 @@ +"""Portable FE state must be complete, bounded and safe to load without a runtime.""" + +import json +import pickle + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.pipeline import SkyulfPipeline +from skyulf.preprocessing.pipeline import FeatureEngineer + + +def _engineer(engine="pandas", **kwargs): + """Fit a real two-step pipeline whose held-out values expose accidental refitting.""" + fe = FeatureEngineer( + [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x"]}}, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}, + ], + **kwargs, + ) + frame = pd.DataFrame({"x": [1.0, np.nan, 3.0]}) + fe.fit_transform(pl.from_pandas(frame) if engine == "polars" else frame) + return fe + + +@pytest.mark.parametrize("fit_engine", ["pandas", "polars"]) +@pytest.mark.parametrize("apply_engine", ["pandas", "polars"]) +def test_local_pipeline_round_trip_does_not_refit(fit_engine, apply_engine): + """Loading learned FE must preserve step order and train-only statistics on either engine.""" + fe = _engineer(fit_engine) + payload = fe.export_state() + restored = FeatureEngineer.from_state(payload, execution_options=ExecutionOptions(apply_engine)) + local = pd.DataFrame({"id": [2, 1], "x": [100.0, np.nan]}) + data = pl.from_pandas(local) if apply_engine == "polars" else local + out = restored.transform(data) + np.testing.assert_allclose( + out["x"].to_numpy(), [120.02499739637573, 0.0], rtol=1e-10, atol=1e-12 + ) + assert out["id"].to_list() == [2, 1] + assert restored.export_state() == payload + assert [step["name"] for step in restored.steps_config] == ["fill", "scale"] + + +def test_unfitted_and_failed_refit_cannot_export_partial_state(): + """An incomplete fit must never become a seemingly valid portable inference pipeline.""" + fe = _engineer() + with pytest.raises(ValueError, match="fitted"): + FeatureEngineer([]).export_state() + with pytest.raises(ValueError): + fe.fit_transform(pd.DataFrame({"x": ["invalid", "text"]})) + with pytest.raises(ValueError, match="fitted"): + fe.export_state() + + +def test_fitted_empty_and_noop_pipelines_round_trip(): + """An intentionally empty pipeline is distinguishable from an unfitted object.""" + for steps in ( + [], + [{"name": "skip", "transformer": "StandardScaler", "params": {"columns": []}}], + ): + fe = FeatureEngineer(steps) + data = pd.DataFrame({"x": [1.0, np.nan]}) + fe.fit_transform(data) + restored = FeatureEngineer.from_state(fe.export_state()) + pd.testing.assert_frame_equal(restored.transform(data), data) + + +def test_total_wire_budget_applies_on_export_and_before_parse(monkeypatch): + """A pipeline of small artifacts must not bypass the total payload byte limit.""" + fe = _engineer() + payload = fe.export_state() + fe.execution_options = ExecutionOptions("pandas", state_max_bytes=len(payload) - 1) + with pytest.raises(ValueError, match="max_bytes"): + fe.export_state() + fe.execution_options = ExecutionOptions("pandas", state_max_bytes=len(payload)) + assert fe.export_state() == payload + + def forbidden(*args, **kwargs): + """An oversized input must be rejected before attempting JSON parsing.""" + pytest.fail("Parsed oversized state") + + monkeypatch.setattr(json, "loads", forbidden) + with pytest.raises(ValueError, match="max_bytes"): + FeatureEngineer.from_state( + payload, execution_options=ExecutionOptions("pandas", state_max_bytes=len(payload) - 1) + ) + + +@pytest.mark.parametrize( + "payload", [b"[]", b"{}", b"null", b'{"format_version":1,"format_version":1}', b"\xff", b"NaN"] +) +def test_malformed_payload_is_rejected(payload): + """Malformed input cannot produce a runnable object or invoke a pickle fallback.""" + with pytest.raises(ValueError): + FeatureEngineer.from_state(payload) + + +def test_step_reordering_and_config_corruption_are_detected(): + """The envelope checksum must cover ordered steps and configuration as well as node state.""" + payload = _engineer().export_state() + document = json.loads(payload) + document["steps"].reverse() + with pytest.raises(ValueError, match="digest"): + FeatureEngineer.from_state(json.dumps(document).encode()) + document = json.loads(payload) + document["steps"][0]["name"] = "tampered" + with pytest.raises(ValueError, match="digest"): + FeatureEngineer.from_state(json.dumps(document).encode()) + + +def test_unknown_version_and_pickle_payload_rejected(): + """New versions and Python object serialization require explicit APIs, never guessing.""" + fe = _engineer() + document = json.loads(fe.export_state()) + document["format_version"] = 2 + with pytest.raises(ValueError, match="version"): + FeatureEngineer.from_state(json.dumps(document).encode()) + with pytest.raises(ValueError): + FeatureEngineer.from_state(pickle.dumps(fe)) + + +def test_unsupported_nodes_and_unserializable_configuration_rejected(): + """A local-only or custom object pipeline must not acquire a misleading portable label.""" + fe = FeatureEngineer( + [{"name": "range", "transformer": "MinMaxScaler", "params": {"columns": ["x"]}}] + ) + fe.fit_transform(pd.DataFrame({"x": [1.0, 3.0]})) + with pytest.raises(ValueError, match="[Uu]nsupported"): + fe.export_state() + portable = _engineer() + portable.fitted_steps[0]["params"]["custom"] = object() + with pytest.raises(TypeError, match="[Uu]nsupported"): + portable.export_state() + + +def test_spark_context_is_rebound_and_protected_features_rejected(): + """Runtime identity comes from the caller and must not overlap learned feature columns.""" + payload = _engineer().export_state() + with pytest.raises(ValueError, match="frame_spec"): + FeatureEngineer.from_state(payload, execution_options=ExecutionOptions("spark")) + with pytest.raises(ValueError, match="row_keys|target|protected"): + FeatureEngineer.from_state( + payload, frame_spec=FrameSpec(("x",)), execution_options=ExecutionOptions("spark") + ) + restored = FeatureEngineer.from_state( + payload, frame_spec=FrameSpec(("new_id",)), execution_options=ExecutionOptions("spark") + ) + assert restored.frame_spec == FrameSpec(("new_id",)) + assert restored.export_state() == payload + + +def test_disabled_scaler_and_nonfinite_constant_configuration_round_trip(): + """Tagged configuration must retain NaN scalars and disabled optional statistics.""" + fe = FeatureEngineer( + [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["x"], "strategy": "constant", "fill_value": float("nan")}, + }, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["x"], "with_mean": False, "with_std": False}, + }, + ] + ) + data = pl.DataFrame({"x": [1.0, None]}) + fe.fit_transform(data) + restored = FeatureEngineer.from_state(fe.export_state()) + assert np.isnan(restored.steps_config[0]["params"]["fill_value"]) + assert restored.fitted_steps[1]["artifact"]["mean"] is None + assert restored.export_state() == fe.export_state() + + +def test_compact_unicode_payload_obeys_received_wire_budget(): + """Canonical escaping of nested state must not impose a second artificial input limit.""" + column = "ölçüm" * 50 + fe = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer", "params": {"columns": [column]}}] + ) + fe.fit_transform(pd.DataFrame({column: [1.0, 3.0]})) + payload = json.dumps( + json.loads(fe.export_state()), ensure_ascii=False, separators=(",", ":") + ).encode() + restored = FeatureEngineer.from_state( + payload, execution_options=ExecutionOptions("pandas", state_max_bytes=len(payload)) + ) + assert restored.transform(pd.DataFrame({column: [np.nan]})).iloc[0, 0] == 2.0 + + +def test_escaped_surrogate_names_keep_previous_json_compatibility(): + """Compact UTF-8 encoding must still preserve names previously represented with escapes.""" + column = "x\ud800" + fe = FeatureEngineer( + [{"name": "fill", "transformer": "SimpleImputer", "params": {"columns": [column]}}] + ) + fe.fit_transform(pd.DataFrame({column: [1.0, 3.0]})) + restored = FeatureEngineer.from_state(fe.export_state()) + assert restored.transform(pd.DataFrame({column: [np.nan]})).iloc[0, 0] == 2.0 + + +@pytest.mark.parametrize("tuning", [False, True]) +@pytest.mark.parametrize("empty", [False, True]) +def test_model_pipeline_exports_only_successful_preprocessing(tuning, empty): + """Tuning must publish exportable FE, and failed model refits must invalidate it.""" + modeling = {"type": "ridge_regression"} + if tuning: + modeling = { + "type": "hyperparameter_tuner", + "base_model": {"type": "ridge_regression"}, + "strategy": "grid", + "metric": "r2", + "search_space": {"alpha": [1.0]}, + "cv_folds": 2, + "n_jobs": 1, + } + steps = ( + [] + if empty + else [{"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}] + ) + pipeline = SkyulfPipeline({"preprocessing": steps, "modeling": modeling}) + data = pd.DataFrame({"x": np.arange(12, dtype=float), "target": np.arange(12) * 2.0}) + pipeline.fit(data, target_column="target") + original = pipeline.feature_engineer + restored = FeatureEngineer.from_state(original.export_state()) + query = pd.DataFrame({"x": [100.0]}) + pd.testing.assert_frame_equal(restored.transform(query), original.transform(query)) + with pytest.raises(ValueError): + pipeline.fit(data.assign(target=np.nan), target_column="target") + with pytest.raises(ValueError, match="fitted"): + pipeline.feature_engineer.export_state() From 81745a7b9c2a4473ba9cbe2117e61c136ad6ebf1 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 22:53:17 +0300 Subject: [PATCH 10/85] feat(core): add validated standalone inference bundles Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 9 + docs/user_guide/inference_bundles.md | 159 ++++++++ docs/user_guide/spark.md | 3 + .../spark_and_mlflow/02-inference-plan.md | 25 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 71 +++- initiatives/spark_and_mlflow/README.md | 4 +- mkdocs.yml | 1 + skyulf-core/examples/inference_bundle.py | 63 +++ skyulf-core/skyulf/inference/__init__.py | 5 + skyulf-core/skyulf/inference/_manifest.py | 202 +++++++++ skyulf-core/skyulf/inference/_model.py | 117 ++++++ skyulf-core/skyulf/inference/_storage.py | 50 +++ skyulf-core/skyulf/inference/bundle.py | 271 ++++++++++++ skyulf-core/skyulf/pipeline/_pipeline.py | 15 + .../skyulf/preprocessing/_feature_state.py | 5 +- .../tests/spark/test_inference_bundle.py | 386 ++++++++++++++++++ .../unit/test_pipeline_inference_schema.py | 185 +++++++++ 17 files changed, 1556 insertions(+), 15 deletions(-) create mode 100644 docs/user_guide/inference_bundles.md create mode 100644 skyulf-core/examples/inference_bundle.py create mode 100644 skyulf-core/skyulf/inference/__init__.py create mode 100644 skyulf-core/skyulf/inference/_manifest.py create mode 100644 skyulf-core/skyulf/inference/_model.py create mode 100644 skyulf-core/skyulf/inference/_storage.py create mode 100644 skyulf-core/skyulf/inference/bundle.py create mode 100644 skyulf-core/tests/spark/test_inference_bundle.py create mode 100644 skyulf-core/tests/unit/test_pipeline_inference_schema.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index fd1f0f60a..0275286f7 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -65,6 +65,15 @@ execution and MLflow adapters remain under development. example and guide demonstrate saving and loading the fitted chain. Successful tuned pipelines can export their supported FE; failed model fits invalidate it. +- Standalone inference bundles with explicit `raw`/`features` inputs, frozen + FE/model payloads, ordered input/output schemas, runtime requirements and + corruption/budget checks. Local pandas/Polars regression and classification + preserve probability class order and default versus opt-in threshold behavior. + Successful pipeline fits capture schema metadata without retaining input frames; + legacy artifacts without schemas require refitting. Includes a runnable example + and [bundle guide](../docs/user_guide/inference_bundles.md). Trusted sklearn + pickle payloads remain distinct from portable FE JSON and legacy persistence. + ### Planned scope — not yet available - Further native Spark nodes and broader portable-state coverage. diff --git a/docs/user_guide/inference_bundles.md b/docs/user_guide/inference_bundles.md new file mode 100644 index 000000000..16525508f --- /dev/null +++ b/docs/user_guide/inference_bundles.md @@ -0,0 +1,159 @@ +# Standalone inference bundles + +The 0.9.0 development API packages a fitted feature pipeline and a Python +estimator with an explicit inference contract. It supports local pandas/Polars +prediction and provides the package boundary for the later Spark worker runner. +Importing `skyulf.inference` requires neither PySpark nor MLflow. + +## Raw data and prepared features + +Choose the input stage when building a bundle: + +| `input_stage` | Expected input | Execution | +| --- | --- | --- | +| `raw` | Original feature columns | Apply saved FE once, then predict | +| `features` | Already transformed model features | Predict directly | + +Both bundles contain the same frozen FE state and estimator. Their declared +stages differ. A stage is an explicit caller contract: numeric values alone +cannot reveal whether a column has already been scaled. Keep raw and prepared +data on the corresponding path. + +```python +from pathlib import Path +from tempfile import TemporaryDirectory + +import numpy as np +import pandas as pd + +from skyulf.data.dataset import SplitDataset +from skyulf.inference import build_bundle, load_bundle, predict_local, save_bundle +from skyulf.pipeline import SkyulfPipeline + +training = pd.DataFrame({"amount": [1.0, 2.0, 3.0], "target": [10.0, 20.0, 30.0]}) +pipeline = SkyulfPipeline({ + "preprocessing": [ + {"name": "fill", "transformer": "SimpleImputer", + "params": {"columns": ["amount"], "strategy": "mean"}}, + {"name": "scale", "transformer": "StandardScaler", + "params": {"columns": ["amount"]}}, + ], + "modeling": {"type": "linear_regression"}, +}) +pipeline.fit(SplitDataset(train=training, test=training.head(0)), target_column="target") + +raw = pd.DataFrame({"amount": [4.0, np.nan]}) +bundle = build_bundle(pipeline, input_stage="raw", feature_order=("amount",)) +with TemporaryDirectory() as temporary: + destination = Path(temporary) / "model" + save_bundle(bundle, destination) + restored = load_bundle(destination) + output = predict_local(raw, restored) + np.testing.assert_allclose(output["prediction"], [40.0, 20.0], atol=1e-12) + +prepared = pipeline.feature_engineer.transform(raw) +features_bundle = build_bundle(pipeline, input_stage="features", feature_order=("amount",)) +np.testing.assert_allclose(predict_local(prepared, features_bundle)["prediction"], + output["prediction"], atol=1e-12) +``` + +The repository also includes `skyulf-core/examples/inference_bundle.py`. Run +it from the root with `.venv/Scripts/python.exe skyulf-core/examples/inference_bundle.py`. +Add `--bundle-dir path/to/new-model` to retain the artifact. An existing +destination is rejected, so an earlier package cannot be overwritten accidentally. + +## Input and output contracts + +A successful `SkyulfPipeline.fit` records two schemas: original training +features with the target excluded, and the actual features supplied to model +training. They contain names and dtypes only, never sample rows. A failed +replacement fit clears this metadata along with the fitted model. + +`feature_order` must exactly match the recorded model order. `predict_local` +rejects missing, extra, duplicate or reordered columns and incompatible dtypes. +It does not sort columns or silently cast them. Equivalent pandas/Polars numeric +and boolean dtype labels are normalized; an integer feature is still distinct +from a floating-point feature. Select/cast columns explicitly before calling +when the source schema differs intentionally. + +Supply feature columns only. Extra targets or identity columns are rejected. +The returned pandas DataFrame preserves a pandas input index; Polars input +receives a RangeIndex. The later Spark runner will carry explicit `FrameSpec` +keys separately from model features. Calling `predict_local` with a Spark frame +fails before any collection or local conversion. + +Regression returns a float64 `prediction` column. Supported classifiers return +`prediction` and `probability_0`, `probability_1`, etc. `bundle.classes` records +the original labels in exactly that probability order; labels are not converted +into column names. Binary `positive_label` is the second estimator class, matching +the existing probability/threshold convention. Empty inputs return the declared +empty output schema. + +Tuning's saved decision thresholds remain active by default, as in the existing +tuning applier. Thresholds saved by `pipeline.optimize_thresholds(...)` remain +opt-in: pass `use_tuned_thresholds=True` to `build_bundle`. The manifest retains +both saved sets and the selected source; opting in without saved pipeline +thresholds fails. Probabilities remain unchanged by threshold decisions. + +## Package contents and loading + +Each new directory contains three fixed-name files: + +| File | Contents | +| --- | --- | +| `manifest.json` | Version, stage, ordered schemas, class/threshold metadata, runtime versions and digests | +| `features.json` | The supported fitted FeatureEngineer state | +| `model.pkl` | The frozen fitted sklearn estimator | + +The bundle holds immutable metadata and bytes. Later mutation of the training +pipeline does not alter it. Building or predicting never fits a transformer or +estimator. The model payload excludes the pipeline, training reports, runtime +sessions and registry clients. Runtime requirements are a fixed list of package +versions, not a copy of environment variables or connection configuration. +An estimator can retain training observations as part of its own fitted state; +K-neighbors models are one example. Bundling preserves that state and its size +is subject to the model byte limit. + +**Only load bundles from trusted producers.** The estimator uses pickle, which +can execute Python during deserialization. Checksums detect corruption; they +are not signatures and do not establish trust. Size, structural, payload-checksum +and runtime checks run before the pickle loader. Model class, feature width, +classes and fitted semantic digest are checked after deserialization. + +The semantic digest covers the inference contract and learned state. Exact +payload checksums also protect transported bytes, but changing only the pickle +protocol does not change semantic identity. Neither digest promises portability +across arbitrary library versions. + +Loading requires the same Python major/minor and exact recorded `skyulf-core`, +scikit-learn, NumPy and SciPy versions. pandas/Polars versions are recorded for +provenance; the input schema remains the execution check. There is no automatic +dependency installation. Prepare a matching environment before loading. + +The optional `options=ExecutionOptions(...)` argument to build/save/load/predict +sets the existing budgets: by default 8 MiB for manifest plus FE bytes and 256 MiB +for estimator bytes. Oversized file reads and pickle serialization are bounded. +These are wire-size checks, not total process-memory guarantees. A wider input +batch or a loaded estimator can use more memory than its serialized form. + +## Current support and legacy adapters + +The first version accepts a successfully fitted standalone `SkyulfPipeline` +with recorded schemas, primitive numeric/boolean features, supported sklearn +regression/classification behavior and portable FE. Currently that FE is +SimpleImputer mean/constant and StandardScaler, including an empty chain. +Classifiers must expose class probabilities. Custom appliers and unsupported +FE nodes require a separate adapter; they are not serialized as an opaque +whole pipeline. Training-only split nodes in the FE chain are therefore not +portable yet; an explicit `SplitDataset` can supply training/test partitions. + +Existing `SkyulfPipeline.save/load` pickle behavior is unchanged. A standalone +pipeline saved after schema capture can be loaded through that API and passed +to `build_bundle`. Historical standalone artifacts without captured schemas +must be fitted successfully again; the bundle does not invent missing column +names or types. Backend artifact dictionaries are rejected. Their explicit +adapter and threshold/label compatibility checks belong to SM-18. + +This delivery verifies local packaging and inference. Distributed Python model +execution, MLflow/Unity Catalog, Databricks runtime validation, endpoints and +template generation remain later stages of the [Spark work](spark.md). diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 58903b4d1..570092625 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -5,6 +5,9 @@ runtime tests, Spark engine adapter and keyed FeatureEngineer entry point are available in the development checkout. **Native SimpleImputer (mean/constant) and StandardScaler support fit and apply.** Their fitted pipeline can be exported and restored across pandas, Polars and Spark. +The [standalone inference bundle](inference_bundles.md) packages this state with +a fitted model and validates local raw/features prediction. The Spark model +worker runner is the next stage. Other built-in native nodes and distributed model inference remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. diff --git a/initiatives/spark_and_mlflow/02-inference-plan.md b/initiatives/spark_and_mlflow/02-inference-plan.md index aa0554b2a..a4b0f76d4 100644 --- a/initiatives/spark_and_mlflow/02-inference-plan.md +++ b/initiatives/spark_and_mlflow/02-inference-plan.md @@ -40,14 +40,14 @@ regression için boş tuple'dır. `predict_local` sonucu regression için `prediction`; classification için `prediction` ve sınıf sırası manifestte tanımlı probability kolonlarıdır. -- [ ] Mevcut pipeline'dan bundle oluştur; raw ve features girişlerini ayrı +- [x] Mevcut pipeline'dan bundle oluştur; raw ve features girişlerini ayrı fixtures ile kaydet/yükle. `features` modunda scaler ikinci kez uygulanmamalı. -- [ ] İsim doğru ama kolon sırası farklı, eksik/ekstra kolon, dtype uyuşmazlığı, +- [x] İsim doğru ama kolon sırası farklı, eksik/ekstra kolon, dtype uyuşmazlığı, bilinmeyen version ve model boyut sınırı için failure testleri yaz. -- [ ] Model payload ile manifest checksum'ını doğrula; dependency manifesti +- [x] Model payload ile manifest checksum'ını doğrula; dependency manifesti credentials ve session taşımasın. Pickle tabanlı payload yalnız güvenilir kaynaklardan yüklenir; manifest checksum'ı güvenilirlik kanıtı değildir. -- [ ] Eski standalone ve backend artifact formatları için explicit adapter +- [x] Eski standalone ve backend artifact formatları için explicit adapter tasarla; ilk bundle yalnız doğrulanmış standalone girdiyi kabul etsin. Legacy backend adapter SM-18'de mevcut threshold/label davranışıyla test edilir. @@ -56,21 +56,30 @@ def test_bundle_round_trip_predictions(fitted_regression_pipeline, tmp_path, raw """Packaging must preserve the prediction function, including preprocessing.""" import numpy as np from skyulf.inference.bundle import build_bundle, save_bundle, load_bundle, predict_local - bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x",)) + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) before = predict_local(raw_frame, bundle)["prediction"] save_bundle(bundle, tmp_path / "model") after = predict_local(raw_frame, load_bundle(tmp_path / "model"))["prediction"] np.testing.assert_allclose(after, before, rtol=1e-10, atol=1e-12) ``` -Fixture'lar bu görevde `tests/spark/conftest.py` içine eklenir: `raw_frame` -id/x kolonları ve farklı scale içeren küçük pandas verisi; +SM-08 fixture'ları `tests/spark/test_inference_bundle.py` içindedir: `raw_frame` +x/z kolonları ve farklı scale içeren küçük pandas verisi; `fitted_regression_pipeline` imputer + scaler + mevcut linear regression ile local fit edilmiş gerçek SkyulfPipeline. Veri üretimi seed=17 ve held-out satırlarla sabitlenir; mock estimator bu testin yerine geçmez. +Local giriş yalnız feature kolonlarıdır; ekstra id/target reddedilir. SM-09 +shared fixture'a ihtiyaç duyduğunda conftest'e taşır, Spark verisine ayrı id ekler. +Kolon adı/sırası modelin NumPy girdisinden tahmin edilmez; başarılı pipeline fit +metadata-only raw/model schema kaydeder. Eski standalone pickle için adapter +`SkyulfPipeline.load` → `build_bundle`; schema yoksa refit gerekir. Backend +dict adapter'ı SM-18'e kadar açıkça reddedilir. Ayrıntılar [bundle rehberinde](../../docs/user_guide/inference_bundles.md). **Komut:** `python -m pytest skyulf-core/tests/spark/test_inference_bundle.py -q` **Kabul:** Kayıt/yükleme, feature sırası ve raw/features giriş ayrımı doğrulanmış. +2026-09-21: SM-08 tamamlandı. Komutlar, runtime sonuçları ve kapsam sınırları +[tamamlanma kaydında](OPEN_QUEUE.md). Dağıtık inference kapısı G2 henüz kapanmadı. + ## SM-09 — Native Spark FE ardından Python model **Bağımlılık:** SM-08. **Oluştur:** `skyulf/inference/spark.py`, @@ -100,7 +109,7 @@ def test_native_path_matches_local(spark, raw_frame, regression_bundle): frame_spec=FrameSpec(row_keys=("id",)), options=ExecutionOptions(engine="spark", python_batch_rows=2), mode="native_features").toPandas().sort_values("id") - expected = predict_local(raw_frame.sort_values("id"), regression_bundle) + expected = predict_local(raw_frame.sort_values("id").drop(columns="id"), regression_bundle) np.testing.assert_allclose(actual["prediction"], expected["prediction"], rtol=1e-10) ``` diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 526824704..f6831aebf 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-00–SM-07 tamamlandı; sıradaki SM-08. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-00–SM-08 tamamlandı; sıradaki SM-09. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -17,8 +17,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-05 | Native SimpleImputer | SM-04 | DONE | Mean/constant train-only fit, Spark apply; aşağıda kanıt | | SM-06 | Native StandardScaler | SM-05 | DONE | Population variance, dört flag ve numeric parity; aşağıda kanıt | | SM-07 | Uçtan uca FE kapısı | SM-06 | DONE | Üç engine çapraz fit/apply; kayıt/yükleme; aşağıda kanıt | -| SM-08 | Ortak inference bundle | SM-07 | READY | Raw/features ayrımı; model metadata round-trip | -| SM-09 | Native FE + worker model | SM-08 | WAIT | Spark tahmini local ile key bazında aynı | +| SM-08 | Ortak inference bundle | SM-07 | DONE | Raw/features ayrımı; model metadata round-trip; aşağıda kanıt | +| SM-09 | Native FE + worker model | SM-08 | READY | Spark tahmini local ile key bazında aynı | | SM-10 | Worker Python FE + model | SM-09 | WAIT | Batch-safe pipeline; window gibi yollar açık ret | | SM-11 | Classification ve ölçek kapısı | SM-10 | WAIT | Class/proba/threshold parity; worker kanıtı | | SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | @@ -374,3 +374,68 @@ ve MLflow entegrasyonu henüz yok. → **1 passed, 1 warning**, 38.00 saniye; mevcut pandas fillna FutureWarning. - Sınır: G1 feature engineering içindir; model bundle/inference, MLflow, Databricks/Connect ve endpoint/template doğrulaması değildir. Sonraki görev SM-08. + +## SM-08 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `7099733c`; bu kayıt SM-08 çalışma ağacına aittir. +- `skyulf/inference/` public API: `build_bundle`, `save_bundle`, `load_bundle`, + `predict_local`, immutable `InferenceBundle`. Metadata ve payload bytes ayrı; + `raw` input'ta FE bir kez uygulanır, `features` doğrudan model tahminidir. + pandas/Polars girdisi; çıktı pandas prediction/probability kolonlarıdır. +- `SkyulfPipeline.fit` metadata-only `_inference_schemas` kaydeder: target hariç + raw input ve gerçek model training feature sırası/dtype'ları. Başarısız refit + temizler; raw frame tutulmaz. NumPy bridge'in kaybettiği kolon adları tahminle + doldurulmaz. Schema capture 31 gerçek frame/tuple/split/wrapper/tuning testiyle + korundu; mevcut pickle ve fingerprint davranışı değişmedi. +- Katı manifest: stage, input/model/output schema, class/probability sırası, + positive label, tuning ve explicit pipeline threshold provenance, sabit + dependency listesi ve digest'ler. pandas/Polars Boolean/bool eşleştirmesi açık. + Eksik/ekstra/tekrarlı/sırası yanlış veya dtype'ı farklı feature'lar reddedilir. +- Kayıt üç sabit isimli dosyadır: manifest.json, features.json, model.pkl. + Var olan hedefe yazılmaz. FE+manifest state bütçesi ile model wire bütçesi ayrı; + protokol-5 PickleBuffer byte sayımı ve explicit FE limitinin tüm çağrılara + aktarımı test edildi. Kaynak pipeline'ın sonraki mutasyonu paketi değiştirmez. +- Semantic digest pickle protokolüne bağlı değildir; ayrıca model/FE wire + checksum kontrolü yapılır. Pickle yalnız güvenilir üreticiden yüklenir. + Python major/minor ve skyulf-core/sklearn/NumPy/SciPy sürümleri yüklemeden + önce doğrulanır. pandas/Polars sürümleri provenance olarak kaydedilir. +- Ruling: local giriş yalnız feature kolonlarını kabul eder; id gibi ekstra + kolonlar otomatik elenmez. SM-09 runner key'leri model girişinden açıkça ayırır. + Fixture seed=17, iki farklı ölçekli x/z kolonu ve held-out satırlar içerir; + test dosyasında tutulur. Bu, plandaki tek x/id örneğine göre kolon sırası + hatasını da yakalar; SM-09 shared fixture'a ihtiyaç duyduğunda taşınabilir. +- Ruling: mevcut `core/serialization.py` provider'ı ve eski backend okuyucu + değiştirilmedi. Standalone adapter `SkyulfPipeline.load` → `build_bundle`; + schema bilgisi olmayan eski pickle yeniden fit gerektirir. Backend dict + doğrudan reddedilir, adapter SM-18'de. İlk FE desteği SM-07'nin node'ları; + split node yerine explicit SplitDataset ile training partitions verilebilir. +- Bağımsız review Polars Boolean alias'ını, 8 MiB üstü FE için custom budget + aktarımını ve büyük estimator protocol-5 PickleBuffer serialization hatasını + yeniden üretti. Red regresyonlardan sonra düzeltildi. Re-review: gerçek + 144 KB KNN bundle ve 8.39 MB FE / 16 MiB bütçe ile pandas+Polars inference geçti; + açık önemli bulgu kalmadı. KNN gibi modeller kendi state'lerinde örnek tutabilir; + schema capture'ın veri tutmaması estimator'ın bu davranışını değiştirmez. +- Dar testler: **76 passed, 2 skipped, 21 warnings**, 4.46 saniye. İki skip + Spark-local giriş reddi vakasıdır; gerçek Spark lane'inde ayrıca çalışır. +- `skyulf-core/examples/inference_bundle.py --bundle-dir .cache/sm08-example-model` + çalıştı: kayıt/yükleme sonrası **[40.0, 20.0]**, raw/features parity ve aynı + semantic digest. Ayrı base-process import kontrolü PySpark/MLflow yüklemedi. +- Yeni `docs/user_guide/inference_bundles.md`, Spark rehberi linki ve nav kaydı. + Rehberin Python örneği gerçek base ortamında **1 passed**, 2.08 saniye; + `mkdocs build --strict` başarılı. Ruff/format ve tam repo ty geçti. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm08-core-full` + → **10045 passed, 225 skipped, 1097 warnings**, 193.33 saniye. Base ortamda + PySpark yok; yeni gerçek Spark input-ret testleri burada iki skip'tir. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py + skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --tb=short + -o addopts= -p no:cacheprovider --basetemp .cache/sm08-spark-full` + → **339 passed, 2 warnings**, 340.64 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Sınır: bu görev local paketleme/inference içindir. Spark worker model runner + SM-09, ikinci Python FE yolu SM-10, dağıtık classification kapısı SM-11'dir. + MLflow, Databricks/Connect, endpoint ve template doğrulaması henüz yok. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index d0f90bd4f..93ccaea05 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-07 tamamlandı; sıradaki görev SM-08.** +Tarih: 2026-09-21. Durum: **SM-00–SM-08 tamamlandı; sıradaki görev SM-09.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-08**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-09**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/mkdocs.yml b/mkdocs.yml index 58d3688e7..f1dec0acc 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -74,6 +74,7 @@ nav: - Overview: user_guide/overview.md - Installation: user_guide/installation.md - Spark (Development): user_guide/spark.md + - Inference Bundles (Development): user_guide/inference_bundles.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/skyulf-core/examples/inference_bundle.py b/skyulf-core/examples/inference_bundle.py new file mode 100644 index 000000000..cf3085aab --- /dev/null +++ b/skyulf-core/examples/inference_bundle.py @@ -0,0 +1,63 @@ +"""Save and restore a standalone inference bundle, with no Spark or MLflow dependency.""" + +import argparse +from pathlib import Path +from tempfile import TemporaryDirectory + +import numpy as np +import pandas as pd + +from skyulf.data.dataset import SplitDataset +from skyulf.inference import build_bundle, load_bundle, predict_local, save_bundle +from skyulf.pipeline import SkyulfPipeline + + +def run_example(destination: Path) -> None: + """Compare raw and prepared-feature predictions before and after persistence.""" + training = pd.DataFrame({"amount": [1.0, 2.0, 3.0], "target": [10.0, 20.0, 30.0]}) + pipeline = SkyulfPipeline( + { + "preprocessing": [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["amount"]}}, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["amount"]}, + }, + ], + "modeling": {"type": "linear_regression"}, + } + ) + pipeline.fit(SplitDataset(train=training, test=training.head(0)), target_column="target") + raw = pd.DataFrame({"amount": [4.0, np.nan]}) + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("amount",)) + save_bundle(bundle, destination) + restored = load_bundle(destination) + result = predict_local(raw, restored) + prepared = pipeline.feature_engineer.transform(raw) + features_bundle = build_bundle(pipeline, input_stage="features", feature_order=("amount",)) + np.testing.assert_allclose(result.prediction, [40.0, 20.0], atol=1e-12) + np.testing.assert_allclose( + predict_local(prepared, features_bundle).prediction, result.prediction + ) + assert restored.semantic_digest == bundle.semantic_digest + print(f"Restored predictions: {result.prediction.to_list()}") + print(f"Bundle semantic digest: {bundle.semantic_digest}") + + +def main() -> None: + """Let the caller retain the artifact or use an isolated temporary example directory.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--bundle-dir", type=Path, help="New directory to create; existing paths are rejected." + ) + args = parser.parse_args() + if args.bundle_dir is not None: + run_example(args.bundle_dir) + else: + with TemporaryDirectory(prefix="skyulf-bundle-") as temporary: + run_example(Path(temporary) / "model") + + +if __name__ == "__main__": + main() diff --git a/skyulf-core/skyulf/inference/__init__.py b/skyulf-core/skyulf/inference/__init__.py new file mode 100644 index 000000000..7aacf02d1 --- /dev/null +++ b/skyulf-core/skyulf/inference/__init__.py @@ -0,0 +1,5 @@ +"""Standalone inference bundles; importing this package needs no Spark or MLflow.""" + +from .bundle import InferenceBundle, build_bundle, load_bundle, predict_local, save_bundle + +__all__ = ["InferenceBundle", "build_bundle", "load_bundle", "predict_local", "save_bundle"] diff --git a/skyulf-core/skyulf/inference/_manifest.py b/skyulf-core/skyulf/inference/_manifest.py new file mode 100644 index 000000000..d60e7efce --- /dev/null +++ b/skyulf-core/skyulf/inference/_manifest.py @@ -0,0 +1,202 @@ +"""Strict, immutable metadata for the initial standalone inference bundle.""" + +import hashlib +import json +import math +import platform +from importlib.metadata import version +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +from ..core.schema import SkyulfSchema +from ..pipeline.seal import artifact_digest + +Label = str | int | float | bool +_DTYPES = { + "bool", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float32", + "float64", +} +_PACKAGES = ("skyulf-core", "scikit-learn", "numpy", "scipy", "pandas", "polars") + + +class ColumnSpec(BaseModel): + """Describe one named scalar column without retaining any training rows.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + name: str = Field(min_length=1) + dtype: str + + +class ThresholdProvenance(BaseModel): + """Keep default tuning decisions distinct from explicit pipeline overrides.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + source: Literal["estimator", "tuning", "pipeline_override"] = "estimator" + values: tuple[float, ...] = () + tuning_values: tuple[float, ...] = () + pipeline_values: tuple[float, ...] = () + metric: str | None = None + + +class BundleManifest(BaseModel): + """Validate the declared input stage, schemas and payload identities.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + format_version: Literal[1] = 1 + input_stage: Literal["raw", "features"] + feature_order: tuple[str, ...] + input_schema: tuple[ColumnSpec, ...] + feature_schema: tuple[ColumnSpec, ...] + output_schema: tuple[ColumnSpec, ...] + task: Literal["regression", "classification"] + classes: tuple[Label, ...] = () + positive_label: Label | None = None + probability_columns: tuple[str, ...] = () + thresholds: ThresholdProvenance = ThresholdProvenance() + requirements: tuple[tuple[str, str], ...] + model_class: str + model_sha256: str + model_state_digest: str + fe_sha256: str + fe_semantic_digest: str + semantic_digest: str = "" + + @model_validator(mode="after") + def validate_contract(self) -> "BundleManifest": + """Reject internally inconsistent schemas and decision metadata before model loading.""" + for schema in (self.input_schema, self.feature_schema, self.output_schema): + names = tuple(col.name for col in schema) + if not names or len(names) != len(set(names)): + raise ValueError("Bundle schemas require distinct nonempty column names.") + if self.feature_order != tuple(col.name for col in self.feature_schema): + raise ValueError("feature_order must match feature_schema.") + if self.input_stage == "features" and self.input_schema != self.feature_schema: + raise ValueError("features input_schema must match feature_schema.") + if any(col.dtype not in _DTYPES for col in (*self.input_schema, *self.feature_schema)): + raise ValueError("Initial bundle inputs require primitive numeric or boolean dtypes.") + expected = ("prediction", *self.probability_columns) + if tuple(col.name for col in self.output_schema) != expected: + raise ValueError("Prediction schema and probability columns disagree.") + if self.task == "regression": + if self.classes or self.probability_columns or self.positive_label is not None: + raise ValueError("Regression cannot declare classes or probabilities.") + if self.output_schema[0].dtype != "float64": + raise ValueError("Regression prediction dtype must be float64.") + else: + if len(self.classes) < 2 or len(set(self.classes)) != len(self.classes): + raise ValueError("Classification requires distinct scalar classes.") + if self.probability_columns != tuple( + f"probability_{i}" for i in range(len(self.classes)) + ): + raise ValueError("Probability columns must follow class positions.") + if self.positive_label != (self.classes[1] if len(self.classes) == 2 else None): + raise ValueError("positive_label must follow the binary class convention.") + if self.output_schema[0].dtype != label_dtype(self.classes): + raise ValueError("Prediction dtype must match classes.") + if any(col.dtype != "float64" for col in self.output_schema[1:]): + raise ValueError("Probability columns require float64.") + self._validate_thresholds() + names = [name for name, _ in self.requirements] + if sorted(names) != sorted(("python", *_PACKAGES)): + raise ValueError("Requirements must contain exactly the supported runtime packages.") + return self + + def _validate_thresholds(self) -> None: + """Threshold arrays are class-ordered and must agree with their active source.""" + state = self.thresholds + for values in (state.values, state.tuning_values, state.pipeline_values): + if values and (len(values) != len(self.classes) or not self.classes): + raise ValueError("Threshold values must cover every class.") + minimum_ok = all( + value >= 0 if len(self.classes) == 2 else value > 0 for value in values + ) + if values and ( + not all(math.isfinite(value) for value in values) + or not minimum_ok + or not any(values) + ): + raise ValueError("Invalid decision thresholds.") + selected = { + "estimator": (), + "tuning": state.tuning_values, + "pipeline_override": state.pipeline_values, + }[state.source] + if state.values != selected or (state.source != "estimator" and not selected): + raise ValueError("Threshold provenance disagrees with the active decision rule.") + + +def schema_columns(schema: SkyulfSchema) -> tuple[ColumnSpec, ...]: + """Normalize equivalent pandas/Polars numeric labels without casting any input data.""" + return tuple( + ColumnSpec( + name=name, dtype=schema.dtypes.get(name, "unknown").lower().replace("boolean", "bool") + ) + for name in schema.columns + ) + + +def label_dtype(classes: tuple[Label, ...]) -> str: + """Keep one unambiguous scalar class type suitable for tabular prediction outputs.""" + kind = type(classes[0]) + if any(type(value) is not kind for value in classes): + raise ValueError("Class labels must share one scalar type.") + if any(isinstance(value, float) and not math.isfinite(value) for value in classes): + raise ValueError("Class labels must be finite.") + if any(isinstance(value, int) and not -(2**63) <= value < 2**63 for value in classes): + raise ValueError("Integer labels must fit int64.") + dtypes: dict[type, str] = {str: "string", int: "int64", float: "float64", bool: "bool"} + return dtypes[kind] + + +def runtime_requirements() -> tuple[tuple[str, str], ...]: + """Record package versions only; configuration, credentials and sessions are excluded.""" + return (("python", platform.python_version()), *((name, version(name)) for name in _PACKAGES)) + + +def check_runtime(manifest: BundleManifest) -> None: + """Require compatible Python and exact estimator dependency versions for pickle loading.""" + current = dict(runtime_requirements()) + for name, expected in manifest.requirements: + actual = current[name] + if name == "python": + compatible = actual.split(".")[:2] == expected.split(".")[:2] + elif name in {"skyulf-core", "scikit-learn", "numpy", "scipy"}: + compatible = actual == expected + else: + continue + if not compatible: + raise ValueError( + f"Bundle runtime mismatch for {name}: requires {expected}, found {actual}." + ) + + +def semantic_digest(manifest: BundleManifest) -> str: + """Hash semantic metadata and fitted model state independently of pickle wire encoding.""" + content = manifest.model_dump(exclude={"semantic_digest", "model_sha256", "fe_sha256"}) + return artifact_digest(content).hex() + + +def checksum(payload: bytes) -> str: + """Verify exact transported bytes independently of the semantic identity.""" + return hashlib.sha256(payload).hexdigest() + + +def manifest_bytes(manifest: BundleManifest) -> bytes: + """Encode deterministic, finite JSON metadata for storage and byte accounting.""" + return json.dumps( + manifest.model_dump(mode="json"), + sort_keys=True, + ensure_ascii=True, + allow_nan=False, + separators=(",", ":"), + ).encode("utf-8") diff --git a/skyulf-core/skyulf/inference/_model.py b/skyulf-core/skyulf/inference/_model.py new file mode 100644 index 000000000..cc007a1c9 --- /dev/null +++ b/skyulf-core/skyulf/inference/_model.py @@ -0,0 +1,117 @@ +"""Capture and restore only the supported standalone sklearn prediction contract.""" + +import io +import pickle # nosec B403 - explicit trusted model persistence +from typing import Any + +import numpy as np +from sklearn.base import BaseEstimator, is_classifier, is_regressor +from sklearn.utils.validation import check_is_fitted + +from ..modeling._tuning.engine import TuningApplier +from ..modeling.sklearn_wrapper import SklearnApplier +from ..pipeline import SkyulfPipeline +from ..pipeline.seal import artifact_digest +from ._manifest import BundleManifest, ThresholdProvenance + + +class _BoundedModelBuffer(io.BytesIO): + """Stop serialization when its wire output exceeds the configured estimator budget.""" + + def __init__(self, limit: int): + """Store the caller's validated byte limit.""" + super().__init__() + self.limit = limit + + def write(self, data: Any) -> int: + """Reject a pickle chunk before growing the output beyond the allowed budget.""" + if self.tell() + memoryview(data).nbytes > self.limit: + raise ValueError("Estimator payload exceeds model_max_bytes.") + return super().write(data) + + +def serialize_model(model: Any, limit: int) -> bytes: + """Freeze a fitted estimator independently of its mutable training pipeline.""" + output = _BoundedModelBuffer(limit) + pickle.dump(model, output, protocol=5) + return output.getvalue() + + +def validate_model(model: Any) -> None: + """Fail closed on custom, composite, multi-output or unsupported model semantics.""" + if not isinstance(model, BaseEstimator) or not type(model).__module__.startswith("sklearn."): + raise ValueError("Only standalone sklearn estimators are supported by this bundle version.") + if not (is_regressor(model) or is_classifier(model)): + raise ValueError("Only regression and classification estimators are supported.") + check_is_fitted(model) + if getattr(model, "n_outputs_", 1) != 1: + raise ValueError("Multi-output estimators are not supported.") + if is_classifier(model) and not callable(getattr(model, "predict_proba", None)): + raise ValueError("Classification bundles require predict_proba.") + + +def pipeline_model(pipeline: SkyulfPipeline) -> Any: + """Reject custom appliers whose prediction behavior would be lost by extracting a model.""" + estimator = pipeline.model_estimator + if estimator is None or estimator.model is None or pipeline._fit_metrics is None: + raise ValueError("A successfully fitted standalone model pipeline is required.") + applier = estimator.applier + if type(applier) is TuningApplier: + applier = applier.base_applier + if ( + type(applier).predict is not SklearnApplier.predict + or type(applier).predict_proba is not SklearnApplier.predict_proba + ): + raise ValueError("Custom model appliers require an explicit inference adapter.") + model = estimator._unwrap_tuned_model() + validate_model(model) + return model + + +def threshold_provenance( + pipeline: SkyulfPipeline, classes: tuple, enabled: bool +) -> ThresholdProvenance: + """Preserve tuning defaults and the opt-in pipeline threshold override separately.""" + estimator = pipeline.model_estimator + assert estimator is not None + artifact = estimator.model + tuning = artifact[1] if isinstance(artifact, tuple) else None + tuned = getattr(tuning, "decision_thresholds", None) + saved = pipeline._tuned_thresholds + if enabled and saved is None: + raise ValueError("use_tuned_thresholds requires saved pipeline thresholds.") + + def values(mapping: dict | None) -> tuple[float, ...]: + """Align threshold labels explicitly to the model's probability column order.""" + if mapping is None: + return () + if not classes or set(mapping) != set(classes): + raise ValueError("Threshold keys must match model classes.") + return tuple(float(mapping[label]) for label in classes) + + tuning_values, pipeline_values = values(tuned), values(saved) + source = "pipeline_override" if enabled else "tuning" if tuned is not None else "estimator" + active = pipeline_values if enabled else tuning_values + return ThresholdProvenance( + source=source, + values=active, + tuning_values=tuning_values, + pipeline_values=pipeline_values, + metric=getattr(tuning, "decision_threshold_metric", None), + ) + + +def load_model(payload: bytes, manifest: BundleManifest) -> Any: + """Load a trusted, checksum-validated pickle and cross-check its fitted metadata.""" + model = pickle.loads(payload) # nosec B301 - caller must trust the producer; checksum is not authentication + validate_model(model) + if f"{type(model).__module__}.{type(model).__qualname__}" != manifest.model_class: + raise ValueError("Model class disagrees with manifest.") + if artifact_digest(model).hex() != manifest.model_state_digest: + raise ValueError("Model semantic digest mismatch.") + if int(model.n_features_in_) != len(manifest.feature_order): + raise ValueError("Model feature width disagrees with manifest.") + classes = tuple(np.asarray(model.classes_).tolist()) if is_classifier(model) else () + if classes != manifest.classes or is_classifier(model) != (manifest.task == "classification"): + raise ValueError("Model classes/task disagree with manifest.") + return model diff --git a/skyulf-core/skyulf/inference/_storage.py b/skyulf-core/skyulf/inference/_storage.py new file mode 100644 index 000000000..0765fc3eb --- /dev/null +++ b/skyulf-core/skyulf/inference/_storage.py @@ -0,0 +1,50 @@ +"""Explicit local bundle I/O, separate from computation and legacy serializers.""" + +import json +from pathlib import Path + +from ..core.execution import ExecutionOptions +from ..core.portable_state import _bad_constant, _unique_object +from ._manifest import BundleManifest + + +def write_payloads(path: str | Path, metadata: bytes, features: bytes, model: bytes) -> None: + """Publish three fixed-name files into a new caller-selected directory.""" + destination = Path(path) + destination.mkdir(parents=True, exist_ok=False) + for name, content in ( + ("manifest.json", metadata), + ("features.json", features), + ("model.pkl", model), + ): + with (destination / name).open("xb") as stream: + stream.write(content) + + +def _read_bounded(path: Path, limit: int, label: str) -> bytes: + """Read at most one byte beyond the wire budget, rejecting larger payloads.""" + with path.open("rb") as stream: + payload = stream.read(limit + 1) + if len(payload) > limit: + raise ValueError(f"Bundle {path.name} exceeds {label}.") + return payload + + +def read_payloads( + path: str | Path, options: ExecutionOptions +) -> tuple[BundleManifest, bytes, bytes]: + """Validate metadata before reading model bytes or invoking the trusted pickle loader.""" + source = Path(path) + metadata = _read_bounded(source / "manifest.json", options.state_max_bytes, "state_max_bytes") + document = json.loads( + metadata.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_bad_constant + ) + if type(document) is not dict or type(document.get("format_version")) is not int: + raise ValueError("Invalid bundle manifest format_version.") + manifest = BundleManifest.model_validate_json(metadata) + state_limit = options.state_max_bytes - len(metadata) + if state_limit <= 0: + raise ValueError("Bundle metadata leaves no state_max_bytes budget for FE.") + features = _read_bounded(source / "features.json", state_limit, "state_max_bytes") + model = _read_bounded(source / "model.pkl", options.model_max_bytes, "model_max_bytes") + return manifest, features, model diff --git a/skyulf-core/skyulf/inference/bundle.py b/skyulf-core/skyulf/inference/bundle.py new file mode 100644 index 000000000..df718f5fc --- /dev/null +++ b/skyulf-core/skyulf/inference/bundle.py @@ -0,0 +1,271 @@ +"""Explicit standalone model bundles with raw/features inference contracts. + +Estimator payloads use pickle and must come from a trusted producer. Checksums +detect corruption; they do not authenticate a producer or make pickle safe. +""" + +import json +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import polars as pl +from sklearn.base import is_classifier + +from ..core.execution import ExecutionOptions +from ..core.schema import SkyulfSchema +from ..engines.pandas_engine import SkyulfPandasWrapper +from ..engines.polars_engine import SkyulfPolarsWrapper +from ..engines.sklearn_bridge import SklearnBridge +from ..engines.spark_engine import is_spark_input +from ..modeling._evaluation.thresholds import apply_thresholds +from ..pipeline import SkyulfPipeline +from ..pipeline.seal import artifact_digest +from ..preprocessing._feature_state import export_feature_state +from ..preprocessing.pipeline import FeatureEngineer +from ._manifest import ( + BundleManifest, + ColumnSpec, + check_runtime, + checksum, + label_dtype, + manifest_bytes, + runtime_requirements, + schema_columns, + semantic_digest, +) +from ._model import load_model, pipeline_model, serialize_model, threshold_provenance +from ._storage import read_payloads, write_payloads + + +@dataclass(frozen=True) +class InferenceBundle: + """Frozen metadata and payload bytes, without a live estimator, session or connection.""" + + manifest: BundleManifest + feature_state: bytes + model_payload: bytes + + @property + def input_stage(self) -> str: + """Expose whether the consumer supplies raw or already transformed features.""" + return self.manifest.input_stage + + @property + def feature_order(self) -> tuple[str, ...]: + """Expose the exact feature positions used during model training.""" + return self.manifest.feature_order + + @property + def probability_columns(self) -> tuple[str, ...]: + """Expose probability names in the same order as model classes.""" + return self.manifest.probability_columns + + @property + def classes(self) -> tuple: + """Expose original scalar class labels without converting them to column names.""" + return self.manifest.classes + + @property + def positive_label(self) -> Any: + """Expose the binary probability convention, or None for other tasks.""" + return self.manifest.positive_label + + @property + def semantic_digest(self) -> str: + """Expose content identity independently of estimator pickle protocol.""" + return self.manifest.semantic_digest + + +def build_bundle( + pipeline: SkyulfPipeline, + *, + input_stage: str, + feature_order: tuple[str, ...], + options: ExecutionOptions | None = None, + use_tuned_thresholds: bool = False, +) -> InferenceBundle: + """Freeze a supported fitted standalone pipeline without refitting or retaining data. + + The requested order must match recorded model training columns. Raw input + applies FE once; features input bypasses it. Tuning thresholds keep their + existing default behavior; pipeline thresholds require explicit opt-in. + Legacy artifacts without recorded schemas require a new successful fit. + """ + if type(pipeline) is not SkyulfPipeline: + raise TypeError("build_bundle requires a fitted standalone SkyulfPipeline.") + if input_stage not in ("raw", "features") or type(use_tuned_thresholds) is not bool: + raise ValueError("Invalid input_stage or use_tuned_thresholds.") + budget = _options(options) + model = pipeline_model(pipeline) + schemas = getattr(pipeline, "_inference_schemas", None) + if schemas is None: + raise ValueError("Missing fitted input schemas; refit this legacy standalone pipeline.") + raw_schema, feature_schema = (schema_columns(schema) for schema in schemas) + if type(feature_order) is not tuple or feature_order != tuple( + col.name for col in feature_schema + ): + raise ValueError("feature_order must match the actual model training order.") + if len(feature_order) != int(model.n_features_in_): + raise ValueError("Recorded model feature width is inconsistent.") + feature_state = export_feature_state(pipeline.feature_engineer, options=budget) + if len(feature_state) > budget.state_max_bytes: + raise ValueError("Feature state exceeds state_max_bytes.") + payload = serialize_model(model, budget.model_max_bytes) + classification = is_classifier(model) + classes = tuple(np.asarray(model.classes_).tolist()) if classification else () + probabilities = tuple(f"probability_{i}" for i in range(len(classes))) + output = ( + ColumnSpec(name="prediction", dtype=label_dtype(classes) if classification else "float64"), + *(ColumnSpec(name=name, dtype="float64") for name in probabilities), + ) + manifest = BundleManifest( + input_stage=input_stage, + feature_order=feature_order, + input_schema=raw_schema if input_stage == "raw" else feature_schema, + feature_schema=feature_schema, + output_schema=output, + task="classification" if classification else "regression", + classes=classes, + positive_label=classes[1] if len(classes) == 2 else None, + probability_columns=probabilities, + thresholds=threshold_provenance(pipeline, classes, use_tuned_thresholds), + requirements=runtime_requirements(), + model_class=f"{type(model).__module__}.{type(model).__qualname__}", + model_sha256=checksum(payload), + model_state_digest=artifact_digest(model).hex(), + fe_sha256=checksum(feature_state), + fe_semantic_digest=json.loads(feature_state)["semantic_digest"], + ) + manifest = manifest.model_copy(update={"semantic_digest": semantic_digest(manifest)}) + bundle = InferenceBundle(manifest, feature_state, payload) + _validate_bundle(bundle, budget) + return bundle + + +def _options(options: ExecutionOptions | None) -> ExecutionOptions: + """Use existing immutable byte budgets without implicitly selecting a runtime.""" + if options is not None and not isinstance(options, ExecutionOptions): + raise TypeError("options must be ExecutionOptions.") + return options if options is not None else ExecutionOptions("pandas") + + +def _validate_bundle(bundle: InferenceBundle, options: ExecutionOptions) -> None: + """Check all metadata and byte identities before any estimator deserialization.""" + if not isinstance(bundle, InferenceBundle): + raise TypeError("Expected InferenceBundle.") + manifest = BundleManifest.model_validate_json(manifest_bytes(bundle.manifest)) + if len(manifest_bytes(manifest)) + len(bundle.feature_state) > options.state_max_bytes: + raise ValueError("Bundle metadata and FE exceed state_max_bytes.") + if len(bundle.model_payload) > options.model_max_bytes: + raise ValueError("Estimator payload exceeds model_max_bytes.") + if ( + checksum(bundle.model_payload) != manifest.model_sha256 + or checksum(bundle.feature_state) != manifest.fe_sha256 + ): + raise ValueError("Bundle payload checksum mismatch.") + if semantic_digest(manifest) != manifest.semantic_digest: + raise ValueError("Bundle semantic digest mismatch.") + FeatureEngineer.from_state( + bundle.feature_state, + execution_options=ExecutionOptions("pandas", state_max_bytes=options.state_max_bytes), + ) + if json.loads(bundle.feature_state)["semantic_digest"] != manifest.fe_semantic_digest: + raise ValueError("Feature state semantic digest mismatch.") + check_runtime(manifest) + + +def _validate_frame(frame: Any, expected: tuple[ColumnSpec, ...], where: str) -> None: + """Require names, positions and normalized dtypes; never silently reorder or cast.""" + actual = schema_columns(SkyulfSchema.from_dataframe(frame)) + if len(frame.columns) != len(set(frame.columns)): + raise ValueError("Duplicate input columns are not supported.") + wanted = SkyulfSchema( + tuple(col.name for col in expected), {col.name: col.dtype for col in expected} + ) + observed = SkyulfSchema( + tuple(col.name for col in actual), {col.name: col.dtype for col in actual} + ) + wanted.assert_compatible(observed, check_dtypes=True, check_order=True, where=where) + + +def predict_local( + frame: Any, bundle: InferenceBundle, *, options: ExecutionOptions | None = None +) -> pd.DataFrame: + """Predict from a local pandas/Polars frame using exactly the declared input stage. + + Supply feature columns only, in the recorded order and dtypes. Extra IDs or + targets are rejected; the output preserves a pandas input index. Spark + frames require the separate distributed runner and are never collected. + """ + if is_spark_input(frame): + raise TypeError("predict_local rejects Spark input; use the distributed inference runner.") + if isinstance(frame, SkyulfPandasWrapper | SkyulfPolarsWrapper): + frame = frame.to_native() + if not isinstance(frame, pd.DataFrame | pl.DataFrame): + raise TypeError("predict_local requires a pandas or Polars DataFrame.") + budget = _options(options) + _validate_bundle(bundle, budget) + manifest = bundle.manifest + _validate_frame(frame, manifest.input_schema, "bundle input") + features = frame + if bundle.input_stage == "raw": + local_options = replace( + budget, engine="polars" if isinstance(frame, pl.DataFrame) else "pandas" + ) + features = FeatureEngineer.from_state( + bundle.feature_state, execution_options=local_options + ).transform(frame, preserve_rows=True) + _validate_frame(features, manifest.feature_schema, "model features") + index = frame.index if isinstance(frame, pd.DataFrame) else pd.RangeIndex(len(frame)) + if len(frame) == 0: + return pd.DataFrame( + {col.name: pd.Series(index=index, dtype=col.dtype) for col in manifest.output_schema} + ) + model = load_model(bundle.model_payload, manifest) + values, _ = SklearnBridge.to_sklearn(features, validate_features=True) + probabilities = None + if manifest.task == "classification": + probabilities = np.asarray(model.predict_proba(values)) + if probabilities.shape != (len(frame), len(bundle.classes)): + raise ValueError("Model probability shape violates the bundle contract.") + if manifest.thresholds.values: + thresholds = dict(zip(bundle.classes, manifest.thresholds.values, strict=True)) + predictions = apply_thresholds(probabilities, thresholds, classes=bundle.classes) + else: + predictions = np.asarray(model.predict(values)) + if predictions.shape != (len(frame),): + raise ValueError("Model prediction shape violates the bundle contract.") + output = pd.DataFrame( + {"prediction": pd.Series(predictions, index=index, dtype=manifest.output_schema[0].dtype)} + ) + if probabilities is not None: + for position, name in enumerate(bundle.probability_columns): + output[name] = probabilities[:, position] + return output + + +def save_bundle( + bundle: InferenceBundle, path: str | Path, *, options: ExecutionOptions | None = None +) -> None: + """Write a new bundle directory; refuse to overwrite an existing path.""" + _validate_bundle(bundle, _options(options)) + write_payloads( + path, manifest_bytes(bundle.manifest), bundle.feature_state, bundle.model_payload + ) + + +def load_bundle(path: str | Path, *, options: ExecutionOptions | None = None) -> InferenceBundle: + """Load a trusted bundle directory after size, schema, checksum and runtime checks. + + This operation deserializes pickle. Only load bundles from trusted producers; + checksum verification is not an authentication mechanism. + """ + budget = _options(options) + manifest, features, model = read_payloads(path, budget) + bundle = InferenceBundle(manifest, features, model) + _validate_bundle(bundle, budget) + load_model(model, manifest) + return bundle diff --git a/skyulf-core/skyulf/pipeline/_pipeline.py b/skyulf-core/skyulf/pipeline/_pipeline.py index ea23dd880..16f6e4ca1 100644 --- a/skyulf-core/skyulf/pipeline/_pipeline.py +++ b/skyulf-core/skyulf/pipeline/_pipeline.py @@ -13,6 +13,7 @@ import polars as pl from ..config_validation import validate_pipeline_config +from ..core.schema import SkyulfSchema from ..core.validation import prediction_row_count, validate_prediction_rows from ..data.dataset import SplitDataset from ..engines import SkyulfDataFrame, get_engine @@ -143,6 +144,7 @@ def __init__(self, config: PipelineConfig | dict[str, Any]): self._fit_metrics: dict[str, Any] | None = None self._target_column: str | None = None self._tuned_thresholds: dict[Any, float] | None = None + self._inference_schemas: tuple[SkyulfSchema, SkyulfSchema] | None = None # Initialize model estimator if config is present if self.modeling_config: @@ -339,6 +341,7 @@ def fit( self._fit_metrics = None self._target_column = None self._tuned_thresholds = None + self._inference_schemas = None if self.model_estimator is not None: self.model_estimator.model = None try: @@ -359,6 +362,11 @@ def _fit( ) -> dict[str, Any]: """Fit validated data, publishing metadata only after all stages complete.""" metrics = {} + input_schema = None + if self.model_estimator is not None: + raw_train = data.train if isinstance(data, SplitDataset) else data + raw_features = raw_train[0] if isinstance(raw_train, tuple) else raw_train + input_schema = SkyulfSchema.from_dataframe(raw_features).drop((target_column,)) # 1. Feature Engineering logger.info("Starting Feature Engineering...") @@ -389,6 +397,10 @@ def _fit( empty_df = engine.create_dataframe({}) dataset = SplitDataset(train=transformed_data, test=empty_df, validation=None) + # Observe the actual training representation before sklearn loses + # its column names. Schemas contain metadata only, never samples. + model_schema = SkyulfSchema.from_dataframe(extract_xy(dataset.train, target_column)[0]) + # Fit the model # Note: fit_predict updates self.model_estimator.model in-memory if not is_tuning: @@ -409,6 +421,9 @@ def _fit( logger.warning(f"Evaluation failed: {e}") metrics["modeling_error"] = str(e) + if self.model_estimator.model is not None and input_schema is not None: + self._inference_schemas = (input_schema, model_schema) + self._fit_metrics = metrics self._target_column = target_column return metrics diff --git a/skyulf-core/skyulf/preprocessing/_feature_state.py b/skyulf-core/skyulf/preprocessing/_feature_state.py index 10b99c9be..621468611 100644 --- a/skyulf-core/skyulf/preprocessing/_feature_state.py +++ b/skyulf-core/skyulf/preprocessing/_feature_state.py @@ -12,7 +12,7 @@ _APPLIERS = {"SimpleImputer": SimpleImputerApplier, "StandardScaler": StandardScalerApplier} -def export_feature_state(engineer: Any) -> bytes: +def export_feature_state(engineer: Any, *, options: ExecutionOptions | None = None) -> bytes: """Reject incomplete or unsupported execution histories before serializing learned state.""" if not getattr(engineer, "_portable_fitted", bool(engineer.fitted_steps)): raise ValueError("FeatureEngineer must be successfully fitted before exporting state.") @@ -24,7 +24,8 @@ def export_feature_state(engineer: Any) -> bytes: if node not in _APPLIERS or type(record["applier"]) is not _APPLIERS[node]: raise ValueError("Unsupported portable pipeline node or custom applier.") records.append({**record, "params": record.get("params", config.get("params", {}))}) - return encode_pipeline(records, max_bytes=_budget(getattr(engineer, "execution_options", None))) + budget = options if options is not None else getattr(engineer, "execution_options", None) + return encode_pipeline(records, max_bytes=_budget(budget)) def restore_feature_state( diff --git a/skyulf-core/tests/spark/test_inference_bundle.py b/skyulf-core/tests/spark/test_inference_bundle.py new file mode 100644 index 000000000..f6485302b --- /dev/null +++ b/skyulf-core/tests/spark/test_inference_bundle.py @@ -0,0 +1,386 @@ +"""A model bundle must preserve inference semantics and reject ambiguous input.""" + +import json +import pickle +from dataclasses import replace +from typing import Any, cast + +import numpy as np +import pandas as pd +import polars as pl +import pytest +from sklearn.metrics import accuracy_score + +from skyulf.core.execution import ExecutionOptions +from skyulf.core.schema import SchemaMismatchError +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle, load_bundle, predict_local, save_bundle +from skyulf.pipeline import SkyulfPipeline +from skyulf.preprocessing import _feature_state + + +@pytest.fixture(params=["pandas", "polars"]) +def fitted_regression_pipeline(request): + """Different feature scales expose swapped columns and accidental double preprocessing.""" + rng = np.random.default_rng(17) + frame = pd.DataFrame({"x": rng.normal(100, 20, 40), "z": rng.normal(5, 2, 40)}) + frame["target"] = 2 * frame.x - 3 * frame.z + 7 + pipeline = SkyulfPipeline( + { + "preprocessing": [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x", "z"]}}, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["x", "z"]}, + }, + ], + "modeling": {"type": "linear_regression"}, + } + ) + data = pl.from_pandas(frame) if request.param == "polars" else frame + pipeline.fit(SplitDataset(train=data, test=data.head(0)), target_column="target") + return pipeline + + +@pytest.fixture +def raw_frame(): + """Held-out values and a nondefault index expose re-fitting and row misalignment.""" + return pd.DataFrame({"x": [150.0, 80.0], "z": [9.0, 3.0]}, index=[17, 4]) + + +@pytest.mark.parametrize("stage", ["raw", "features"]) +def test_round_trip_preserves_predictions(fitted_regression_pipeline, raw_frame, tmp_path, stage): + """Loading must preserve the same prediction function without applying FE twice.""" + pipeline = fitted_regression_pipeline + bundle = build_bundle(pipeline, input_stage=stage, feature_order=("x", "z")) + frame = raw_frame if stage == "raw" else pipeline.feature_engineer.transform(raw_frame) + before = predict_local(frame, bundle) + save_bundle(bundle, tmp_path / "model") + restored = load_bundle(tmp_path / "model") + after = predict_local(frame, restored) + np.testing.assert_allclose(after.prediction, [280.0, 158.0], rtol=1e-10, atol=1e-12) + pd.testing.assert_frame_equal(before, after) + assert after.index.tolist() == [17, 4] + assert restored.semantic_digest == bundle.semantic_digest + assert restored.probability_columns == () + + +def test_polars_apply_and_empty_input(fitted_regression_pipeline, raw_frame): + """Local engine changes and empty batches must retain the declared output schema.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + out = predict_local(pl.from_pandas(raw_frame), bundle) + np.testing.assert_allclose(out.prediction, [280.0, 158.0]) + empty = predict_local(raw_frame.head(0), bundle) + assert empty.empty and list(empty.columns) == ["prediction"] + assert str(empty.prediction.dtype) == "float64" + + +@pytest.mark.parametrize("change", ["reorder", "missing", "extra", "dtype", "duplicate"]) +def test_input_contract_fails_closed(fitted_regression_pipeline, raw_frame, change): + """Names alone cannot protect NumPy model inputs from order or dtype mistakes.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + frame = { + "reorder": lambda: raw_frame[["z", "x"]], + "missing": lambda: raw_frame[["x"]], + "extra": lambda: raw_frame.assign(id=[1, 2]), + "dtype": lambda: raw_frame.assign(x=raw_frame.x.astype(str)), + "duplicate": lambda: pd.concat([raw_frame, raw_frame[["x"]]], axis=1), + }[change]() + with pytest.raises((SchemaMismatchError, ValueError)): + predict_local(frame, bundle) + + +def test_feature_order_must_match_actual_training_order(fitted_regression_pipeline): + """An explicit manifest cannot redefine the feature positions learned by the model.""" + with pytest.raises(ValueError, match="feature_order"): + build_bundle(fitted_regression_pipeline, input_stage="features", feature_order=("z", "x")) + + +def test_model_budget_is_enforced_before_unpickling( + fitted_regression_pipeline, tmp_path, monkeypatch +): + """Oversized estimators must never reach deserialization even with valid checksums.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + limit = len(bundle.model_payload) - 1 + with pytest.raises(ValueError, match="model_max_bytes"): + build_bundle( + fitted_regression_pipeline, + input_stage="raw", + feature_order=("x", "z"), + options=ExecutionOptions("pandas", model_max_bytes=limit), + ) + save_bundle(bundle, tmp_path / "model") + + def forbidden(*args, **kwargs): + """A bounded load failure must happen before executing the pickle loader.""" + pytest.fail("Deserialized an oversized model") + + monkeypatch.setattr(pickle, "loads", forbidden) + with pytest.raises(ValueError, match="model_max_bytes"): + load_bundle(tmp_path / "model", options=ExecutionOptions("pandas", model_max_bytes=limit)) + + +@pytest.mark.parametrize("part", ["manifest", "model", "features"]) +def test_corruption_is_rejected_before_deserialization( + fitted_regression_pipeline, tmp_path, monkeypatch, part +): + """Corrupt metadata or either payload must not become an executable bundle.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + path = tmp_path / "model" + save_bundle(bundle, path) + if part == "manifest": + manifest = json.loads((path / "manifest.json").read_bytes()) + manifest["format_version"] = 999 + (path / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + else: + target = path / ("model.pkl" if part == "model" else "features.json") + target.write_bytes(target.read_bytes() + b"corrupt") + + def forbidden(*args, **kwargs): + """Untrusted bytes must pass all structural and checksum gates first.""" + pytest.fail("Deserialized corrupt bundle") + + monkeypatch.setattr(pickle, "loads", forbidden) + with pytest.raises(ValueError): + load_bundle(path) + + +def test_bundle_freezes_source_and_preserves_legacy_pickle( + fitted_regression_pipeline, raw_frame, tmp_path +): + """A later training-object mutation cannot silently change an already built package.""" + pipeline = fitted_regression_pipeline + pipeline.save(str(tmp_path / "legacy.pkl")) + legacy = SkyulfPipeline.load(str(tmp_path / "legacy.pkl")) + bundle = build_bundle(legacy, input_stage="raw", feature_order=("x", "z")) + assert pipeline.model_estimator is not None + pipeline.model_estimator.model.coef_[:] = 0 + np.testing.assert_allclose(predict_local(raw_frame, bundle).prediction, [280.0, 158.0]) + with pytest.raises(TypeError, match="standalone"): + build_bundle(cast(Any, {"model": legacy}), input_stage="raw", feature_order=("x", "z")) + + +def test_manifest_and_payload_disagreement_rejected(fitted_regression_pipeline, raw_frame): + """Frozen metadata cannot be paired with a different model or preprocessing payload.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + with pytest.raises(ValueError, match="checksum"): + predict_local(raw_frame, replace(bundle, model_payload=b"other")) + + +def test_class_order_and_opt_in_thresholds_round_trip(tmp_path): + """Default model decisions and explicit pipeline thresholds must remain distinct.""" + frame = pd.DataFrame({"x": np.linspace(-3, 3, 30)}) + frame["label"] = np.where(frame.x > 0, "yes", "no") + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=frame, test=frame.head(0)), target_column="label") + query = pd.DataFrame({"x": [-0.1, 0.1, 2.0]}) + pipeline.optimize_thresholds( + query, np.array(["no", "no", "yes"]), accuracy_score, grid_points=5 + ) + for enabled in (False, True): + bundle = build_bundle( + pipeline, input_stage="raw", feature_order=("x",), use_tuned_thresholds=enabled + ) + path = tmp_path / str(enabled) + save_bundle(bundle, path) + restored = load_bundle(path) + out = predict_local(query, restored) + np.testing.assert_array_equal( + out.prediction, pipeline.predict(query, use_tuned_thresholds=enabled) + ) + assert pipeline.model_estimator is not None + assert pipeline.model_estimator.model is not None + np.testing.assert_allclose( + out[list(restored.probability_columns)], + pipeline.model_estimator.model.predict_proba(query.to_numpy()), + ) + assert restored.classes == ("no", "yes") and restored.positive_label == "yes" + assert tuple(out.columns) == ("prediction", *restored.probability_columns) + + +def test_boolean_input_schema_crosses_local_engines(): + """Polars Boolean and pandas bool represent the same supported primitive feature type.""" + data = pl.DataFrame({"flag": [True, False, True, False], "target": [3.0, 1.0, 3.0, 1.0]}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=data, test=data.head(0)), target_column="target") + bundle = build_bundle(pipeline, input_stage="features", feature_order=("flag",)) + out = predict_local(pd.DataFrame({"flag": [False, True]}), bundle) + np.testing.assert_allclose(out.prediction, [1.0, 3.0]) + + +def test_tuning_thresholds_remain_default_after_packaging(tmp_path): + """Extracting the tuned estimator must not lose the tuner's active decision rule.""" + frame = pd.DataFrame({"x": np.linspace(-3, 3, 36)}) + frame["label"] = np.where(frame.x > 0, 2, 1) + pipeline = SkyulfPipeline( + { + "preprocessing": [], + "modeling": { + "type": "hyperparameter_tuner", + "base_model": {"type": "logistic_regression"}, + "strategy": "grid", + "metric": "accuracy", + "search_space": {"C": [1.0]}, + "cv_folds": 2, + "n_jobs": 1, + "tune_threshold": True, + }, + } + ) + pipeline.fit( + SplitDataset(train=frame, test=frame.head(0), validation=frame.iloc[::2]), + target_column="label", + ) + query = pd.DataFrame({"x": [-0.2, 0.2, 2.0]}) + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + save_bundle(bundle, tmp_path / "tuned") + restored = load_bundle(tmp_path / "tuned") + assert restored.manifest.thresholds.source == "tuning" + np.testing.assert_array_equal( + predict_local(query, restored).prediction, pipeline.predict(query) + ) + + +def test_legacy_schema_missing_and_existing_destination_rejected( + fitted_regression_pipeline, tmp_path +): + """Existing files remain untouched and unnamed historical model inputs are never guessed.""" + pipeline = fitted_regression_pipeline + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + save_bundle(bundle, tmp_path / "model") + original = (tmp_path / "model" / "model.pkl").read_bytes() + with pytest.raises(FileExistsError): + save_bundle(bundle, tmp_path / "model") + assert (tmp_path / "model" / "model.pkl").read_bytes() == original + del pipeline._inference_schemas + with pytest.raises(ValueError, match="refit"): + build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + + +def test_manifest_corruption_and_runtime_mismatch_before_pickle( + fitted_regression_pipeline, tmp_path, monkeypatch +): + """Valid JSON with changed semantics or incompatible dependencies cannot reach pickle.""" + from skyulf.inference._manifest import semantic_digest + + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + path = tmp_path / "model" + save_bundle(bundle, path) + changed = bundle.manifest.model_copy(update={"input_stage": "features"}) + with pytest.raises(ValueError, match="digest"): + predict_local(pd.DataFrame({"x": [0.0], "z": [0.0]}), replace(bundle, manifest=changed)) + requirements = tuple( + (name, "0.0.0" if name == "scikit-learn" else value) + for name, value in bundle.manifest.requirements + ) + changed = bundle.manifest.model_copy(update={"requirements": requirements}) + changed = changed.model_copy(update={"semantic_digest": semantic_digest(changed)}) + (path / "manifest.json").write_text(changed.model_dump_json(), encoding="utf-8") + + def forbidden(*args, **kwargs): + """Version checks must precede execution of even checksum-valid pickle bytes.""" + pytest.fail("Loaded incompatible model") + + monkeypatch.setattr(pickle, "loads", forbidden) + with pytest.raises(ValueError, match="runtime mismatch"): + load_bundle(path) + + +def test_metadata_and_fe_share_one_byte_budget(fitted_regression_pipeline): + """Independent small components must not bypass a combined state budget.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + with pytest.raises(ValueError, match="state_max_bytes"): + build_bundle( + fitted_regression_pipeline, + input_stage="raw", + feature_order=("x", "z"), + options=ExecutionOptions("pandas", state_max_bytes=len(bundle.feature_state)), + ) + + +def test_bundle_identity_ignores_pickle_protocol(fitted_regression_pipeline, tmp_path): + """Wire checksums may change without changing learned model or pipeline semantics.""" + from skyulf.inference._manifest import checksum + + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + payload = pickle.dumps(pickle.loads(bundle.model_payload), protocol=4) + changed = replace( + bundle, + model_payload=payload, + manifest=bundle.manifest.model_copy(update={"model_sha256": checksum(payload)}), + ) + save_bundle(changed, tmp_path / "protocol4") + loaded = load_bundle(tmp_path / "protocol4") + assert loaded.semantic_digest == bundle.semantic_digest + np.testing.assert_allclose( + predict_local(pd.DataFrame({"x": [150.0], "z": [9.0]}), loaded).prediction, [280.0] + ) + + +def test_explicit_state_budget_reaches_export_and_raw_apply( + fitted_regression_pipeline, raw_frame, monkeypatch +): + """Every FE operation must use the bundle caller's budget rather than reverting to defaults.""" + monkeypatch.setattr(_feature_state, "DEFAULT_MAX_STATE_BYTES", 128) + options = ExecutionOptions("pandas", state_max_bytes=64 * 1024) + bundle = build_bundle( + fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z"), options=options + ) + np.testing.assert_allclose( + predict_local(raw_frame, bundle, options=options).prediction, [280.0, 158.0] + ) + np.testing.assert_allclose( + predict_local(pl.from_pandas(raw_frame), bundle, options=options).prediction, [280.0, 158.0] + ) + + +def test_large_protocol_five_array_serializes_with_real_byte_budget(): + """Protocol-five PickleBuffer chunks must work and be measured in bytes, not elements.""" + from skyulf.inference._model import serialize_model + + array = np.arange(100000, dtype=np.float64) + payload = serialize_model(array, array.nbytes + 4096) + np.testing.assert_array_equal(pickle.loads(payload), array) + with pytest.raises(ValueError, match="model_max_bytes"): + serialize_model(array, array.nbytes - 1) + + +def test_large_fitted_knn_bundle_round_trip(tmp_path): + """Real fitted models with large NumPy buffers must survive public bundle persistence.""" + rng = np.random.default_rng(17) + frame = pd.DataFrame(rng.normal(size=(512, 20)), columns=[f"x{i}" for i in range(20)]) + columns = tuple(frame.columns) + frame["target"] = np.arange(len(frame), dtype=float) + pipeline = SkyulfPipeline( + { + "preprocessing": [], + "modeling": { + "type": "k_neighbors_regressor", + "params": {"n_neighbors": 1, "algorithm": "brute"}, + }, + } + ) + pipeline.fit(SplitDataset(train=frame, test=frame.head(0)), target_column="target") + bundle = build_bundle(pipeline, input_stage="features", feature_order=columns) + save_bundle(bundle, tmp_path / "knn") + output = predict_local(frame[list(columns)].head(3), load_bundle(tmp_path / "knn")) + np.testing.assert_allclose(output.prediction, [0.0, 1.0, 2.0]) + assert len(bundle.model_payload) > 65536 + + +def test_spark_input_is_rejected_without_driver_collection( + spark, fitted_regression_pipeline, monkeypatch +): + """The local prediction entry point must never silently collect a distributed input.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + frame = spark.range(3) + + def forbidden(*args, **kwargs): + """Rejection must happen before any driver materialization action.""" + pytest.fail("Collected Spark input") + + monkeypatch.setattr(type(frame), "collect", forbidden) + monkeypatch.setattr(type(frame), "toPandas", forbidden) + with pytest.raises(TypeError, match="Spark"): + predict_local(frame, bundle) diff --git a/skyulf-core/tests/unit/test_pipeline_inference_schema.py b/skyulf-core/tests/unit/test_pipeline_inference_schema.py new file mode 100644 index 000000000..3d2d855a7 --- /dev/null +++ b/skyulf-core/tests/unit/test_pipeline_inference_schema.py @@ -0,0 +1,185 @@ +"""Observed feature schemas for portable model inference.""" + +import gc +import pickle +import weakref +from dataclasses import asdict +from typing import Any, cast + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.core.schema import SkyulfSchema +from skyulf.data.dataset import SplitDataset +from skyulf.engines import get_engine +from skyulf.pipeline import SkyulfPipeline + + +def _frame() -> pd.DataFrame: + """Include unsorted feature names and a target in the middle of the frame.""" + return pd.DataFrame( + { + "zeta": np.arange(24, dtype=np.int64), + "target": np.arange(24) * 2.0 + 1, + "category": ["b", "a"] * 12, + "alpha": np.arange(24, dtype=np.int64) % 3, + } + ) + + +def _pipeline(tuning: bool = False) -> SkyulfPipeline: + """Train a real model after changing feature names, dtypes and order.""" + modeling: dict[str, Any] = {"type": "ridge_regression", "params": {"alpha": 0.1}} + if tuning: + modeling = { + "type": "hyperparameter_tuner", + "base_model": {"type": "ridge_regression"}, + "strategy": "grid", + "metric": "r2", + "search_space": {"alpha": [0.1]}, + "cv_folds": 2, + "n_jobs": 1, + } + return SkyulfPipeline( + { + "preprocessing": [ + { + "name": "encode", + "transformer": "OneHotEncoder", + "params": {"columns": ["category"]}, + }, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["zeta"]}, + }, + ], + "modeling": modeling, + } + ) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize("payload", ["frame", "tuple", "split", "split_tuple", "wrapped"]) +@pytest.mark.parametrize("tuning", [False, True], ids=["model", "tuner"]) +def test_inference_schemas_describe_actual_training_features(engine, payload, tuning): + """Serving must preserve the raw and learned feature order before NumPy loses names.""" + frame: Any = _frame() + if engine == "polars": + frame = pl.from_pandas(frame) + data: Any = frame + if payload in {"tuple", "split_tuple"}: + features = frame.drop("target") if engine == "polars" else frame.drop(columns="target") + data = features, frame["target"] + if payload in {"split", "split_tuple"}: + data = SplitDataset(train=data, test=frame[:2]) + if payload == "wrapped": + data = get_engine(frame).wrap(frame) + pipeline = _pipeline(tuning) + + pipeline.fit(cast(Any, data), target_column="target") + + assert pipeline._inference_schemas is not None + raw, modeled = pipeline._inference_schemas + int64, float64, int8 = ( + ("int64", "float64", "int8") if engine == "pandas" else ("Int64", "Float64", "Int8") + ) + assert raw.columns == ("zeta", "category", "alpha") + assert raw.dtypes == { + "zeta": int64, + "category": "object" if engine == "pandas" else "String", + "alpha": int64, + } + assert modeled.columns == ("zeta", "alpha", "category_a", "category_b") + assert modeled.dtypes == { + "zeta": float64, + "alpha": int64, + "category_a": int8, + "category_b": int8, + } + + +@pytest.mark.parametrize("tuning", [False, True], ids=["model", "tuner"]) +@pytest.mark.parametrize("failure", ["preprocessing", "model", "held_out_transform"]) +def test_failed_refit_clears_inference_schemas(tuning, failure): + """A failed replacement must not advertise schemas from an obsolete or partial model.""" + pipeline = _pipeline(tuning) + frame = _frame() + pipeline.fit(frame, target_column="target") + assert pipeline._inference_schemas is not None + replacement = frame + held_out = frame[:2] + if failure == "preprocessing": + replacement = frame.assign(zeta="invalid") + elif failure == "model": + replacement = frame.assign(target=np.nan) + else: + held_out = frame[:2].assign(zeta="invalid") + + with pytest.raises((TypeError, ValueError)): + pipeline.fit(SplitDataset(train=replacement, test=held_out), target_column="target") + + assert pipeline._inference_schemas is None + assert not pipeline.is_fitted() + + +def test_preprocessing_only_fit_has_no_model_inference_schemas(): + """Feature engineering alone cannot advertise a fitted model interface.""" + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {}}) + + pipeline.fit(_frame(), target_column="target") + + assert pipeline._inference_schemas is None + + +@pytest.mark.parametrize("tuning", [False, True], ids=["model", "tuner"]) +def test_successful_refit_replaces_both_inference_schemas(tuning): + """A new feature dtype and category vocabulary must replace the old serving contract.""" + pipeline = _pipeline(tuning) + frame = _frame() + pipeline.fit(frame, target_column="target") + replacement = frame.assign(zeta=frame["zeta"].astype(np.float32), category="c") + + pipeline.fit(replacement, target_column="target") + + assert pipeline._inference_schemas is not None + raw, modeled = pipeline._inference_schemas + assert raw.dtypes["zeta"] == "float32" + assert modeled.columns == ("zeta", "alpha", "category_c") + + +def test_schema_capture_does_not_retain_training_samples(): + """Capturing portable metadata must not keep any training frame alive.""" + pipeline = _pipeline() + frame = _frame() + reference = weakref.ref(frame) + + pipeline.fit(frame, target_column="target") + del frame + gc.collect() + + assert reference() is None + assert pipeline._inference_schemas is not None + assert all(isinstance(schema, SkyulfSchema) for schema in pipeline._inference_schemas) + for schema in pipeline._inference_schemas: + assert set(asdict(schema)) == {"columns", "dtypes"} + assert all(isinstance(value, str) for value in schema.columns) + assert all(isinstance(value, str) for value in schema.dtypes.values()) + + +def test_inference_schemas_survive_pickle_without_changing_predictions_or_fingerprint(): + """Existing persisted pipelines keep exact schemas while retaining their serving behavior.""" + pipeline = _pipeline() + assert pipeline._inference_schemas is None + frame = _frame() + pipeline.fit(frame, target_column="target") + query = frame.drop(columns="target")[:3] + fingerprint = pipeline.fingerprint() + + restored = pickle.loads(pickle.dumps(pipeline)) + + assert restored._inference_schemas == pipeline._inference_schemas + assert restored.fingerprint() == fingerprint + np.testing.assert_allclose(restored.predict(query), pipeline.predict(query)) From 74ceacb98c48303e7eb5f4c87d9a53941ffc9679 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 23:26:31 +0300 Subject: [PATCH 11/85] feat(core): add native Spark batch model inference Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 11 +- docs/user_guide/inference_bundles.md | 127 +++++- docs/user_guide/spark.md | 27 +- .../spark_and_mlflow/02-inference-plan.md | 35 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 79 +++- initiatives/spark_and_mlflow/README.md | 4 +- skyulf-core/skyulf/inference/__init__.py | 10 +- skyulf-core/skyulf/inference/bundle.py | 17 +- skyulf-core/skyulf/inference/spark.py | 173 ++++++++ skyulf-core/tests/spark/conftest.py | 36 ++ .../tests/spark/test_inference_bundle.py | 30 -- .../spark/test_native_features_inference.py | 398 ++++++++++++++++++ 12 files changed, 883 insertions(+), 64 deletions(-) create mode 100644 skyulf-core/skyulf/inference/spark.py create mode 100644 skyulf-core/tests/spark/test_native_features_inference.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 0275286f7..e482817b0 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -74,11 +74,18 @@ execution and MLflow adapters remain under development. and [bundle guide](../docs/user_guide/inference_bundles.md). Trusted sklearn pickle payloads remain distinct from portable FE JSON and legacy persistence. +- Distributed regression inference through `predict_spark(mode="native_features")`: + saved FE runs as native Spark expressions, then the fitted Python estimator runs + in worker batches. Explicit row keys preserve result identity; schema/order and + package checks precede submission. Model loading is reused within each iterator, + and unused input columns do not reach workers. The bundle guide includes a Spark + example and explains compatibility with existing pipeline/backend artifacts. + ### Planned scope — not yet available - Further native Spark nodes and broader portable-state coverage. -- Distributed Python inference: native Spark preprocessing followed by Python - prediction, or a compatible Python preprocessing/model pipeline on workers. +- Compatible Python preprocessing/model pipelines on Spark workers, distributed + classification and worker packaging/scale validation. - Optional MLflow tracking/model packaging and Unity Catalog model resolution. - Scheduled batch inference with reproducible model versions and Delta outputs. diff --git a/docs/user_guide/inference_bundles.md b/docs/user_guide/inference_bundles.md index 16525508f..80ff05cf2 100644 --- a/docs/user_guide/inference_bundles.md +++ b/docs/user_guide/inference_bundles.md @@ -2,7 +2,7 @@ The 0.9.0 development API packages a fitted feature pipeline and a Python estimator with an explicit inference contract. It supports local pandas/Polars -prediction and provides the package boundary for the later Spark worker runner. +prediction and native Spark FE followed by Python regression on Spark workers. Importing `skyulf.inference` requires neither PySpark nor MLflow. ## Raw data and prepared features @@ -78,8 +78,8 @@ when the source schema differs intentionally. Supply feature columns only. Extra targets or identity columns are rejected. The returned pandas DataFrame preserves a pandas input index; Polars input -receives a RangeIndex. The later Spark runner will carry explicit `FrameSpec` -keys separately from model features. Calling `predict_local` with a Spark frame +receives a RangeIndex. The Spark runner carries explicit `FrameSpec` keys +separately from model features. Calling `predict_local` with a Spark frame fails before any collection or local conversion. Regression returns a float64 `prediction` column. Supported classifiers return @@ -136,6 +136,89 @@ for estimator bytes. Oversized file reads and pickle serialization are bounded. These are wire-size checks, not total process-memory guarantees. A wider input batch or a loaded estimator can use more memory than its serialized form. +## Native Spark FE and worker model inference + +`predict_spark(..., mode="native_features")` accepts a raw-input regression +bundle and a Spark DataFrame. The fitted FE runs as native Spark expressions. +Only the prepared feature columns and row keys reach the Python workers; +the estimator receives the features in the saved training order. Pandas/NumPy +batches exist inside those workers, without collecting the dataset to the driver. +Local training describes where the fit runs; it does not waive the matching +runtime requirements above. Train/package and consume in compatible environments, +even when switching from pandas or Polars inputs to Spark inputs. + +This example continues the local training example above. `spark` is an existing, +caller-owned SparkSession; the runner neither creates nor closes it: + +```python +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.inference import predict_spark + +incoming = spark.createDataFrame( + [(101, 4.0, "unused"), (102, None, "unused")], + "id long, amount double, extra string", +).repartition(2) + +predictions = predict_spark( + incoming, + bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark", python_batch_rows=2), + mode="native_features", +) +# This small example materializes two output rows; the runner does not collect them. +rows = predictions.orderBy("id").collect() +assert [row.id for row in rows] == [101, 102] +np.testing.assert_allclose([row.prediction for row in rows], [40.0, 20.0], atol=1e-12) +``` + +Production consumers receive a Spark DataFrame and can select their own action +or output sink. Output rows have no guaranteed physical order; match them by +the declared unique, non-null keys. Composite integer/string/boolean keys are +supported; floating-point and date/time keys are rejected by this first runner. +Keys must not also be model features. Incoming column names must not collide +with prediction output names. Leave `FrameSpec.target` unset. Unused input +columns are projected away, while the relative order and dtypes of required +feature columns are validated rather than silently corrected. + +Native FE output must also match the recorded model-feature dtypes before any +validation action runs. Some local/Spark operations promote numeric types +differently: a local integer column without missing values can remain integer +after mean imputation, while Spark's replacement expression produces double. +That bundle is rejected instead of casting silently. Normalize numeric types +explicitly before training and use the same input types for inference when a +cross-engine pipeline requires floating-point features. + +For this first worker runner, integral/boolean **model features** must have a +non-nullable Spark schema. Arrow can convert a nullable integer batch to pandas +float when it contains nulls, losing precision for large integers before the +model sees it. Nullable integral/boolean feature schemas are rejected eagerly, +even if their present rows happen to contain no nulls. Floating-point features +can retain null/NaN behavior. Row keys have a separate distributed non-null +check and can retain nullable schema metadata. Broader nullable feature transport +is part of the later worker validation gate. + +The model is loaded once per worker iterator invocation and reused over its +prediction chunks. Task retries or later actions may load it again. The worker +receives model bytes and inference metadata, without a SparkSession, registry +client or tracking connection. Prepare matching dependencies on driver and +workers; the runtime contract is checked in both places. + +`python_batch_rows` limits the rows passed to an individual model prediction. +Spark's `spark.sql.execution.arrow.maxRecordsPerBatch` separately controls Arrow +transport batches. Set that Spark configuration on your session when needed; +the runner does not change it. Neither row limit is a byte-memory guarantee. +Input-key and FE preservation checks can execute bounded validation actions +before prediction; prediction itself remains a lazy Spark computation. +Validation does not freeze a changing source. The caller owns any snapshot or +persist policy needed to keep validation and later actions on the same input. + +The first distributed runner accepts `input_stage="raw"` and regression only. +Prepared-feature bundles, classification, streaming and the Python FE worker +mode are not enabled by this delivery. Local classification remains available. Databricks, +Spark Connect and worker-wheel isolation still require their later validation +gates; local PySpark tests do not establish those deployment guarantees. + ## Current support and legacy adapters The first version accepts a successfully fitted standalone `SkyulfPipeline` @@ -147,6 +230,21 @@ FE nodes require a separate adapter; they are not serialized as an opaque whole pipeline. Training-only split nodes in the FE chain are therefore not portable yet; an explicit `SplitDataset` can supply training/test partitions. +Saving fitted transformations alongside the model already exists in Skyulf. +The new bundle adds an explicit execution contract for local and distributed +consumers; it does not relearn or replace those fitted transformations. + +| Existing artifact | Saved information and current consumer | New bundle bridge | +| --- | --- | --- | +| Standalone `SkyulfPipeline.save()` pickle | The pipeline object, fitted FE and model; `SkyulfPipeline.load(...).predict(...)` | Load with the existing API, then call `build_bundle` if recorded schemas and supported FE are present | +| Backend job artifact, normally `.joblib` | Model, fitted FeatureEngineer, target/drop metadata, model feature order/dtypes and training engine; `DeploymentService` | Explicit adapter planned for SM-18; do not pass the dictionary to `build_bundle` | +| Estimator-only pickle | Whatever the producer saved in the estimator | External preprocessing is not recovered automatically; a fitted pipeline and its input contract are needed | + +The backend serving path already transforms raw input and aligns the result to +the saved training feature order. Some serving choices, including enabled tuned +thresholds and request overrides, are resolved outside that artifact. Its adapter +must preserve that behavior and target-label decoding as well as the fitted model. + Existing `SkyulfPipeline.save/load` pickle behavior is unchanged. A standalone pipeline saved after schema capture can be loaded through that API and passed to `build_bundle`. Historical standalone artifacts without captured schemas @@ -154,6 +252,23 @@ must be fitted successfully again; the bundle does not invent missing column names or types. Backend artifact dictionaries are rejected. Their explicit adapter and threshold/label compatibility checks belong to SM-18. -This delivery verifies local packaging and inference. Distributed Python model -execution, MLflow/Unity Catalog, Databricks runtime validation, endpoints and -template generation remain later stages of the [Spark work](spark.md). +Changing the inference engine does not make every fitted Python transformer a +native Spark operation. For example, a future binning adapter must use the saved +training bin boundaries; it must not discover new boundaries from each inference +batch. The native path requires an implemented Spark applier and a supported +state codec. The planned Python-worker path requires explicit support for +independent batches and row preservation. Rolling/lag and transformations that +need neighboring rows cannot be made correct merely by putting them inside a +worker batch. Unsupported combinations fail explicitly; there is no automatic +conversion of a whole Spark dataset to local pandas or Polars. + +MLflow is a separate packaging/integration layer. Logging only an estimator +does not include external feature engineering; log a fitted pipeline or provide +a model wrapper that runs it. MLflow's +[Spark UDF](https://mlflow.org/docs/latest/api_reference/python_api/mlflow.pyfunc.html#mlflow.pyfunc.spark_udf) +executes Python model inference through pandas batches; it does not compile +arbitrary Python transformations into native Spark expressions. Skyulf's MLflow +adapter will expose the selected bundle contract in a later stage. + +MLflow/Unity Catalog, Databricks runtime validation, endpoints and template +generation remain later stages of the [Spark work](spark.md). diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 570092625..9f00a4f6c 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -6,9 +6,9 @@ available in the development checkout. **Native SimpleImputer (mean/constant) and StandardScaler support fit and apply.** Their fitted pipeline can be exported and restored across pandas, Polars and Spark. The [standalone inference bundle](inference_bundles.md) packages this state with -a fitted model and validates local raw/features prediction. The Spark model -worker runner is the next stage. -Other built-in native nodes and distributed model inference remain under development. +a fitted model and validates local raw/features prediction. The Spark runner +applies native FE and runs a Python regression model in worker batches. +Other native nodes, worker Python FE and distributed classification remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. ## Why a separate environment? @@ -527,6 +527,27 @@ repartitioning to 1/2/7 partitions, reversed inputs, repeated apply and a 10,000 fixture that rejects unbounded driver collection. Validation currently uses local PySpark; Databricks/Connect validation is still pending. +## Model inference after native FE + +Use `predict_spark(..., mode="native_features")` with a raw-input inference +bundle to apply the supported saved transformations natively and run a Python +regression model on Spark workers. The result is a Spark DataFrame containing +row keys and predictions. The full dataset remains distributed; pandas/NumPy +are used for individual worker model batches. + +The [inference bundle guide](inference_bundles.md#native-spark-fe-and-worker-model-inference) +contains a working example, input/order checks and the distinction between +model chunk size and Arrow transport batches. Its +[legacy artifact section](inference_bundles.md#current-support-and-legacy-adapters) +explains how existing pipeline pickle and backend joblib artifacts relate to +the new bundle. Saving fitted FE with a model already existed; distributed +execution requires explicit support for the transformations in that artifact. + +Current distributed model support is regression with native mean/constant +imputation and StandardScaler, including an empty FE chain. Local training can +use pandas or Polars. Python FE on workers, classification, MLflow packaging and +Databricks runtime validation have separate later gates. + ## Capability declarations ### Inspecting declared support diff --git a/initiatives/spark_and_mlflow/02-inference-plan.md b/initiatives/spark_and_mlflow/02-inference-plan.md index a4b0f76d4..114a469e2 100644 --- a/initiatives/spark_and_mlflow/02-inference-plan.md +++ b/initiatives/spark_and_mlflow/02-inference-plan.md @@ -63,13 +63,14 @@ def test_bundle_round_trip_predictions(fitted_regression_pipeline, tmp_path, raw np.testing.assert_allclose(after, before, rtol=1e-10, atol=1e-12) ``` -SM-08 fixture'ları `tests/spark/test_inference_bundle.py` içindedir: `raw_frame` -x/z kolonları ve farklı scale içeren küçük pandas verisi; -`fitted_regression_pipeline` imputer + scaler + mevcut linear regression ile +`raw_frame`, x/z kolonları ve farklı scale içeren küçük pandas verisidir. +SM-09 ile bu fixture ve `fitted_regression_pipeline`, ortak +`tests/spark/conftest.py` dosyasındadır; pipeline fixture'ı imputer + +scaler + mevcut linear regression ile local fit edilmiş gerçek SkyulfPipeline. Veri üretimi seed=17 ve held-out satırlarla sabitlenir; mock estimator bu testin yerine geçmez. Local giriş yalnız feature kolonlarıdır; ekstra id/target reddedilir. SM-09 -shared fixture'a ihtiyaç duyduğunda conftest'e taşır, Spark verisine ayrı id ekler. +Spark verisine ayrı id ekler; training fixture iki engine için ortak kullanılır. Kolon adı/sırası modelin NumPy girdisinden tahmin edilmez; başarılı pipeline fit metadata-only raw/model schema kaydeder. Eski standalone pickle için adapter `SkyulfPipeline.load` → `build_bundle`; schema yoksa refit gerekir. Backend @@ -88,13 +89,13 @@ dict adapter'ı SM-18'e kadar açıkça reddedilir. Ayrıntılar [bundle rehberi `mode="native_features"` ham girdiye önce native FE uygular, worker'a yalnız model feature'ları + keys gönderir. Sonuç Spark DataFrame'dir. -- [ ] Gerçek Spark action ve key-based karşılaştırma testi yaz. Model training +- [x] Gerçek Spark action ve key-based karşılaştırma testi yaz. Model training local fixture'da açıkça yapılsın; Spark fit çağrısı veya gizli conversion olmasın. -- [ ] Native FE'yi G1 yoluyla çalıştır; Python modelini mapInPandas iterator +- [x] Native FE'yi G1 yoluyla çalıştır; Python modelini mapInPandas iterator başına bir kez yükle. Output schema önceden bundle'dan gelsin; key dtype korunsun. -- [ ] Feature order ve input_stage doğrulamasını driver'da yap. Geniş kolonları +- [x] Feature order ve input_stage doğrulamasını driver'da yap. Geniş kolonları gereksiz yere worker'a gönderme; session/connection closure capture etme. -- [ ] Repartition ve Arrow batch boyutu değişince aynı key için aynı tahmini, +- [x] Repartition ve Arrow batch boyutu değişince aynı key için aynı tahmini, boş partition ve boş dataframe'de doğru boş schema'yı doğrula. ```python @@ -104,12 +105,12 @@ def test_native_path_matches_local(spark, raw_frame, regression_bundle): from skyulf.core.execution import FrameSpec, ExecutionOptions from skyulf.inference.bundle import predict_local from skyulf.inference.spark import predict_spark - frame = spark.createDataFrame(raw_frame).repartition(3) + frame = spark.createDataFrame(raw_frame.assign(id=range(len(raw_frame)))).repartition(3) actual = predict_spark(frame, regression_bundle, frame_spec=FrameSpec(row_keys=("id",)), options=ExecutionOptions(engine="spark", python_batch_rows=2), mode="native_features").toPandas().sort_values("id") - expected = predict_local(raw_frame.sort_values("id").drop(columns="id"), regression_bundle) + expected = predict_local(raw_frame, regression_bundle) np.testing.assert_allclose(actual["prediction"], expected["prediction"], rtol=1e-10) ``` @@ -119,6 +120,16 @@ inference yolunda driver collection olmaması ayrıca denetlenir. **Komut:** `python -m pytest skyulf-core/tests/spark/test_native_features_inference.py -q` **Kabul:** G2a: Spark FE native, model dağıtık Python; FE bir kez uygulanır. +2026-09-21: SM-09 tamamlandı. 393 gerçek Spark lane testi, 10050 base core testi +ve rehber örneği geçti; komutlar ve sınırlar [tamamlanma kaydındadır](OPEN_QUEUE.md). + +SM-09'un ilk runner'ı raw regression bundle kabul eder. Prepared-feature giriş, +Python FE worker modu, classification ve streaming açık ret verir. Numeric +model schema değişimleri action öncesinde reddedilir. Integer/boolean model +feature'ları Arrow hassasiyetini korumak için non-nullable Spark schema ister; +key'ler ayrı non-null/unique değer kontrolünden geçer. Model chunk satır limiti +Arrow transport limiti değildir. Detaylar [bundle rehberindedir](../../docs/user_guide/inference_bundles.md). + ## SM-10 — Worker'da Python FE + model **Bağımlılık:** SM-09. **Değiştir:** `skyulf/inference/spark.py`, bundle @@ -167,6 +178,10 @@ metadata'sı taşıyan geçerli bundle'dır; bozuk manifest ile ret üretme. - [ ] Worker'ın wheel'i kullanması ve eksik dependency'nin anlaşılır hatası için ayrı-process testi ekle. Model her satır için yüklenmesin; iterator seviyesinde yükleme helper'ını ölç. Task sayısına eşit tam bir global yükleme sayısı varsayma. +- [ ] SM-09'un nullable integer/boolean model-feature schema sınırını yeniden + değerlendir. Arrow → pandas null dönüşümünde büyük integer hassasiyeti + korunmadan desteği genişletme; float'tan integer'a geri cast çözüm değildir. + Destek açılmayacaksa mevcut erken ret ve kullanıcı dokümanını koru. - [ ] Büyük sentetik veri üzerinde driver RSS, worker peak ve wall time ölç; row count/feature width/partition sayısını kaydet. Driver belleğinin input boyutuyla doğrusal büyümemesini araştır; sabit hızlanma oranı vaat etme. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index f6831aebf..87f2be3e0 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-00–SM-08 tamamlandı; sıradaki SM-09. Hedef: 0.9.0.** +Güncelleme: 2026-09-21. **SM-00–SM-09 tamamlandı; sıradaki SM-10. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -18,8 +18,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-06 | Native StandardScaler | SM-05 | DONE | Population variance, dört flag ve numeric parity; aşağıda kanıt | | SM-07 | Uçtan uca FE kapısı | SM-06 | DONE | Üç engine çapraz fit/apply; kayıt/yükleme; aşağıda kanıt | | SM-08 | Ortak inference bundle | SM-07 | DONE | Raw/features ayrımı; model metadata round-trip; aşağıda kanıt | -| SM-09 | Native FE + worker model | SM-08 | READY | Spark tahmini local ile key bazında aynı | -| SM-10 | Worker Python FE + model | SM-09 | WAIT | Batch-safe pipeline; window gibi yollar açık ret | +| SM-09 | Native FE + worker model | SM-08 | DONE | Spark tahmini local ile key bazında aynı; aşağıda kanıt | +| SM-10 | Worker Python FE + model | SM-09 | READY | Batch-safe pipeline; window gibi yollar açık ret | | SM-11 | Classification ve ölçek kapısı | SM-10 | WAIT | Class/proba/threshold parity; worker kanıtı | | SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | @@ -66,8 +66,8 @@ olarak yazılır; yerel test sonucu gerçek UC/Databricks sonucu yerine geçmez. Önce README, mimari ve bu kuyruğu oku. Güncel git durumunu ve ilgili kaynakları doğrula; kullanıcı değişikliklerini koru. İlk READY görevi ACTIVE yap, kendi test döngüsüyle tamamla ve kanıtı yaz. Sonraki bağımlılığı aç. Endpoint veya -template'e önden başlama. SM-00 test/runtime hazırlığıdır; native node uygulaması -ve MLflow entegrasyonu henüz yok. +template'e önden başlama. SM-00 yalnız test/runtime hazırlığıydı; güncel +destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. ## SM-00 — 2026-09-21 tamamlanma kaydı @@ -439,3 +439,72 @@ ve MLflow entegrasyonu henüz yok. - Sınır: bu görev local paketleme/inference içindir. Spark worker model runner SM-09, ikinci Python FE yolu SM-10, dağıtık classification kapısı SM-11'dir. MLflow, Databricks/Connect, endpoint ve template doğrulaması henüz yok. + +## SM-09 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `81745a7b`; bu kayıt SM-09 çalışma ağacına aittir. +- `inference/spark.py` ve public `predict_spark`: raw girdiye native FE, + ardından `mapInPandas` iterator'larında Python regression tahmini. Model + iterator başına bir kez yüklenir; yalnız feature'lar ve key'ler worker'a gider. + Ortak model tahmin helper'ı local davranışı tekrar kullanır. Session, frame + veya bağlantı worker closure'a girmez; pandas dönüşümü worker batch'indedir. +- `tests/spark/test_native_features_inference.py`; SM-08'in fitted pipeline ve + raw-frame fixture'ları ortak conftest'e taşındı. pandas/Polars eğitim, bundle + kayıt/yükleme, repartition 1/3, Arrow limit 1/5, eksik değerler, boş veri ve + partition'lar, birleşik key'ler, `2**53` üstü identity, worker projection, + bounded driver validation, iterator model yükleme ve chunk sınırı doğrulandı. +- Ruling: native model schema önce yalnız Spark ifadeleri oluşturularak + incelenir; sonra mevcut FE key/preservation kontrolleri çalışır. Preview veri + action'ı içermez, öğrenilmiş kuralları tekrar fit etmez. Local integer imputer + çıktısı ile Spark double promotion uyuşmazlığı artık action'dan önce hata verir. +- Ruling: nullable integer/boolean model feature schema'ları erken reddedilir; + Arrow null batch dönüşümü hassasiyet kaybetmeden çözülene kadar destek ilan + edilmez. Non-nullable integer model feature ve büyük integer key gerçek action + ile geçti. Key'lerin nullable schema metadata'sı ayrı değer kontrolüyle korunur. + Broader nullable transport SM-11'e kayıtlıdır. +- Ruling: raw model input kolonlarının kendi sırası/dtype'ları korunmalı; + extra kolonlar projection ile elenir. Key'ler integer/string/boolean'dır; + feature/output isimleriyle çakışamaz. Incoming prediction kolonu da reddedilir. + `FrameSpec.target` boş olmalıdır. Raw regression dışındaki stage/task/mode ve + streaming açık ret verir. `python_batch_rows` model çağrısını sınırlar; + Arrow transport konfigürasyonuna veya kullanıcının Spark session'ına yazılmaz. +- TDD red: eksik public API; streaming, native dtype ve nullable transport + girdilerinin doğrulamadan önce Spark action'a ulaşması ayrı ayrı yeniden + üretildi. Dar final test: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark/test_native_features_inference.py + skyulf-core/tests/spark/test_inference_bundle.py -q -o addopts= + -p no:cacheprovider --basetemp .cache/sm09-runner-final` + → **101 passed**, 110.42 saniye; owned JVM temiz kapandı. +- Bağımsız review iki schema/Arrow bulgusunu doğruladı; düzeltmelerin ve red + regresyonların yeniden incelemesinde açık yüksek/orta bulgu kalmadı. +- Eski backend artifact akışı ayrıca doğrulandı: `.venv/Scripts/python.exe -m + pytest tests/integration/test_bundle_preprocessing_integrity.py + tests/integration/test_full_inference_pipeline.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm09-legacy` + → **22 passed, 30 warnings**, 7.80 saniye. Backend kaynakları değiştirilmedi; + full FE/model joblib reader korunuyor, yeni bundle adapter'ı SM-18'de. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm09-core-full` + → **10050 passed, 274 skipped, 1097 warnings**, 194.81 saniye. Base ortamda + PySpark yok; gerçek Spark testleri ayrı lane'de doğrulanır. +- Ruff/format ve tam repo ty başarılı. Bundle/Spark rehberleri mevcut artifact + davranışını, yeni runner'ı, dtype ve sürüm sınırlarını açıklıyor. + `mkdocs build --strict` başarılı. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py + skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --tb=short + -o addopts= -p no:cacheprovider --basetemp .cache/sm09-spark-full` + → **393 passed, 2 warnings**, 418.45 saniye. PySpark 4.0.3 / Java 17; + JVM temiz kapandı. Warning'ler mevcut Split alias'ına ait. +- Spark runtime: Python 3.12.10, skyulf-core 0.9.0, pandas 2.3.2, + Polars 1.44.2, sklearn 1.9.1, NumPy 1.26.4, SciPy 1.17.1, Arrow 24.0.0. +- Rehberin iki Python bloğu `.venv-spark/Scripts/python.exe + .cache/sm09_docs_example.py` ile aynı ortamda çalıştırıldı: local kayıt/yükleme + ve key'li Spark sonucu **[40.0, 20.0]**, başarılı assert'ler ve temiz JVM kapanışı. +- Sınır: bu G2a / native FE + regression teslimatıdır. SM-10 Python FE worker + modu, SM-11 classification/worker wheel/ölçek kapısıdır. Databricks/Connect, + MLflow/UC, endpoint ve template doğrulaması yoktur. Sıradaki görev SM-10. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index 93ccaea05..6c68b7fc8 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,6 +1,6 @@ # Spark ve MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-08 tamamlandı; sıradaki görev SM-09.** +Tarih: 2026-09-21. Durum: **SM-00–SM-09 tamamlandı; sıradaki görev SM-10.** Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). @@ -47,7 +47,7 @@ Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutu ## Çalışma kuralları -- Sonraki görev **SM-09**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. +- Sonraki görev **SM-10**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. - Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. - Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. diff --git a/skyulf-core/skyulf/inference/__init__.py b/skyulf-core/skyulf/inference/__init__.py index 7aacf02d1..eea6f8344 100644 --- a/skyulf-core/skyulf/inference/__init__.py +++ b/skyulf-core/skyulf/inference/__init__.py @@ -1,5 +1,13 @@ """Standalone inference bundles; importing this package needs no Spark or MLflow.""" from .bundle import InferenceBundle, build_bundle, load_bundle, predict_local, save_bundle +from .spark import predict_spark -__all__ = ["InferenceBundle", "build_bundle", "load_bundle", "predict_local", "save_bundle"] +__all__ = [ + "InferenceBundle", + "build_bundle", + "load_bundle", + "predict_local", + "predict_spark", + "save_bundle", +] diff --git a/skyulf-core/skyulf/inference/bundle.py b/skyulf-core/skyulf/inference/bundle.py index df718f5fc..623b99a22 100644 --- a/skyulf-core/skyulf/inference/bundle.py +++ b/skyulf-core/skyulf/inference/bundle.py @@ -225,24 +225,31 @@ def predict_local( {col.name: pd.Series(index=index, dtype=col.dtype) for col in manifest.output_schema} ) model = load_model(bundle.model_payload, manifest) + return _predict_features(features, model, manifest, index) + + +def _predict_features( + features: Any, model: Any, manifest: BundleManifest, index: pd.Index +) -> pd.DataFrame: + """Apply an already loaded estimator without preprocessing or retaining batch state.""" values, _ = SklearnBridge.to_sklearn(features, validate_features=True) probabilities = None if manifest.task == "classification": probabilities = np.asarray(model.predict_proba(values)) - if probabilities.shape != (len(frame), len(bundle.classes)): + if probabilities.shape != (len(features), len(manifest.classes)): raise ValueError("Model probability shape violates the bundle contract.") if manifest.thresholds.values: - thresholds = dict(zip(bundle.classes, manifest.thresholds.values, strict=True)) - predictions = apply_thresholds(probabilities, thresholds, classes=bundle.classes) + thresholds = dict(zip(manifest.classes, manifest.thresholds.values, strict=True)) + predictions = apply_thresholds(probabilities, thresholds, classes=manifest.classes) else: predictions = np.asarray(model.predict(values)) - if predictions.shape != (len(frame),): + if predictions.shape != (len(features),): raise ValueError("Model prediction shape violates the bundle contract.") output = pd.DataFrame( {"prediction": pd.Series(predictions, index=index, dtype=manifest.output_schema[0].dtype)} ) if probabilities is not None: - for position, name in enumerate(bundle.probability_columns): + for position, name in enumerate(manifest.probability_columns): output[name] = probabilities[:, position] return output diff --git a/skyulf-core/skyulf/inference/spark.py b/skyulf-core/skyulf/inference/spark.py new file mode 100644 index 000000000..c2f5290f0 --- /dev/null +++ b/skyulf-core/skyulf/inference/spark.py @@ -0,0 +1,173 @@ +"""Native Spark preprocessing followed by bounded worker-side Python prediction.""" + +import importlib +from collections.abc import Callable, Iterator +from typing import Any + +import pandas as pd + +from ..core.capabilities import UnsupportedExecutionError +from ..core.execution import ExecutionOptions, FrameSpec +from ..preprocessing._spark import _column, _native, _resolved_names +from ..preprocessing.pipeline import FeatureEngineer +from ._manifest import BundleManifest, check_runtime, checksum +from ._model import load_model +from .bundle import InferenceBundle, _predict_features, _validate_bundle, _validate_frame + + +def predict_spark( + frame: Any, + bundle: InferenceBundle, + *, + frame_spec: FrameSpec, + options: ExecutionOptions, + mode: str, +) -> Any: + """Apply frozen native FE and distribute a regression estimator over Spark workers. + + Currently accepts raw regression bundles with native row-preserving FE. + Supply unique non-null integer, string or boolean keys; output contains + those keys and prediction, with no row ordering guarantee. Extra unused + input columns are projected away. Declared features must retain their + training order and dtypes; keys never become model features. + Integral and boolean model features require a nonnullable Spark schema, + because Arrow otherwise can widen their values in pandas batches. Native + FE output dtype changes are rejected against the fitted bundle schema. + + Schema, stage, capability and bundle checks precede distributed validation. + Existing native FE performs bounded key and row-preservation checks on the + driver. Prediction stays distributed, loading the model once per iterator. + ``python_batch_rows`` bounds estimator calls, not Arrow transport batches + or bytes. Configure ``spark.sql.execution.arrow.maxRecordsPerBatch`` on + the caller's session separately; this function never changes that setting. + Estimator pickle payloads must come from a trusted producer. + """ + if not isinstance(frame_spec, FrameSpec): + raise TypeError("frame_spec must be FrameSpec.") + if not isinstance(options, ExecutionOptions) or options.engine != "spark": + raise ValueError("predict_spark requires ExecutionOptions(engine='spark').") + if frame_spec.target is not None: + raise ValueError("Inference frame_spec must not declare a target.") + if mode != "native_features": + raise UnsupportedExecutionError( + "inference", "predict", "spark", "Only mode='native_features' is implemented." + ) + _validate_bundle(bundle, options) + manifest = bundle.manifest + if manifest.input_stage != "raw": + raise ValueError("native_features currently requires a raw input_stage bundle.") + if manifest.task != "regression": + raise UnsupportedExecutionError( + "inference", "predict", "spark", "Only regression bundles are currently supported." + ) + native = _native(frame) + if native.isStreaming: + raise UnsupportedExecutionError( + "inference", "predict", "spark", "Streaming inference is not supported." + ) + _validate_names_and_keys(native, manifest, frame_spec) + raw_names = {column.name for column in manifest.input_schema} + raw = native.select(*[_column(native, name) for name in native.columns if name in raw_names]) + _validate_frame(raw, manifest.input_schema, "bundle input") + selected = native.select( + *[_column(native, name) for name in (*frame_spec.row_keys, *raw.columns)] + ) + engineer = FeatureEngineer.from_state( + bundle.feature_state, execution_options=options, frame_spec=frame_spec + ) + # The portable allowlist contains native appliers that only construct Spark + # expressions. Inspect their output types before FE's key-validation actions. + preview = selected + for step in engineer.fitted_steps: + preview = _native(step["applier"].apply(preview, step["artifact"])) + _model_features(preview, manifest) + transformed = _native(engineer.transform(selected, preserve_rows=True)) + features = _model_features(transformed, manifest) + worker_frame = transformed.select( + *[_column(transformed, name) for name in (*frame_spec.row_keys, *features.columns)] + ) + types = importlib.import_module("pyspark.sql.types") + schema = types.StructType( + [native.schema[key] for key in frame_spec.row_keys] + + [ + types.StructField(column.name, types.DoubleType(), True) + for column in manifest.output_schema + ] + ) + worker = _prediction_iterator( + bundle.model_payload, manifest, frame_spec.row_keys, options.python_batch_rows + ) + return worker_frame.mapInPandas(worker, schema=schema) + + +def _model_features(frame: Any, manifest: BundleManifest) -> Any: + """Check native output positions and dtypes using only the lazy Spark schema.""" + features = frame.select( + *[_column(frame, name) for name in frame.columns if name in manifest.feature_order] + ) + _validate_frame(features, manifest.feature_schema, "model features") + integral = {"byte", "short", "integer", "long", "boolean"} + for field in features.schema.fields: + if field.nullable and field.dataType.typeName() in integral: + raise UnsupportedExecutionError( + "inference", + "predict", + "spark", + f"Nullable model feature {field.name!r} risks Arrow dtype conversion. " + "Use a nonnullable Spark schema, or normalize to floats before training.", + ) + return features + + +def _validate_names_and_keys(frame: Any, manifest: BundleManifest, spec: FrameSpec) -> None: + """Reject ambiguous names, protected-column collisions and unsafe Arrow key types.""" + resolved = _resolved_names(frame) + if len(resolved) != len(set(resolved)): + raise ValueError("Duplicate Spark column names are unsupported.") + sensitive = frame.sparkSession.conf.get("spark.sql.caseSensitive") == "true" + + def names(columns: tuple[str, ...]) -> set[str]: + """Apply the same identifier resolution used by Spark for collision checks.""" + return set(columns if sensitive else (name.lower() for name in columns)) + + keys = names(spec.row_keys) + raw = names(tuple(col.name for col in manifest.input_schema)) + features = names(manifest.feature_order) + output = names(tuple(col.name for col in manifest.output_schema)) + if len(keys) != len(spec.row_keys) or keys & (raw | features | output): + raise ValueError("row_keys collide with feature or prediction columns.") + if output & (raw | features | set(resolved)): + raise ValueError("Input and prediction output columns collide.") + if len(raw) != len(manifest.input_schema) or len(features) != len(manifest.feature_order): + raise ValueError("Duplicate Spark feature names in bundle schema.") + missing = set(spec.row_keys).difference(frame.columns) + if missing: + raise ValueError(f"Missing Spark row_keys: {sorted(missing)}") + supported = {"byte", "short", "integer", "long", "string", "boolean"} + for key in spec.row_keys: + if frame.schema[key].dataType.typeName() not in supported: + raise TypeError( + f"Unsupported inference key dtype for {key}; use integer/string/boolean." + ) + + +def _prediction_iterator( + payload: bytes, manifest: BundleManifest, row_keys: tuple[str, ...], batch_rows: int +) -> Callable[[Iterator[pd.DataFrame]], Iterator[pd.DataFrame]]: + """Capture only frozen metadata and bytes, never a Spark session or dataframe.""" + + def predict_batches(batches: Iterator[pd.DataFrame]) -> Iterator[pd.DataFrame]: + """Validate the worker runtime once and reuse one estimator across bounded chunks.""" + check_runtime(manifest) + if checksum(payload) != manifest.model_sha256: + raise ValueError("Bundle payload checksum mismatch on worker.") + model = load_model(payload, manifest) + for batch in batches: + for offset in range(0, len(batch), batch_rows): + chunk = batch.iloc[offset : offset + batch_rows] + features = chunk.loc[:, list(manifest.feature_order)] + _validate_frame(features, manifest.feature_schema, "worker model features") + predictions = _predict_features(features, model, manifest, chunk.index) + yield pd.concat([chunk.loc[:, list(row_keys)], predictions], axis=1) + + return predict_batches diff --git a/skyulf-core/tests/spark/conftest.py b/skyulf-core/tests/spark/conftest.py index 6c6b04b63..5458a6bb4 100644 --- a/skyulf-core/tests/spark/conftest.py +++ b/skyulf-core/tests/spark/conftest.py @@ -5,8 +5,14 @@ import os import sys +import numpy as np +import pandas as pd +import polars as pl import pytest +from skyulf.data.dataset import SplitDataset +from skyulf.pipeline import SkyulfPipeline + @pytest.fixture(scope="session") def spark(tmp_path_factory): @@ -40,3 +46,33 @@ def spark(tmp_path_factory): yield session finally: session.stop() + + +@pytest.fixture(params=["pandas", "polars"]) +def fitted_regression_pipeline(request): + """Different feature scales expose swapped columns and accidental double preprocessing.""" + rng = np.random.default_rng(17) + frame = pd.DataFrame({"x": rng.normal(100, 20, 40), "z": rng.normal(5, 2, 40)}) + frame["target"] = 2 * frame.x - 3 * frame.z + 7 + pipeline = SkyulfPipeline( + { + "preprocessing": [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x", "z"]}}, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["x", "z"]}, + }, + ], + "modeling": {"type": "linear_regression"}, + } + ) + data = pl.from_pandas(frame) if request.param == "polars" else frame + pipeline.fit(SplitDataset(train=data, test=data.head(0)), target_column="target") + return pipeline + + +@pytest.fixture +def raw_frame(): + """Held-out values and a nondefault index expose re-fitting and row misalignment.""" + return pd.DataFrame({"x": [150.0, 80.0], "z": [9.0, 3.0]}, index=[17, 4]) diff --git a/skyulf-core/tests/spark/test_inference_bundle.py b/skyulf-core/tests/spark/test_inference_bundle.py index f6485302b..fb4c42380 100644 --- a/skyulf-core/tests/spark/test_inference_bundle.py +++ b/skyulf-core/tests/spark/test_inference_bundle.py @@ -19,36 +19,6 @@ from skyulf.preprocessing import _feature_state -@pytest.fixture(params=["pandas", "polars"]) -def fitted_regression_pipeline(request): - """Different feature scales expose swapped columns and accidental double preprocessing.""" - rng = np.random.default_rng(17) - frame = pd.DataFrame({"x": rng.normal(100, 20, 40), "z": rng.normal(5, 2, 40)}) - frame["target"] = 2 * frame.x - 3 * frame.z + 7 - pipeline = SkyulfPipeline( - { - "preprocessing": [ - {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x", "z"]}}, - { - "name": "scale", - "transformer": "StandardScaler", - "params": {"columns": ["x", "z"]}, - }, - ], - "modeling": {"type": "linear_regression"}, - } - ) - data = pl.from_pandas(frame) if request.param == "polars" else frame - pipeline.fit(SplitDataset(train=data, test=data.head(0)), target_column="target") - return pipeline - - -@pytest.fixture -def raw_frame(): - """Held-out values and a nondefault index expose re-fitting and row misalignment.""" - return pd.DataFrame({"x": [150.0, 80.0], "z": [9.0, 3.0]}, index=[17, 4]) - - @pytest.mark.parametrize("stage", ["raw", "features"]) def test_round_trip_preserves_predictions(fitted_regression_pipeline, raw_frame, tmp_path, stage): """Loading must preserve the same prediction function without applying FE twice.""" diff --git a/skyulf-core/tests/spark/test_native_features_inference.py b/skyulf-core/tests/spark/test_native_features_inference.py new file mode 100644 index 000000000..c8a710d80 --- /dev/null +++ b/skyulf-core/tests/spark/test_native_features_inference.py @@ -0,0 +1,398 @@ +"""Native Spark preprocessing must preserve the frozen local prediction function.""" + +import importlib +import subprocess +import sys +from dataclasses import replace + +import numpy as np +import pandas as pd +import pytest + +import skyulf.inference as inference +from skyulf.core.capabilities import UnsupportedExecutionError +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.core.schema import SchemaMismatchError +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle, load_bundle, predict_local, save_bundle +from skyulf.pipeline import SkyulfPipeline +from skyulf.preprocessing.pipeline import FeatureEngineer + + +@pytest.fixture +def regression_bundle(fitted_regression_pipeline): + """Reuse real pandas/Polars training without fitting anything on Spark input.""" + return build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + + +def _predict(frame, bundle, **kwargs): + """Exercise the public API with the smallest supported explicit contract.""" + return inference.predict_spark( + frame, + bundle, + frame_spec=kwargs.pop("frame_spec", FrameSpec(row_keys=("id",))), + options=kwargs.pop("options", ExecutionOptions("spark", python_batch_rows=2)), + mode=kwargs.pop("mode", "native_features"), + **kwargs, + ) + + +@pytest.mark.parametrize("partitions,arrow_rows", [(1, 1), (3, 5)]) +def test_native_path_matches_persisted_local_bundle( + spark, regression_bundle, tmp_path, monkeypatch, partitions, arrow_rows +): + """Repartitioning, missing values and Arrow boundaries must not change keyed predictions.""" + save_bundle(regression_bundle, tmp_path / "bundle") + bundle = load_bundle(tmp_path / "bundle") + raw = pd.DataFrame({"x": [150.0, 80.0, np.nan, 110.0], "z": [9.0, 3.0, 4.0, np.nan]}) + expected = predict_local(raw, bundle) + frame = spark.createDataFrame( + [ + (10, 150.0, 9.0, "wide"), + (11, 80.0, 3.0, "wide"), + (12, None, 4.0, "wide"), + (2**53 + 1, 110.0, float("nan"), "wide"), + ], + "id long, x double, z double, unused string", + ).repartition(partitions) + old_limit = spark.conf.get("spark.sql.execution.arrow.maxRecordsPerBatch") + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", str(arrow_rows)) + + def forbidden(*args, **kwargs): + """Prediction must never train or materialize a distributed input locally.""" + pytest.fail("Inference attempted fitting or driver materialization") + + collect = type(frame).collect + validation_plans = [] + + def bounded_collect(self): + """Only existing one-row validation results may reach the driver in inference.""" + plan = self._jdf.queryExecution().logical().toString() + assert plan.startswith("GlobalLimit 1"), plan + validation_plans.append(plan) + return collect(self) + + try: + with monkeypatch.context() as patch: + patch.setattr(FeatureEngineer, "fit_transform", forbidden) + patch.setattr(type(frame), "toPandas", forbidden) + patch.setattr(type(frame), "toLocalIterator", forbidden) + patch.setattr(type(frame), "collect", bounded_collect) + output = _predict(frame, bundle) + rows = output.orderBy("id").collect() + plan = output._jdf.queryExecution().executedPlan().toString() + assert "MapInPandas" in plan + assert not any(name in plan for name in ("ArrowEvalPython", "BatchEvalPython", "PythonUDF")) + assert output.columns == ["id", "prediction"] + assert output.schema["id"] == frame.schema["id"] + assert spark.conf.get("spark.sql.execution.arrow.maxRecordsPerBatch") == str(arrow_rows) + assert validation_plans + assert [row.id for row in rows] == [10, 11, 12, 2**53 + 1] + np.testing.assert_allclose( + [row.prediction for row in rows], expected.prediction, rtol=1e-10 + ) + finally: + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", old_limit) + + +@pytest.mark.parametrize("empty", [False, True]) +def test_empty_partitions_and_composite_key_schema(spark, regression_bundle, empty): + """Empty partitions and inputs must preserve explicit key types and prediction schema.""" + frame = spark.createDataFrame( + [] if empty else [(1, 2, 3, 4, "a", True, 150.0, 9.0)], + "tiny byte, small short, id int, large long, text string, flag boolean, x double, z double", + ).repartition(3) + keys = ("tiny", "small", "id", "large", "text", "flag") + output = _predict(frame, regression_bundle, frame_spec=FrameSpec(row_keys=keys)) + rows = output.collect() + assert output.schema.fields[:-1] == [frame.schema[key] for key in keys] + assert output.schema["prediction"].dataType.typeName() == "double" + assert [tuple(row)[:-1] for row in rows] == ([] if empty else [(1, 2, 3, 4, "a", True)]) + np.testing.assert_allclose([row.prediction for row in rows], [] if empty else [280.0]) + + +@pytest.mark.parametrize( + "change,match", + [ + ("order", "order"), + ("missing", "missing"), + ("dtype", "dtype"), + ("duplicate", "[Dd]uplicate"), + ("key_feature", "colli|row_keys"), + ("key_output", "colli|prediction"), + ("output_input", "colli|prediction"), + ("date_key", "key.*dtype|key.*type"), + ("target", "target"), + ("stage", "raw|stage"), + ("mode", "mode|native_features"), + ("engine", "engine|spark"), + ("checksum", "checksum"), + ("runtime", "runtime"), + ("streaming", "[Ss]treaming"), + ], +) +def test_preflight_rejects_invalid_contract_before_actions( + spark, regression_bundle, fitted_regression_pipeline, monkeypatch, change, match +): + """Schema, identity and bundle errors must fail before a distributed validation job.""" + frame = spark.createDataFrame([(1, 150.0, 9.0)], "id long, x double, z double") + kwargs = {} + bundle = regression_bundle + if change == "order": + frame = frame.select("id", "z", "x") + elif change == "missing": + frame = frame.drop("z") + elif change == "dtype": + frame = frame.selectExpr("id", "cast(x as string) as x", "z") + elif change == "duplicate": + frame = frame.selectExpr("id", "x", "z", "x as X") + elif change == "key_feature": + kwargs["frame_spec"] = FrameSpec(row_keys=("x",)) + elif change == "key_output": + frame = frame.withColumnRenamed("id", "PREDICTION") + kwargs["frame_spec"] = FrameSpec(row_keys=("PREDICTION",)) + elif change == "output_input": + frame = frame.selectExpr("*", "1 as prediction") + elif change == "date_key": + frame = frame.selectExpr("date'2026-01-01' as id", "x", "z") + elif change == "target": + kwargs["frame_spec"] = FrameSpec(row_keys=("id",), target="z") + elif change == "stage": + bundle = build_bundle( + fitted_regression_pipeline, input_stage="features", feature_order=("x", "z") + ) + elif change == "mode": + kwargs["mode"] = "python_pipeline" + elif change == "engine": + kwargs["options"] = ExecutionOptions("pandas") + elif change == "checksum": + bundle = replace(bundle, model_payload=b"broken") + elif change == "streaming": + frame = ( + spark.readStream.format("rate") + .load() + .selectExpr("value as id", "cast(value as double) as x", "cast(value as double) as z") + ) + elif change == "runtime": + from skyulf.inference._manifest import semantic_digest + + manifest = bundle.manifest.model_copy( + update={ + "requirements": tuple( + (name, "0.0.0" if name == "scikit-learn" else version) + for name, version in bundle.manifest.requirements + ) + } + ) + manifest = manifest.model_copy(update={"semantic_digest": semantic_digest(manifest)}) + bundle = replace(bundle, manifest=manifest) + + def forbidden(*args, **kwargs): + """Even the bounded key validation action is forbidden for invalid metadata.""" + pytest.fail("Invalid contract reached a Spark action") + + for action in ("collect", "count", "first", "take", "toPandas", "toLocalIterator"): + monkeypatch.setattr(type(frame), action, forbidden) + with pytest.raises( + (ValueError, TypeError, SchemaMismatchError, UnsupportedExecutionError), match=match + ): + _predict(frame, bundle, **kwargs) + + +@pytest.mark.parametrize("ids", [[1, 1], [1, None]]) +def test_duplicate_or_null_keys_are_rejected(spark, regression_bundle, ids): + """Rows cannot be associated safely with predictions when business keys are ambiguous.""" + frame = spark.createDataFrame([(key, 150.0, 9.0) for key in ids], "id long, x double, z double") + with pytest.raises(ValueError, match="unique and non-null"): + _predict(frame, regression_bundle) + + +def test_native_feature_dtype_mismatch_is_rejected_before_actions(spark, monkeypatch): + """Native dtype promotion cannot silently change the local model's recorded schema.""" + train = pd.DataFrame({"x": [1, 3, 5, 7], "y": [2.0, 6.0, 10.0, 14.0]}) + pipeline = SkyulfPipeline( + { + "preprocessing": [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"columns": ["x"]}} + ], + "modeling": {"type": "linear_regression"}, + } + ) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + frame = spark.createDataFrame([(1, 2)], "id long, x long") + + def forbidden(*args, **kwargs): + """A dtype incompatibility is known from Spark expressions without executing them.""" + pytest.fail("Feature dtype mismatch reached a Spark action") + + monkeypatch.setattr(type(frame), "collect", forbidden) + with pytest.raises(SchemaMismatchError, match="dtype"): + _predict(frame, bundle) + + +def test_classification_is_rejected_before_actions(spark, monkeypatch): + """Unimplemented distributed class semantics must not silently use a regression schema.""" + train = pd.DataFrame({"x": [-2.0, -1.0, 1.0, 2.0], "y": ["no", "no", "yes", "yes"]}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + frame = spark.createDataFrame([(1, 2.0)], "id long, x double") + + def forbidden(*args, **kwargs): + """Unsupported tasks must fail before even bounded validation actions.""" + pytest.fail("Classification reached a Spark action") + + monkeypatch.setattr(type(frame), "collect", forbidden) + with pytest.raises(UnsupportedExecutionError, match="regression"): + _predict(frame, bundle) + + +@pytest.mark.parametrize("kind", ["integer", "boolean"]) +def test_nullable_integral_features_are_rejected_before_actions(spark, monkeypatch, kind): + """Arrow must not silently widen nullable integral or boolean model features.""" + values = [1, 3, 5, 7] if kind == "integer" else [False, True, False, True] + train = pd.DataFrame({"x": values, "y": [2.0, 6.0, 10.0, 14.0]}) + pipeline = SkyulfPipeline( + { + "preprocessing": [], + "modeling": { + "type": "random_forest_regressor", + "params": {"n_estimators": 3, "random_state": 17}, + }, + } + ) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + if kind == "integer": + local = pd.DataFrame({"x": pd.Series([5, None, 7], dtype="Int64")}) + assert len(predict_local(local, bundle)) == 3 + dtype = "long" if kind == "integer" else "boolean" + frame = spark.createDataFrame([(1, values[0]), (2, None)], f"id long, x {dtype}") + + def forbidden(*args, **kwargs): + """Unsupported transport schemas are known before key validation needs any rows.""" + pytest.fail("Nullable model feature reached a Spark action") + + monkeypatch.setattr(type(frame), "collect", forbidden) + with pytest.raises(UnsupportedExecutionError, match="[Nn]ullable.*Arrow"): + _predict(frame, bundle) + + +def test_nonnullable_integer_features_preserve_supported_inference(spark): + """The conservative nullable transport guard must still accept declared nonnullable integers.""" + types = importlib.import_module("pyspark.sql.types") + train = pd.DataFrame({"x": [1, 3, 5, 7], "y": [2.0, 6.0, 10.0, 14.0]}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + large = 2**53 + 1 + frame = spark.createDataFrame( + [(large, large)], + types.StructType( + [ + types.StructField("id", types.LongType(), False), + types.StructField("x", types.LongType(), False), + ] + ), + ) + rows = _predict(frame, bundle).collect() + expected = predict_local(pd.DataFrame({"x": [large]}), bundle) + assert [row.id for row in rows] == [large] + np.testing.assert_allclose([row.prediction for row in rows], expected.prediction) + + +def test_worker_loads_once_and_bounds_estimator_batches(regression_bundle, monkeypatch): + """Iterator reuse must avoid repeated deserialization and bound each estimator call.""" + module = importlib.import_module("skyulf.inference.spark") + load_model = module.load_model + loaded = [] + sizes = [] + + def recorded_load(payload, manifest): + """Observe the real loader and estimator without replacing their behavior.""" + model = load_model(payload, manifest) + predict = model.predict + + def recorded_predict(values): + """The estimator must receive only the two trained feature columns.""" + sizes.append(values.shape) + return predict(values) + + model.predict = recorded_predict + loaded.append(model) + return model + + monkeypatch.setattr(module, "load_model", recorded_load) + worker = module._prediction_iterator( + regression_bundle.model_payload, regression_bundle.manifest, ("id",), 2 + ) + batch = pd.DataFrame({"id": range(5), "x": np.zeros(5), "z": np.zeros(5)}) + result = pd.concat(worker(iter([batch, batch.head(0), batch.iloc[:3]])), ignore_index=True) + assert len(loaded) == 1 + assert sizes == [(2, 2), (2, 2), (1, 2), (2, 2), (1, 2)] + assert result.id.tolist() == [0, 1, 2, 3, 4, 0, 1, 2] + np.testing.assert_allclose(result.prediction, loaded[0].intercept_) + + +def test_worker_checks_runtime_before_loading_model(regression_bundle, monkeypatch): + """A worker with incompatible packages must reject even driver-validated model bytes.""" + module = importlib.import_module("skyulf.inference.spark") + metadata = importlib.import_module("skyulf.inference._manifest") + requirements = regression_bundle.manifest.requirements + monkeypatch.setattr( + metadata, + "runtime_requirements", + lambda: tuple( + (name, "0.0.0" if name == "scikit-learn" else version) for name, version in requirements + ), + ) + + def forbidden(*args, **kwargs): + """Pickle must not run on an incompatible worker.""" + pytest.fail("Runtime mismatch reached model loading") + + monkeypatch.setattr(module, "load_model", forbidden) + worker = module._prediction_iterator( + regression_bundle.model_payload, regression_bundle.manifest, ("id",), 2 + ) + with pytest.raises(ValueError, match="runtime mismatch"): + list(worker(iter([]))) + + +def test_only_keys_and_model_features_reach_worker(spark, regression_bundle, monkeypatch): + """Unused nested or wide fields must be projected before Arrow serialization.""" + frame = spark.createDataFrame([(1, 150.0, 9.0)], "id long, x double, z double") + frame = frame.selectExpr("id", "x", "array('large', 'unused') as baggage", "z") + observed = [] + original = type(frame).mapInPandas + + def recorded_map(self, func, schema, **kwargs): + """Observe the real distributed boundary and retain its actual execution.""" + observed.append(self.columns) + return original(self, func, schema, **kwargs) + + monkeypatch.setattr(type(frame), "mapInPandas", recorded_map) + rows = _predict(frame, regression_bundle).collect() + assert observed == [["id", "x", "z"]] + np.testing.assert_allclose([row.prediction for row in rows], [280.0]) + + +def test_inference_import_does_not_require_spark(): + """Publishing the Spark entry point must not make optional runtimes mandatory.""" + code = """ +import importlib.abc +import sys +class BlockExtras(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname.split('.')[0] in {'pyspark', 'mlflow'}: + raise ImportError('optional runtime deliberately unavailable') +sys.meta_path.insert(0, BlockExtras()) +from skyulf.inference import predict_spark, predict_local +assert callable(predict_spark) and callable(predict_local) +assert not any(name.split('.')[0] in {'pyspark', 'mlflow'} for name in sys.modules) +""" + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, timeout=30 + ) + assert result.returncode == 0, result.stderr From a910e08bfc2a21701cd70ddb7cdbf5b8db6cc2a2 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Mon, 21 Sep 2026 23:48:58 +0300 Subject: [PATCH 12/85] docs: explain inference paths with diagrams Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 3 + docs/assets/diagrams/inference/local.mmd | 16 ++ docs/assets/diagrams/inference/local.svg | 1 + .../diagrams/inference/spark_native.mmd | 20 ++ .../diagrams/inference/spark_native.svg | 1 + .../inference/spark_python_planned.mmd | 23 ++ .../inference/spark_python_planned.svg | 1 + docs/assets/diagrams/inference/training.mmd | 22 ++ docs/assets/diagrams/inference/training.svg | 1 + docs/user_guide/inference_bundles.md | 3 + docs/user_guide/inference_flow.md | 205 ++++++++++++++++++ docs/user_guide/spark.md | 3 + mkdocs.yml | 1 + 13 files changed, 300 insertions(+) create mode 100644 docs/assets/diagrams/inference/local.mmd create mode 100644 docs/assets/diagrams/inference/local.svg create mode 100644 docs/assets/diagrams/inference/spark_native.mmd create mode 100644 docs/assets/diagrams/inference/spark_native.svg create mode 100644 docs/assets/diagrams/inference/spark_python_planned.mmd create mode 100644 docs/assets/diagrams/inference/spark_python_planned.svg create mode 100644 docs/assets/diagrams/inference/training.mmd create mode 100644 docs/assets/diagrams/inference/training.svg create mode 100644 docs/user_guide/inference_flow.md diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index e482817b0..2e1e37481 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -80,6 +80,9 @@ execution and MLflow adapters remain under development. package checks precede submission. Model loading is reused within each iterator, and unused input columns do not reach workers. The bundle guide includes a Spark example and explains compatibility with existing pipeline/backend artifacts. +- [Illustrated inference guide](../docs/user_guide/inference_flow.md) covering + fitted FE/model reuse, a numerical local/Spark example, and available versus + planned inference paths. Includes four SVG diagrams and editable Mermaid sources. ### Planned scope — not yet available diff --git a/docs/assets/diagrams/inference/local.mmd b/docs/assets/diagrams/inference/local.mmd new file mode 100644 index 000000000..cb263ffc7 --- /dev/null +++ b/docs/assets/diagrams/inference/local.mmd @@ -0,0 +1,16 @@ +flowchart TD + accTitle: Local inference paths + accDescr: Raw input receives fitted FE and model prediction. Prepared feature input bypasses FE. + raw["New raw data
input_stage = raw"]:::plain + prepared["Already prepared features
input_stage = features"]:::plain + checkraw["Validate bundle and raw schema"]:::check + checkfeatures["Validate bundle and feature schema"]:::check + fe["Apply saved FE
Local pandas / Polars"]:::work + model["Predict with the saved model
Local Python"]:::work + output["Prediction result
pandas DataFrame"]:::plain + raw --> checkraw --> fe --> model + prepared --> checkfeatures --> model + model --> output + classDef plain fill:#ffffff,stroke:#64748b,color:#172b3a + classDef check fill:#e8f0fb,stroke:#245997,color:#172b3a + classDef work fill:#e9f5ee,stroke:#287447,color:#172b3a diff --git a/docs/assets/diagrams/inference/local.svg b/docs/assets/diagrams/inference/local.svg new file mode 100644 index 000000000..55c61ea79 --- /dev/null +++ b/docs/assets/diagrams/inference/local.svg @@ -0,0 +1 @@ +Local inference pathsRaw input receives fitted FE and model prediction. Prepared feature input bypasses FE.New raw datainput_stage = rawAlready prepared featuresinput_stage = featuresValidate bundle and rawschemaValidate bundle and featureschemaApply saved FELocal pandas / PolarsPredict with the savedmodelLocal PythonPrediction resultpandas DataFrame diff --git a/docs/assets/diagrams/inference/spark_native.mmd b/docs/assets/diagrams/inference/spark_native.mmd new file mode 100644 index 000000000..c9b2b841d --- /dev/null +++ b/docs/assets/diagrams/inference/spark_native.mmd @@ -0,0 +1,20 @@ +flowchart TD + accTitle: Available native Spark FE and Python model inference + accDescr: Spark data stays distributed. Saved FE rules execute as native Spark expressions; prepared feature batches reach the same Python model on workers. + bundle["Driver: load bundle
Validate support, schema, versions"]:::check + raw["Distributed Spark input
Raw features + row_keys"]:::plain + fe["Native FE on Spark partitions
Apply saved transformation rules"]:::work + a["Python worker A
Prepared feature batch
Predict with the same model"]:::work + b["Python worker B
Prepared feature batch
Predict with the same model"]:::work + result["Spark DataFrame
row_keys + prediction"]:::plain + raw --> fe + bundle -.->|"Learned FE state"| fe + bundle -.->|"Model payload"| a + bundle -.->|"Model payload"| b + fe -->|"Features + keys"| a + fe -->|"Features + keys"| b + a --> result + b --> result + classDef plain fill:#ffffff,stroke:#64748b,color:#172b3a + classDef check fill:#e8f0fb,stroke:#245997,color:#172b3a + classDef work fill:#e9f5ee,stroke:#287447,color:#172b3a diff --git a/docs/assets/diagrams/inference/spark_native.svg b/docs/assets/diagrams/inference/spark_native.svg new file mode 100644 index 000000000..0e8ab4a69 --- /dev/null +++ b/docs/assets/diagrams/inference/spark_native.svg @@ -0,0 +1 @@ +Available native Spark FE and Python model inferenceSpark data stays distributed. Saved FE rules execute as native Spark expressions; prepared feature batches reach the same Python model on workers.Learned FE stateModel payloadModel payloadFeatures + keysFeatures + keysDriver: load bundleValidate support, schema,versionsDistributed Spark inputRaw features + row_keysNative FE on SparkpartitionsApply saved transformationrulesPython worker APrepared feature batchPredict with the samemodelPython worker BPrepared feature batchPredict with the samemodelSpark DataFramerow_keys + prediction diff --git a/docs/assets/diagrams/inference/spark_python_planned.mmd b/docs/assets/diagrams/inference/spark_python_planned.mmd new file mode 100644 index 000000000..94cfbcc17 --- /dev/null +++ b/docs/assets/diagrams/inference/spark_python_planned.mmd @@ -0,0 +1,23 @@ +flowchart TD + accTitle: Planned Python FE and model inference inside Spark workers + accDescr: SM-10 is not implemented. The planned path distributes raw batches and applies fitted Python FE and the model inside each worker. + status["SM-10: PLANNED
python_pipeline is not available yet"]:::future + raw["Distributed Spark input
Raw features + row_keys"]:::plain + subgraph wa["Python worker A — planned"] + fea["Batch-independent Python FE
Apply saved transformation rules"]:::future + ma["Predict with the same fitted model"]:::future + fea --> ma + end + subgraph wb["Python worker B — planned"] + feb["Batch-independent Python FE
Apply saved transformation rules"]:::future + mb["Predict with the same fitted model"]:::future + feb --> mb + end + result["Spark DataFrame
row_keys + prediction"]:::plain + status -.-> raw + raw -->|"Raw batch + keys"| wa + raw -->|"Raw batch + keys"| wb + ma --> result + mb --> result + classDef plain fill:#ffffff,stroke:#64748b,color:#172b3a + classDef future fill:#fff0e8,stroke:#aa4b23,color:#172b3a diff --git a/docs/assets/diagrams/inference/spark_python_planned.svg b/docs/assets/diagrams/inference/spark_python_planned.svg new file mode 100644 index 000000000..18cc46c59 --- /dev/null +++ b/docs/assets/diagrams/inference/spark_python_planned.svg @@ -0,0 +1 @@ +Planned Python FE and model inference inside Spark workersSM-10 is not implemented. The planned path distributes raw batches and applies fitted Python FE and the model inside each worker.Python worker B — plannedPython worker A — plannedRaw batch + keysRaw batch + keysSM-10: PLANNEDpython_pipeline is notavailable yetDistributed Spark inputRaw features + row_keysBatch-independent PythonFEApply saved transformationrulesPredict with the same fittedmodelBatch-independent PythonFEApply saved transformationrulesPredict with the same fittedmodelSpark DataFramerow_keys + prediction diff --git a/docs/assets/diagrams/inference/training.mmd b/docs/assets/diagrams/inference/training.mmd new file mode 100644 index 000000000..e9e5f8e3b --- /dev/null +++ b/docs/assets/diagrams/inference/training.mmd @@ -0,0 +1,22 @@ +flowchart TD + accTitle: From training to an inference bundle + accDescr: pandas or Polars training produces fitted FE state, a Python model and schema metadata, saved together in a bundle. + train["Training data
pandas / Polars"]:::plain + fitfe["Fit FE: learn rules
and transform training data"]:::work + features["Prepared model features"]:::plain + fitmodel["Fit model on these features"]:::work + state["features.json
Learned FE state"]:::saved + model["model.pkl
Fitted Python model"]:::saved + schema["manifest.json
Columns, order, dtypes, versions"]:::saved + bundle["Save inference bundle
Load and reuse on new data"]:::saved + train --> fitfe --> features --> fitmodel + fitfe -.-> state + fitmodel -.-> model + train -.-> schema + features -.-> schema + state --> bundle + model --> bundle + schema --> bundle + classDef plain fill:#ffffff,stroke:#64748b,color:#172b3a + classDef work fill:#e9f5ee,stroke:#287447,color:#172b3a + classDef saved fill:#e8f0fb,stroke:#245997,color:#172b3a diff --git a/docs/assets/diagrams/inference/training.svg b/docs/assets/diagrams/inference/training.svg new file mode 100644 index 000000000..bbb8ce93f --- /dev/null +++ b/docs/assets/diagrams/inference/training.svg @@ -0,0 +1 @@ +From training to an inference bundlepandas or Polars training produces fitted FE state, a Python model and schema metadata, saved together in a bundle.Training datapandas / PolarsFit FE: learn rulesand transform training dataPrepared model featuresFit model on these featuresfeatures.jsonLearned FE statemodel.pklFitted Python modelmanifest.jsonColumns, order, dtypes,versionsSave inference bundleLoad and reuse on newdata diff --git a/docs/user_guide/inference_bundles.md b/docs/user_guide/inference_bundles.md index 80ff05cf2..8387d600b 100644 --- a/docs/user_guide/inference_bundles.md +++ b/docs/user_guide/inference_bundles.md @@ -5,6 +5,9 @@ estimator with an explicit inference contract. It supports local pandas/Polars prediction and native Spark FE followed by Python regression on Spark workers. Importing `skyulf.inference` requires neither PySpark nor MLflow. +Start with [How inference works](inference_flow.md) for training and inference +diagrams and a worked example of reusing the same fitted FE and model. + ## Raw data and prepared features Choose the input stage when building a bundle: diff --git a/docs/user_guide/inference_flow.md b/docs/user_guide/inference_flow.md new file mode 100644 index 000000000..7a0ca6b80 --- /dev/null +++ b/docs/user_guide/inference_flow.md @@ -0,0 +1,205 @@ +# How inference works: pandas, Polars and Spark + +**Status: 0.9.0 development branch, SM-09 complete.** This guide explains how +fitted feature engineering (FE) and a trained model are reused on new data. + +The principle is the same in each path: **learn during training → save an +artifact → apply the saved transformations → predict with the trained model.** +Inference does not refit the imputer, scaler or model. + +Supported pandas/Polars-to-Spark paths are tested to preserve the prediction +function. This does not imply that every Python pipeline automatically works +on Spark. Compatibility depends on each FE implementation, the recorded schema +and the runtime environment. + +## 1. What training saves + +![Training produces fitted FE state, a Python model and schema metadata in one bundle](../assets/diagrams/inference/training.svg) + +[Editable Mermaid source](../assets/diagrams/inference/training.mmd) + +Suppose we train this pipeline using pandas or Polars: + +```text +SimpleImputer(mean) → StandardScaler → LinearRegression +``` + +The bundle contains the fitted FE state and input contract alongside the model: + +| Part | Saved information | Purpose during inference | +| --- | --- | --- | +| `features.json` | Step order, columns, learned fill values and scaler statistics | Reapply the same transformations | +| `model.pkl` | The fitted sklearn estimator and learned parameters | Call the trained model's `predict` method | +| `manifest.json` | Raw/model columns, order, dtypes, versions, output contract and content identities | Detect invalid inputs and incompatible packages | + +JSON does not translate Python code into Spark code. **We implement the code +that applies the saved state.** For example, the Spark StandardScaler applier +constructs native Spark expressions using the saved means and scales. + +The model is not converted into a Spark MLlib model. It remains the trained +Python/sklearn estimator. In distributed inference, it runs on Spark workers. +Model training here still uses the local pandas/Polars path. Fitting FE on Spark +and training a model across a cluster are separate capabilities. + +## 2. Why the same row should receive the same prediction + +Consider two training rows: `amount=[10.0, 30.0]`, `target=[100.0, 300.0]`. +The learned values in this example are: + +```text +Imputer: replace missing amount with 20. +Scaler: z = (amount - 20) / 10 +Model: prediction = 100 × z + 200 +``` + +Each inference path should apply these same learned values to new data: + +| Row key | New amount | After imputation | After scaling: z | Prediction | +| --- | --- | --- | --- | --- | +| 101 | 40.0 | 40.0 | 2.0 | 400.0 | +| 102 | missing | 20.0 | 0.0 | 200.0 | + +Spark does not calculate a new mean for each partition. Workers do not train +separate models. Each row uses the saved `20`, `10` and the same model parameters. +Floating-point results are compared within appropriate numerical tolerances; +bit-for-bit equality is not a universal guarantee. + +## 3. Local inference — available + +![Local inference applies FE to raw input and bypasses FE for prepared features](../assets/diagrams/inference/local.svg) + +[Editable Mermaid source](../assets/diagrams/inference/local.mmd) + +`predict_local(frame, bundle)` runs in one Python process: + +1. Validate the bundle and input schema. +2. For an `input_stage="raw"` bundle, apply the saved FE to pandas/Polars input. +3. Validate the resulting model columns and their order, then predict. +4. Return a pandas DataFrame. + +An `input_stage="features"` bundle expects already prepared model features and +bypasses FE. Applying the scaler again to `z=2` would produce the wrong model +input. The raw/features distinction makes the caller's responsibility explicit; +the system cannot determine from numbers alone whether scaling already happened. + +The new bundle API's initial support is narrower than the existing local pipeline +API. Existing local transformations have not been removed because they are not +yet supported by this new format. + +## 4. Native Spark FE + Python model — available + +![Distributed native Spark FE followed by the same Python model on worker batches](../assets/diagrams/inference/spark_native.svg) + +[Editable Mermaid source](../assets/diagrams/inference/spark_native.mmd) + +Solid arrows show data flow. Dashed arrows show saved FE state or model payload +transfer. Raw data is not collected into a pandas DataFrame on the driver. + +`predict_spark(..., mode="native_features")` follows these steps: + +1. The driver validates the bundle and execution request: supported FE, raw input, + a regression model, column order/dtypes and compatible package versions. +2. Spark FE appliers turn the learned rules into Spark expressions. Their model + output schema is checked before any data action. +3. Spark validates unique, non-null row keys and applies FE across the distributed + frame. Key and row preservation are checked as well. +4. Only prepared model features and row keys reach the Python workers. +5. Each worker iterator loads the same model payload. It predicts on its + pandas/NumPy batches without applying FE again. +6. The result is a Spark DataFrame containing `row_keys + prediction`. + +**Pandas describes the small piece being processed inside a worker.** The entire +Spark table is not collected to the driver for local prediction. Spark continues +distributing partitions across workers. The two workers in the diagram are +illustrative; Spark determines the actual task and worker count. + +The model is loaded once per iterator and reused across prediction chunks. +A new task, retry or later action may load it again. Spark does not guarantee +physical row order, so results are matched by keys such as `id`. Keys do not +automatically become model features. + +Validation executes some distributed actions and returns only bounded control +results to the driver. Prediction remains a lazy Spark DataFrame: an action such +as `show`, `collect` or writing to a sink executes model prediction. The runner +does not itself write a table or schedule a monthly job. + +## 5. Python FE + model inside workers — planned SM-10 + +![Planned path: Spark distributes raw batches and workers apply fitted Python FE and the model](../assets/diagrams/inference/spark_python_planned.svg) + +[Editable Mermaid source](../assets/diagrams/inference/spark_python_planned.mmd) + +This path is **not implemented yet**. `mode="python_pipeline"` currently raises +an error. The planned path distributes raw batches and runs compatible fitted +Python FE together with the model inside each worker. + +This also keeps the dataset distributed. The distinction is where FE executes: +native Spark expressions or Python code inside worker batches. + +Not every Python transformation is independent of batch boundaries: + +- **Apply saved, fixed bin boundaries:** each row can be handled independently, + provided the required state format, adapter and compatibility tests exist. +- **Learn new bin boundaries from each batch:** changes the training transformation + and must not happen during inference. +- **Rolling/lag:** a required preceding row may belong to another partition. + Independent batches can give incorrect results without explicit ordering and + window context. + +Being batch-independent does not automatically make a node supported today. +Packaging, execution and compatibility checks must also be implemented. An +unsupported native FE step will not silently fall back to this worker path. + +## 6. What compatibility means + +**Training with pandas or Polars is not itself a problem.** When FE semantics, +model features and the trained estimator are preserved, supported paths are +expected and tested to produce matching predictions. + +The limitation concerns arbitrary operations inside arbitrary artifacts: + +| Situation | Current behavior | +| --- | --- | +| Supported imputer/scaler, compatible schema and runtime | Local/Spark prediction parity is tested | +| FE without a supported Spark applier or portable-state codec | Unsupported by the new bundle/native path; no silent fallback | +| Wrong feature order, missing columns or a different native FE output dtype | Error instead of silent correction | +| Incompatible model/runtime versions | Error; prepare compatible driver and worker environments | +| Nullable integer/boolean model-feature schema | The initial Spark runner rejects it before actions due to Arrow conversion risks | +| An existing backend artifact dictionary supplied as a new bundle | Rejected; the backend adapter is planned for SM-18 | + +Current native FE support covers **SimpleImputer mean/constant and StandardScaler**; +an empty FE chain is also supported. The first Spark model runner accepts **raw +input and regression**. Local bundle classification support does not mean that +distributed classification is complete; that validation gate is SM-11. + +Row keys can be integer/string/boolean. Integer/boolean model features require +a non-nullable Spark schema; keys have a separate non-null value check. +See the [bundle guide](inference_bundles.md) for detailed dtype, input-stage and +runtime-version requirements. + +## 7. Relationship to existing artifacts + +Saving and loading the model together with fitted FE already existed in Skyulf. +That principle is preserved. The new bundle carries the same kind of information +with an explicit contract that the distributed runner can validate and execute. + +Existing `SkyulfPipeline.save/load` and backend `.joblib` paths remain available. +This does not make every old file a direct `predict_spark` input. Building a new +standalone bundle requires recorded schemas and supported FE; adapting the old +backend artifact format is a separate delivery. + +| Inference path | Where FE runs | Where the model runs | Status | +| --- | --- | --- | --- | +| Local raw | Local pandas/Polars | The same local Python process | Available | +| Local prepared features | Already prepared; FE is bypassed here | Local Python process | Available | +| Spark native features | Native Spark operations | Spark Python worker batches | SM-09: raw + regression | +| Spark Python pipeline | Python FE inside a Spark worker | Python model in the same worker | SM-10: planned | + +Local/Spark describes where and how computation runs. Monthly batch scheduling, +HTTP endpoints and SQL access describe how it is invoked; they are separate from +the training or FE algorithm. MLflow/Unity Catalog packaging and registry support, +real Databricks validation, endpoints and templates remain later stages. + +For runnable code, see the [native Spark inference example](inference_bundles.md#native-spark-fe-and-worker-model-inference). +The SVG diagrams on this page display without Mermaid support; each has an +editable source linked above. diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 9f00a4f6c..f28ee0e3b 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -11,6 +11,9 @@ applies native FE and runs a Python regression model in worker batches. Other native nodes, worker Python FE and distributed classification remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. +[How inference works](inference_flow.md) explains how the saved FE and +model are reused, with diagrams for local, native Spark and planned worker FE paths. + ## Why a separate environment? `.venv-spark` isolates PySpark and its dependencies from the web application's diff --git a/mkdocs.yml b/mkdocs.yml index f1dec0acc..b8d3bc960 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -75,6 +75,7 @@ nav: - Installation: user_guide/installation.md - Spark (Development): user_guide/spark.md - Inference Bundles (Development): user_guide/inference_bundles.md + - Inference Flow (Development): user_guide/inference_flow.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md From 0070813ae5eee0a406a17ad665ea24db6ccf9118 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 00:00:30 +0300 Subject: [PATCH 13/85] docs: record Spark inference session handoff Signed-off-by: flyingriverhorse --- initiatives/spark_and_mlflow/HANDOFF.md | 63 ++++++++++++++++++++++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 2 + 2 files changed, 65 insertions(+) create mode 100644 initiatives/spark_and_mlflow/HANDOFF.md diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md new file mode 100644 index 000000000..63e0fbc5e --- /dev/null +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -0,0 +1,63 @@ +# Session handoff - 2026-09-21 + +Work is parked at the user's request. Resume with SM-10 when requested. +Target release: 0.9.0. Branch: `090`. + +## Starting point + +- SM-00 through SM-09 are complete; SM-10 remains READY and is not implemented. +- Last implementation commit: `74ceacb9` (native Spark batch model inference). +- Last guide commit: `a910e08b` (English inference explanation and four diagrams). +- Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and + the SM-10 section of [02-inference-plan.md](02-inference-plan.md) before coding. +- User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). + +## Confirmed terminology and intended workflow + +`local` describes single-machine execution, not the user's personal computer. +The runtime environment and the execution engine are independent choices. +Local pandas/Polars FE and sklearn training may run inside Databricks; a later +Spark inference job may also run inside Databricks. + +The user's intended workflow is: + +```text +Databricks training job: pandas/Polars FE + sklearn model + -> Save fitted FE, model and input contract + -> Databricks scoring job: Spark FE + Python model on workers + -> Write predictions to a Delta table, for example monthly +``` + +This is the intended deployment scenario, not a claim that the complete +Databricks integration has already been validated. Scheduling, Delta delivery, +MLflow/Unity Catalog, endpoints and templates retain their later queue stages. +Keep new documentation and diagram labels in English. + +## Current execution boundaries + +- `predict_local` consumes the new standalone bundle; the frontend does not + call it yet. Frontend inference uses `POST /deployment/predict` and + `DeploymentService`, which loads the existing artifact, applies FE, aligns + model columns and predicts. The backend artifact bridge belongs to SM-18. +- `predict_spark(mode="native_features")` supports raw regression bundles + with supported native FE. Spark applies the saved rules; Python workers run + the same fitted model on batches. There is no full-data driver collection. +- Portable FE currently supports SimpleImputer mean/constant, StandardScaler + and an empty chain. Unsupported steps fail explicitly. +- Spark FE fit -> export -> restore -> Spark apply is available. This does + not imply that end-to-end distributed model training is implemented. +- `mode="python_pipeline"` is still rejected. SM-10 adds compatible fitted + Python FE and model execution together inside workers, without refitting, + while rejecting unsupported context-dependent or row-changing operations. + +## Verification and workspace + +Before parking, the English guide's example was checked with both pandas and +Polars training: local and Spark predictions matched `[400.0, 200.0]`. +The strict documentation build, four rendered diagrams and commit hooks passed. +Broader implementation evidence is recorded under SM-09 in OPEN_QUEUE.md; +those suites were not rerun for this handoff-only update. + +Three pre-existing untracked directories remain outside this change: +`.tmp-review-model/`, `.tmp-spark-review-full/`, `.tmp-spark-review-pytest/`. +Preserve them; do not stage or delete them as part of the next task. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 87f2be3e0..04b478b60 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -3,6 +3,8 @@ Güncelleme: 2026-09-21. **SM-00–SM-09 tamamlandı; sıradaki SM-10. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. +Session parked on 2026-09-21: read [HANDOFF.md](HANDOFF.md) before resuming SM-10. + Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. From df63d231da3d91c1157ba5f9f0f7ea0dba88d9bb Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 13:21:04 +0300 Subject: [PATCH 14/85] feat(core): add worker Python pipeline inference Signed-off-by: flyingriverhorse --- skyulf-core/skyulf/inference/spark.py | 129 ++++++++++++-- .../spark/test_native_features_inference.py | 1 - .../spark/test_python_pipeline_inference.py | 159 ++++++++++++++++++ 3 files changed, 271 insertions(+), 18 deletions(-) create mode 100644 skyulf-core/tests/spark/test_python_pipeline_inference.py diff --git a/skyulf-core/skyulf/inference/spark.py b/skyulf-core/skyulf/inference/spark.py index c2f5290f0..cbfebaf82 100644 --- a/skyulf-core/skyulf/inference/spark.py +++ b/skyulf-core/skyulf/inference/spark.py @@ -1,4 +1,4 @@ -"""Native Spark preprocessing followed by bounded worker-side Python prediction.""" +"""Spark inference with native or worker-local portable Python preprocessing.""" import importlib from collections.abc import Callable, Iterator @@ -8,7 +8,7 @@ from ..core.capabilities import UnsupportedExecutionError from ..core.execution import ExecutionOptions, FrameSpec -from ..preprocessing._spark import _column, _native, _resolved_names +from ..preprocessing._spark import _column, _native, _resolved_names, _validate_keys from ..preprocessing.pipeline import FeatureEngineer from ._manifest import BundleManifest, check_runtime, checksum from ._model import load_model @@ -23,9 +23,10 @@ def predict_spark( options: ExecutionOptions, mode: str, ) -> Any: - """Apply frozen native FE and distribute a regression estimator over Spark workers. + """Apply frozen FE and distribute a regression estimator over Spark workers. - Currently accepts raw regression bundles with native row-preserving FE. + Raw regression bundles support native Spark FE (``native_features``) and + portable pandas FE in each worker iterator (``python_pipeline``). Supply unique non-null integer, string or boolean keys; output contains those keys and prediction, with no row ordering guarantee. Extra unused input columns are projected away. Declared features must retain their @@ -48,14 +49,17 @@ def predict_spark( raise ValueError("predict_spark requires ExecutionOptions(engine='spark').") if frame_spec.target is not None: raise ValueError("Inference frame_spec must not declare a target.") - if mode != "native_features": + if mode not in ("native_features", "python_pipeline"): raise UnsupportedExecutionError( - "inference", "predict", "spark", "Only mode='native_features' is implemented." + "inference", + "predict", + "spark", + "Only mode='native_features' or mode='python_pipeline' is implemented.", ) _validate_bundle(bundle, options) manifest = bundle.manifest if manifest.input_stage != "raw": - raise ValueError("native_features currently requires a raw input_stage bundle.") + raise ValueError(f"{mode} currently requires a raw input_stage bundle.") if manifest.task != "regression": raise UnsupportedExecutionError( "inference", "predict", "spark", "Only regression bundles are currently supported." @@ -66,12 +70,31 @@ def predict_spark( "inference", "predict", "spark", "Streaming inference is not supported." ) _validate_names_and_keys(native, manifest, frame_spec) - raw_names = {column.name for column in manifest.input_schema} - raw = native.select(*[_column(native, name) for name in native.columns if name in raw_names]) + input_names = {column.name for column in manifest.input_schema} + raw = native.select(*[_column(native, name) for name in native.columns if name in input_names]) _validate_frame(raw, manifest.input_schema, "bundle input") - selected = native.select( - *[_column(native, name) for name in (*frame_spec.row_keys, *raw.columns)] + selected_names = ( + tuple(frame_spec.row_keys) + tuple(column.name for column in manifest.input_schema) + if mode == "python_pipeline" + else tuple(frame_spec.row_keys) + tuple(raw.columns) ) + selected = native.select(*[_column(native, name) for name in selected_names]) + if mode == "python_pipeline": + engineer = FeatureEngineer.from_state( + bundle.feature_state, + execution_options=ExecutionOptions("pandas", state_max_bytes=options.state_max_bytes), + ) + _validate_python_pipeline(engineer) + _validate_keys(native, frame_spec) + worker = _python_pipeline_prediction_iterator( + bundle.feature_state, + bundle.model_payload, + manifest, + frame_spec.row_keys, + options.python_batch_rows, + options.state_max_bytes, + ) + return selected.mapInPandas(worker, schema=_prediction_schema(native, manifest, frame_spec)) engineer = FeatureEngineer.from_state( bundle.feature_state, execution_options=options, frame_spec=frame_spec ) @@ -86,18 +109,90 @@ def predict_spark( worker_frame = transformed.select( *[_column(transformed, name) for name in (*frame_spec.row_keys, *features.columns)] ) + schema = _prediction_schema(native, manifest, frame_spec) + worker = _prediction_iterator( + bundle.model_payload, manifest, frame_spec.row_keys, options.python_batch_rows + ) + return worker_frame.mapInPandas(worker, schema=schema) + + +def _prediction_schema(native: Any, manifest: BundleManifest, spec: FrameSpec) -> Any: + """Build the stable Spark output schema from source key fields and the manifest.""" types = importlib.import_module("pyspark.sql.types") - schema = types.StructType( - [native.schema[key] for key in frame_spec.row_keys] + return types.StructType( + [native.schema[key] for key in spec.row_keys] + [ types.StructField(column.name, types.DoubleType(), True) for column in manifest.output_schema ] ) - worker = _prediction_iterator( - bundle.model_payload, manifest, frame_spec.row_keys, options.python_batch_rows - ) - return worker_frame.mapInPandas(worker, schema=schema) + + +def _validate_python_pipeline(engineer: FeatureEngineer) -> None: + """Allow only the frozen, row-independent portable FE nodes in worker mode.""" + supported = {"SimpleImputer", "StandardScaler"} + for step in engineer.fitted_steps: + node_type = step["type"] + params = step.get("params", {}) + if node_type == "SimpleImputer" and params.get("strategy", "mean") not in ( + "mean", + "constant", + ): + raise UnsupportedExecutionError( + node_type, + "apply", + "spark", + "python_pipeline supports only mean or constant SimpleImputer state.", + ) + if node_type not in supported: + raise UnsupportedExecutionError( + node_type, + "apply", + "spark", + "python_pipeline requires portable row-independent, row-preserving FE.", + ) + + +def _python_pipeline_prediction_iterator( + feature_state: bytes, + payload: bytes, + manifest: BundleManifest, + row_keys: tuple[str, ...], + batch_rows: int, + state_max_bytes: int, +) -> Callable[[Iterator[pd.DataFrame]], Iterator[pd.DataFrame]]: + """Restore portable pandas FE once, then apply it to each Arrow batch before prediction.""" + + def predict_batches(batches: Iterator[pd.DataFrame]) -> Iterator[pd.DataFrame]: + """Run frozen local FE and one loaded estimator across worker batches.""" + check_runtime(manifest) + if checksum(feature_state) != manifest.fe_sha256: + raise ValueError("Bundle feature state checksum mismatch on worker.") + if checksum(payload) != manifest.model_sha256: + raise ValueError("Bundle payload checksum mismatch on worker.") + engineer = FeatureEngineer.from_state( + feature_state, + execution_options=ExecutionOptions("pandas", state_max_bytes=state_max_bytes), + ) + _validate_python_pipeline(engineer) + model = load_model(payload, manifest) + raw_columns = [column.name for column in manifest.input_schema] + for batch in batches: + if batch.empty: + continue + source = batch.loc[:, [*row_keys, *raw_columns]] + transformed = engineer.transform(source, preserve_rows=True) + features = transformed.loc[:, list(manifest.feature_order)] + _validate_frame(features, manifest.feature_schema, "worker model features") + for offset in range(0, len(features), batch_rows): + chunk = features.iloc[offset : offset + batch_rows] + keys = source.iloc[offset : offset + batch_rows].loc[:, list(row_keys)] + predictions = _predict_features(chunk, model, manifest, chunk.index) + yield pd.concat( + [keys.reset_index(drop=True), predictions.reset_index(drop=True)], axis=1 + ) + + return predict_batches def _model_features(frame: Any, manifest: BundleManifest) -> Any: diff --git a/skyulf-core/tests/spark/test_native_features_inference.py b/skyulf-core/tests/spark/test_native_features_inference.py index c8a710d80..4c64d4fc8 100644 --- a/skyulf-core/tests/spark/test_native_features_inference.py +++ b/skyulf-core/tests/spark/test_native_features_inference.py @@ -124,7 +124,6 @@ def test_empty_partitions_and_composite_key_schema(spark, regression_bundle, emp ("date_key", "key.*dtype|key.*type"), ("target", "target"), ("stage", "raw|stage"), - ("mode", "mode|native_features"), ("engine", "engine|spark"), ("checksum", "checksum"), ("runtime", "runtime"), diff --git a/skyulf-core/tests/spark/test_python_pipeline_inference.py b/skyulf-core/tests/spark/test_python_pipeline_inference.py new file mode 100644 index 000000000..d518ef07c --- /dev/null +++ b/skyulf-core/tests/spark/test_python_pipeline_inference.py @@ -0,0 +1,159 @@ +"""Worker-side Python feature engineering must preserve local predictions.""" + +from dataclasses import replace + +import numpy as np +import pandas as pd +import pytest + +import skyulf.inference as inference +from skyulf.core.capabilities import UnsupportedExecutionError +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.inference._manifest import checksum, semantic_digest +from skyulf.inference.bundle import build_bundle, predict_local +from skyulf.inference.spark import _validate_python_pipeline +from skyulf.preprocessing.pipeline import FeatureEngineer + + +@pytest.fixture +def regression_bundle(fitted_regression_pipeline): + """Build a raw regression bundle from each local training engine.""" + return build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + + +def _predict(frame, bundle, **kwargs): + """Call the distributed runner with the explicit Spark contract.""" + return inference.predict_spark( + frame, + bundle, + frame_spec=kwargs.pop("frame_spec", FrameSpec(row_keys=("id",))), + options=kwargs.pop("options", ExecutionOptions("spark", python_batch_rows=2)), + mode=kwargs.pop("mode", "python_pipeline"), + **kwargs, + ) + + +@pytest.mark.parametrize("partitions,arrow_rows", [(1, 1), (3, 5)]) +def test_python_pipeline_matches_local_for_each_training_engine( + spark, regression_bundle, arrow_rows, partitions +): + """Worker Python FE must match predict_local across partition and Arrow boundaries.""" + raw = pd.DataFrame({"x": [150.0, 80.0, np.nan, 110.0], "z": [9.0, 3.0, 4.0, np.nan]}) + expected = predict_local(raw, regression_bundle) + frame = spark.createDataFrame( + [(10, 150.0, 9.0), (11, 80.0, 3.0), (12, None, 4.0), (13, 110.0, float("nan"))], + "id long, x double, z double", + ).repartition(partitions) + old_limit = spark.conf.get("spark.sql.execution.arrow.maxRecordsPerBatch") + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", str(arrow_rows)) + try: + rows = _predict(frame, regression_bundle).orderBy("id").collect() + finally: + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", old_limit) + np.testing.assert_allclose([row.prediction for row in rows], expected.prediction, rtol=1e-10) + assert [row.id for row in rows] == [10, 11, 12, 13] + + +def test_python_pipeline_applies_frozen_feature_state_once_per_worker_iterator( + regression_bundle, monkeypatch +): + """A worker iterator restores state once and transforms each nonempty batch once.""" + module = __import__("skyulf.inference.spark", fromlist=["FeatureEngineer"]) + original_restore = module.FeatureEngineer.from_state + restored = [] + transformed = [] + + def record_restore(*args, **kwargs): + """Record worker state restoration while retaining the real implementation.""" + engineer = original_restore(*args, **kwargs) + restored.append(engineer) + original_transform = engineer.transform + + def record_transform(data, **transform_kwargs): + """Record each frozen batch application without changing its result.""" + transformed.append(len(data)) + return original_transform(data, **transform_kwargs) + + engineer.transform = record_transform + return engineer + + monkeypatch.setattr(module.FeatureEngineer, "from_state", record_restore) + worker = module._python_pipeline_prediction_iterator( + regression_bundle.feature_state, + regression_bundle.model_payload, + regression_bundle.manifest, + ("id",), + 2, + 8 * 1024 * 1024, + ) + batches = iter( + [ + pd.DataFrame({"id": [1, 2], "x": [150.0, 80.0], "z": [9.0, 3.0]}), + pd.DataFrame({"id": [3], "x": [110.0], "z": [4.0]}), + ] + ) + result = pd.concat(worker(batches), ignore_index=True) + assert len(restored) == 1 + assert transformed == [2, 1] + assert result.columns.tolist() == ["id", "prediction"] + + +def test_python_pipeline_never_fits_or_materializes_source(spark, regression_bundle, monkeypatch): + """Distributed Python inference must not fit or collect the Spark source frame.""" + frame = spark.createDataFrame([(1, 150.0, 9.0)], "id long, x double, z double") + + def forbidden(*args, **kwargs): + """Fail if inference attempts training or full-frame materialization.""" + pytest.fail("inference attempted fitting or driver materialization") + + monkeypatch.setattr(type(frame), "toPandas", forbidden) + monkeypatch.setattr(type(frame), "toLocalIterator", forbidden) + monkeypatch.setattr( + __import__("skyulf.inference.spark", fromlist=["FeatureEngineer"]).FeatureEngineer, + "fit_transform", + forbidden, + ) + rows = _predict(frame, regression_bundle).collect() + assert len(rows) == 1 + + +def test_python_pipeline_rejects_unsupported_context_before_action( + spark, regression_bundle, monkeypatch +): + """Unknown portable pipeline state must be rejected before Spark validation actions.""" + frame = spark.createDataFrame([(1, 150.0, 9.0)], "id long, x double, z double") + payload = regression_bundle.feature_state.replace(b"SimpleImputer", b"RollingWindowStep") + manifest = regression_bundle.manifest.model_copy( + update={"fe_sha256": checksum(payload), "fe_semantic_digest": "invalid"} + ) + manifest = manifest.model_copy(update={"semantic_digest": semantic_digest(manifest)}) + unsupported = replace(regression_bundle, feature_state=payload, manifest=manifest) + for action in ("collect", "count", "first", "take", "toPandas", "toLocalIterator"): + monkeypatch.setattr( + type(frame), action, lambda *args, **kwargs: pytest.fail("Spark action") + ) + with pytest.raises( + (ValueError, UnsupportedExecutionError), match="portable|semantic|unsupported" + ): + _predict(frame, unsupported) + + +def test_python_pipeline_rejects_nonportable_imputer_strategy_before_action(regression_bundle): + """Median imputer state cannot silently enter the mean/constant worker path.""" + engineer = FeatureEngineer.from_state(regression_bundle.feature_state) + engineer.fitted_steps[0]["params"]["strategy"] = "median" + with pytest.raises(UnsupportedExecutionError, match="mean or constant"): + _validate_python_pipeline(engineer) + + +def test_native_mode_still_uses_native_feature_path(spark, regression_bundle): + """The native mode remains available after adding the Python pipeline mode.""" + frame = spark.createDataFrame([(1, 150.0, 9.0)], "id long, x double, z double") + rows = inference.predict_spark( + frame, + regression_bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark", python_batch_rows=2), + mode="native_features", + ).collect() + assert rows[0].id == 1 From add50eb7ff8ff870e81ce3a4a15da2ec4bbb2394 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 13:44:01 +0300 Subject: [PATCH 15/85] docs: mark SM-10 worker inference available Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 4 ++-- .../inference/spark_python_planned.mmd | 20 +++++++++---------- .../inference/spark_python_planned.svg | 2 +- docs/user_guide/inference_bundles.md | 11 +++++----- docs/user_guide/inference_flow.md | 17 +++++++++------- docs/user_guide/spark.md | 8 ++++---- .../spark_and_mlflow/02-inference-plan.md | 5 ++++- initiatives/spark_and_mlflow/HANDOFF.md | 16 ++++++++------- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 6 +++--- 9 files changed, 49 insertions(+), 40 deletions(-) diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 2e1e37481..d6d8a8b65 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -81,8 +81,8 @@ execution and MLflow adapters remain under development. and unused input columns do not reach workers. The bundle guide includes a Spark example and explains compatibility with existing pipeline/backend artifacts. - [Illustrated inference guide](../docs/user_guide/inference_flow.md) covering - fitted FE/model reuse, a numerical local/Spark example, and available versus - planned inference paths. Includes four SVG diagrams and editable Mermaid sources. + fitted FE/model reuse, a numerical local/Spark example, and available inference + paths. Includes four SVG diagrams and editable Mermaid sources. ### Planned scope — not yet available diff --git a/docs/assets/diagrams/inference/spark_python_planned.mmd b/docs/assets/diagrams/inference/spark_python_planned.mmd index 94cfbcc17..a3f1adc4c 100644 --- a/docs/assets/diagrams/inference/spark_python_planned.mmd +++ b/docs/assets/diagrams/inference/spark_python_planned.mmd @@ -1,16 +1,16 @@ flowchart TD - accTitle: Planned Python FE and model inference inside Spark workers - accDescr: SM-10 is not implemented. The planned path distributes raw batches and applies fitted Python FE and the model inside each worker. - status["SM-10: PLANNED
python_pipeline is not available yet"]:::future + accTitle: Python FE and model inference inside Spark workers + accDescr: SM-10 distributes raw batches and applies fitted Python FE and the model inside each worker. + status["SM-10: AVAILABLE
python_pipeline supports raw regression"]:::available raw["Distributed Spark input
Raw features + row_keys"]:::plain - subgraph wa["Python worker A — planned"] - fea["Batch-independent Python FE
Apply saved transformation rules"]:::future - ma["Predict with the same fitted model"]:::future + subgraph wa["Python worker A"] + fea["Batch-independent Python FE
Apply saved transformation rules"]:::available + ma["Predict with the same fitted model"]:::available fea --> ma end - subgraph wb["Python worker B — planned"] - feb["Batch-independent Python FE
Apply saved transformation rules"]:::future - mb["Predict with the same fitted model"]:::future + subgraph wb["Python worker B"] + feb["Batch-independent Python FE
Apply saved transformation rules"]:::available + mb["Predict with the same fitted model"]:::available feb --> mb end result["Spark DataFrame
row_keys + prediction"]:::plain @@ -20,4 +20,4 @@ flowchart TD ma --> result mb --> result classDef plain fill:#ffffff,stroke:#64748b,color:#172b3a - classDef future fill:#fff0e8,stroke:#aa4b23,color:#172b3a + classDef available fill:#e9f8ef,stroke:#267a45,color:#172b3a diff --git a/docs/assets/diagrams/inference/spark_python_planned.svg b/docs/assets/diagrams/inference/spark_python_planned.svg index 18cc46c59..96186779d 100644 --- a/docs/assets/diagrams/inference/spark_python_planned.svg +++ b/docs/assets/diagrams/inference/spark_python_planned.svg @@ -1 +1 @@ -Planned Python FE and model inference inside Spark workersSM-10 is not implemented. The planned path distributes raw batches and applies fitted Python FE and the model inside each worker.Python worker B — plannedPython worker A — plannedRaw batch + keysRaw batch + keysSM-10: PLANNEDpython_pipeline is notavailable yetDistributed Spark inputRaw features + row_keysBatch-independent PythonFEApply saved transformationrulesPredict with the same fittedmodelBatch-independent PythonFEApply saved transformationrulesPredict with the same fittedmodelSpark DataFramerow_keys + prediction +Python FE and model inference inside Spark workersSM-10 distributes raw batches and applies fitted Python FE and the model inside each worker.Python worker BPython worker ARaw batch + keysRaw batch + keysSM-10: AVAILABLEpython_pipeline supportsraw regressionDistributed Spark inputRaw features + row_keysBatch-independent PythonFEApply saved transformationrulesPredict with the same fittedmodelBatch-independent PythonFEApply saved transformationrulesPredict with the same fittedmodelSpark DataFramerow_keys + prediction diff --git a/docs/user_guide/inference_bundles.md b/docs/user_guide/inference_bundles.md index 8387d600b..8fcca8934 100644 --- a/docs/user_guide/inference_bundles.md +++ b/docs/user_guide/inference_bundles.md @@ -216,9 +216,10 @@ before prediction; prediction itself remains a lazy Spark computation. Validation does not freeze a changing source. The caller owns any snapshot or persist policy needed to keep validation and later actions on the same input. -The first distributed runner accepts `input_stage="raw"` and regression only. -Prepared-feature bundles, classification, streaming and the Python FE worker -mode are not enabled by this delivery. Local classification remains available. Databricks, +The distributed runners accept `input_stage="raw"` and regression only. +Prepared-feature bundles, classification and streaming remain unsupported. +The Python FE worker mode is available for the portable row-independent path; +local classification remains available. Databricks, Spark Connect and worker-wheel isolation still require their later validation gates; local PySpark tests do not establish those deployment guarantees. @@ -259,8 +260,8 @@ Changing the inference engine does not make every fitted Python transformer a native Spark operation. For example, a future binning adapter must use the saved training bin boundaries; it must not discover new boundaries from each inference batch. The native path requires an implemented Spark applier and a supported -state codec. The planned Python-worker path requires explicit support for -independent batches and row preservation. Rolling/lag and transformations that +state codec. The Python-worker path requires explicit support for independent +batches and row preservation. Rolling/lag and transformations that need neighboring rows cannot be made correct merely by putting them inside a worker batch. Unsupported combinations fail explicitly; there is no automatic conversion of a whole Spark dataset to local pandas or Polars. diff --git a/docs/user_guide/inference_flow.md b/docs/user_guide/inference_flow.md index 7a0ca6b80..fda9b87db 100644 --- a/docs/user_guide/inference_flow.md +++ b/docs/user_guide/inference_flow.md @@ -1,6 +1,6 @@ # How inference works: pandas, Polars and Spark -**Status: 0.9.0 development branch, SM-09 complete.** This guide explains how +**Status: 0.9.0 development branch, SM-10 complete.** This guide explains how fitted feature engineering (FE) and a trained model are reused on new data. The principle is the same in each path: **learn during training → save an @@ -123,15 +123,16 @@ results to the driver. Prediction remains a lazy Spark DataFrame: an action such as `show`, `collect` or writing to a sink executes model prediction. The runner does not itself write a table or schedule a monthly job. -## 5. Python FE + model inside workers — planned SM-10 +## 5. Python FE + model inside workers — available in SM-10 -![Planned path: Spark distributes raw batches and workers apply fitted Python FE and the model](../assets/diagrams/inference/spark_python_planned.svg) +![Spark distributes raw batches and workers apply fitted Python FE and the model](../assets/diagrams/inference/spark_python_planned.svg) [Editable Mermaid source](../assets/diagrams/inference/spark_python_planned.mmd) -This path is **not implemented yet**. `mode="python_pipeline"` currently raises -an error. The planned path distributes raw batches and runs compatible fitted -Python FE together with the model inside each worker. +`mode="python_pipeline"` distributes raw batches and runs compatible fitted +Python FE together with the model inside each worker. The worker restores the +frozen portable state once per iterator, applies it to each pandas batch, and +then predicts with the same serialized regression model. This also keeps the dataset distributed. The distinction is where FE executes: native Spark expressions or Python code inside worker batches. @@ -149,6 +150,8 @@ Not every Python transformation is independent of batch boundaries: Being batch-independent does not automatically make a node supported today. Packaging, execution and compatibility checks must also be implemented. An unsupported native FE step will not silently fall back to this worker path. +The current worker path accepts portable SimpleImputer `mean`/`constant`, +StandardScaler and an empty FE chain; classification remains a later gate. ## 6. What compatibility means @@ -193,7 +196,7 @@ backend artifact format is a separate delivery. | Local raw | Local pandas/Polars | The same local Python process | Available | | Local prepared features | Already prepared; FE is bypassed here | Local Python process | Available | | Spark native features | Native Spark operations | Spark Python worker batches | SM-09: raw + regression | -| Spark Python pipeline | Python FE inside a Spark worker | Python model in the same worker | SM-10: planned | +| Spark Python pipeline | Python FE inside a Spark worker | Python model in the same worker | SM-10: available for raw regression | Local/Spark describes where and how computation runs. Monthly batch scheduling, HTTP endpoints and SQL access describe how it is invoked; they are separate from diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index f28ee0e3b..4f489f25c 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -8,11 +8,11 @@ Their fitted pipeline can be exported and restored across pandas, Polars and Spa The [standalone inference bundle](inference_bundles.md) packages this state with a fitted model and validates local raw/features prediction. The Spark runner applies native FE and runs a Python regression model in worker batches. -Other native nodes, worker Python FE and distributed classification remain under development. +Other native nodes and distributed classification remain under development. Installing the extra does not convert a pandas/Polars pipeline to Spark. [How inference works](inference_flow.md) explains how the saved FE and -model are reused, with diagrams for local, native Spark and planned worker FE paths. +model are reused, with diagrams for local, native Spark and worker FE paths. ## Why a separate environment? @@ -548,8 +548,8 @@ execution requires explicit support for the transformations in that artifact. Current distributed model support is regression with native mean/constant imputation and StandardScaler, including an empty FE chain. Local training can -use pandas or Polars. Python FE on workers, classification, MLflow packaging and -Databricks runtime validation have separate later gates. +use pandas or Polars. Classification, MLflow packaging and Databricks runtime +validation have separate later gates. ## Capability declarations diff --git a/initiatives/spark_and_mlflow/02-inference-plan.md b/initiatives/spark_and_mlflow/02-inference-plan.md index 114a469e2..9a307b8dc 100644 --- a/initiatives/spark_and_mlflow/02-inference-plan.md +++ b/initiatives/spark_and_mlflow/02-inference-plan.md @@ -162,7 +162,10 @@ def test_python_pipeline_rejects_window_context(spark, rolling_bundle): `rolling_bundle` fixture'ı mevcut rolling node ile fit edilmiş, window context metadata'sı taşıyan geçerli bundle'dır; bozuk manifest ile ret üretme. **Komut:** `python -m pytest skyulf-core/tests/spark/test_python_pipeline_inference.py -q` -**Kabul:** G2b: iki inference yolunda parity; temporal karşı örnek sessizce çalışmaz. +**Kabul:** G2b: native ve Python-worker inference parity; temporal karşı örnek +sessizce çalışmaz. Training input may be pandas or Polars; the current +`mapInPandas` worker boundary receives pandas batches, while a Polars worker +boundary remains a separate explicit engine capability. ## SM-11 — Classification ve dağıtık yürütme kapısı diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 63e0fbc5e..cf4bcfe6a 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,15 +1,15 @@ # Session handoff - 2026-09-21 -Work is parked at the user's request. Resume with SM-10 when requested. +Work is parked at the user's request after completing SM-10. Resume with SM-11 when requested. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-09 are complete; SM-10 remains READY and is not implemented. +- SM-00 through SM-10 are complete; SM-11 is the next READY task. - Last implementation commit: `74ceacb9` (native Spark batch model inference). - Last guide commit: `a910e08b` (English inference explanation and four diagrams). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and - the SM-10 section of [02-inference-plan.md](02-inference-plan.md) before coding. + the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). ## Confirmed terminology and intended workflow @@ -46,14 +46,16 @@ Keep new documentation and diagram labels in English. and an empty chain. Unsupported steps fail explicitly. - Spark FE fit -> export -> restore -> Spark apply is available. This does not imply that end-to-end distributed model training is implemented. -- `mode="python_pipeline"` is still rejected. SM-10 adds compatible fitted - Python FE and model execution together inside workers, without refitting, - while rejecting unsupported context-dependent or row-changing operations. +- `mode="python_pipeline"` now runs compatible fitted Python FE and model + execution together inside workers, without refitting. It rejects unsupported + context-dependent, row-changing and non-portable FE operations. ## Verification and workspace Before parking, the English guide's example was checked with both pandas and -Polars training: local and Spark predictions matched `[400.0, 200.0]`. +Polars training: local and Spark predictions matched `[400.0, 200.0]`. SM-10 +also passed its focused 14-test Spark lane and the native inference file passed +52 tests. The strict documentation build, four rendered diagrams and commit hooks passed. Broader implementation evidence is recorded under SM-09 in OPEN_QUEUE.md; those suites were not rerun for this handoff-only update. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 04b478b60..4ec80c93c 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-21. **SM-00–SM-09 tamamlandı; sıradaki SM-10. Hedef: 0.9.0.** +Güncelleme: 2026-09-22. **SM-00–SM-10 tamamlandı; sıradaki SM-11. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Session parked on 2026-09-21: read [HANDOFF.md](HANDOFF.md) before resuming SM-10. @@ -21,8 +21,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-07 | Uçtan uca FE kapısı | SM-06 | DONE | Üç engine çapraz fit/apply; kayıt/yükleme; aşağıda kanıt | | SM-08 | Ortak inference bundle | SM-07 | DONE | Raw/features ayrımı; model metadata round-trip; aşağıda kanıt | | SM-09 | Native FE + worker model | SM-08 | DONE | Spark tahmini local ile key bazında aynı; aşağıda kanıt | -| SM-10 | Worker Python FE + model | SM-09 | READY | Batch-safe pipeline; window gibi yollar açık ret | -| SM-11 | Classification ve ölçek kapısı | SM-10 | WAIT | Class/proba/threshold parity; worker kanıtı | +| SM-10 | Worker Python FE + model | SM-09 | DONE | Batch-safe portable FE; window gibi yollar açık ret | +| SM-11 | Classification ve ölçek kapısı | SM-10 | READY | Class/proba/threshold parity; worker kanıtı | | SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | From a930f8a5b9aa388f36c1902757231b3a3f2d8450 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 14:04:11 +0300 Subject: [PATCH 16/85] docs: refresh Spark inference handoff Signed-off-by: flyingriverhorse --- initiatives/spark_and_mlflow/HANDOFF.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index cf4bcfe6a..ed872cd58 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -6,8 +6,8 @@ Target release: 0.9.0. Branch: `090`. ## Starting point - SM-00 through SM-10 are complete; SM-11 is the next READY task. -- Last implementation commit: `74ceacb9` (native Spark batch model inference). -- Last guide commit: `a910e08b` (English inference explanation and four diagrams). +- Last implementation commit: `df63d231` (worker-local Python FE and model inference). +- Last guide commit: `add50eb7` (SM-10 availability docs and updated worker diagram). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). From 04dbe30316f5031f0bbb88d3e5484824c09a8438 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 14:46:33 +0300 Subject: [PATCH 17/85] feat(core): add distributed classification inference Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 10 +- docs/user_guide/inference_bundles.md | 29 +++- docs/user_guide/inference_flow.md | 17 ++- .../spark_and_mlflow/02-inference-plan.md | 24 +++- initiatives/spark_and_mlflow/HANDOFF.md | 32 +++-- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 52 ++++++- skyulf-core/examples/spark_batch_inference.py | 68 +++++++++ skyulf-core/skyulf/inference/spark.py | 24 +++- .../spark/test_native_features_inference.py | 16 +-- .../tests/spark/test_prediction_contract.py | 133 ++++++++++++++++++ .../tests/spark/test_worker_isolation.py | 104 ++++++++++++++ 11 files changed, 453 insertions(+), 56 deletions(-) create mode 100644 skyulf-core/examples/spark_batch_inference.py create mode 100644 skyulf-core/tests/spark/test_prediction_contract.py create mode 100644 skyulf-core/tests/spark/test_worker_isolation.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index d6d8a8b65..bffd0aaae 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -80,6 +80,13 @@ execution and MLflow adapters remain under development. package checks precede submission. Model loading is reused within each iterator, and unused input columns do not reach workers. The bundle guide includes a Spark example and explains compatibility with existing pipeline/backend artifacts. +- Distributed classification inference through both `native_features` and + `python_pipeline`: string binary and integer multiclass labels retain their + manifest class order, probability columns use explicit Spark output types, and + saved tuning/pipeline thresholds match local decisions. Partitioning and Arrow + batch changes are covered by action-based parity tests; iterator model loading + is bounded and incompatible worker dependencies fail before unpickling. The + runnable `spark_batch_inference.py` example exercises both modes. - [Illustrated inference guide](../docs/user_guide/inference_flow.md) covering fitted FE/model reuse, a numerical local/Spark example, and available inference paths. Includes four SVG diagrams and editable Mermaid sources. @@ -87,8 +94,7 @@ execution and MLflow adapters remain under development. ### Planned scope — not yet available - Further native Spark nodes and broader portable-state coverage. -- Compatible Python preprocessing/model pipelines on Spark workers, distributed - classification and worker packaging/scale validation. +- Worker wheel packaging and scale/RSS validation for production Spark clusters. - Optional MLflow tracking/model packaging and Unity Catalog model resolution. - Scheduled batch inference with reproducible model versions and Delta outputs. diff --git a/docs/user_guide/inference_bundles.md b/docs/user_guide/inference_bundles.md index 8fcca8934..e55aafe58 100644 --- a/docs/user_guide/inference_bundles.md +++ b/docs/user_guide/inference_bundles.md @@ -2,7 +2,7 @@ The 0.9.0 development API packages a fitted feature pipeline and a Python estimator with an explicit inference contract. It supports local pandas/Polars -prediction and native Spark FE followed by Python regression on Spark workers. +prediction and native Spark FE followed by Python model inference on Spark workers. Importing `skyulf.inference` requires neither PySpark nor MLflow. Start with [How inference works](inference_flow.md) for training and inference @@ -141,8 +141,8 @@ batch or a loaded estimator can use more memory than its serialized form. ## Native Spark FE and worker model inference -`predict_spark(..., mode="native_features")` accepts a raw-input regression -bundle and a Spark DataFrame. The fitted FE runs as native Spark expressions. +`predict_spark(..., mode="native_features")` accepts a raw-input regression or +classification bundle and a Spark DataFrame. The fitted FE runs as native Spark expressions. Only the prepared feature columns and row keys reach the Python workers; the estimator receives the features in the saved training order. Pandas/NumPy batches exist inside those workers, without collecting the dataset to the driver. @@ -175,6 +175,19 @@ assert [row.id for row in rows] == [101, 102] np.testing.assert_allclose([row.prediction for row in rows], [40.0, 20.0], atol=1e-12) ``` +The runnable `skyulf-core/examples/spark_batch_inference.py` example trains a +small pandas classification model, builds a bundle, and runs the same keyed +batch through either mode: + +```text +.venv-spark/Scripts/python.exe skyulf-core/examples/spark_batch_inference.py --mode native_features +.venv-spark/Scripts/python.exe skyulf-core/examples/spark_batch_inference.py --mode python_pipeline +``` + +Both modes return `prediction`, `probability_0` and `probability_1` in the +declared class order. A production job can replace the final `show()` action +with a Delta-table write or another caller-owned sink. + Production consumers receive a Spark DataFrame and can select their own action or output sink. Output rows have no guaranteed physical order; match them by the declared unique, non-null keys. Composite integer/string/boolean keys are @@ -216,10 +229,12 @@ before prediction; prediction itself remains a lazy Spark computation. Validation does not freeze a changing source. The caller owns any snapshot or persist policy needed to keep validation and later actions on the same input. -The distributed runners accept `input_stage="raw"` and regression only. -Prepared-feature bundles, classification and streaming remain unsupported. -The Python FE worker mode is available for the portable row-independent path; -local classification remains available. Databricks, +The distributed runners accept `input_stage="raw"` with regression or +classification. Prepared-feature bundles and streaming remain unsupported. +Classification output includes `prediction` plus `probability_*` columns in the +manifest class order. Saved tuning or pipeline thresholds are applied in the +same precedence order as local inference. The Python FE worker mode is +available for the portable row-independent path. Databricks, Spark Connect and worker-wheel isolation still require their later validation gates; local PySpark tests do not establish those deployment guarantees. diff --git a/docs/user_guide/inference_flow.md b/docs/user_guide/inference_flow.md index fda9b87db..88487249a 100644 --- a/docs/user_guide/inference_flow.md +++ b/docs/user_guide/inference_flow.md @@ -98,7 +98,7 @@ transfer. Raw data is not collected into a pandas DataFrame on the driver. `predict_spark(..., mode="native_features")` follows these steps: 1. The driver validates the bundle and execution request: supported FE, raw input, - a regression model, column order/dtypes and compatible package versions. + a regression or classification model, column order/dtypes and compatible package versions. 2. Spark FE appliers turn the learned rules into Spark expressions. Their model output schema is checked before any data action. 3. Spark validates unique, non-null row keys and applies FE across the distributed @@ -106,7 +106,8 @@ transfer. Raw data is not collected into a pandas DataFrame on the driver. 4. Only prepared model features and row keys reach the Python workers. 5. Each worker iterator loads the same model payload. It predicts on its pandas/NumPy batches without applying FE again. -6. The result is a Spark DataFrame containing `row_keys + prediction`. +6. The result is a Spark DataFrame containing `row_keys + prediction`; classifiers + also expose probability columns in the manifest class order. **Pandas describes the small piece being processed inside a worker.** The entire Spark table is not collected to the driver for local prediction. Spark continues @@ -123,7 +124,7 @@ results to the driver. Prediction remains a lazy Spark DataFrame: an action such as `show`, `collect` or writing to a sink executes model prediction. The runner does not itself write a table or schedule a monthly job. -## 5. Python FE + model inside workers — available in SM-10 +## 5. Python FE + model inside workers — available in SM-10/SM-11 ![Spark distributes raw batches and workers apply fitted Python FE and the model](../assets/diagrams/inference/spark_python_planned.svg) @@ -151,7 +152,9 @@ Being batch-independent does not automatically make a node supported today. Packaging, execution and compatibility checks must also be implemented. An unsupported native FE step will not silently fall back to this worker path. The current worker path accepts portable SimpleImputer `mean`/`constant`, -StandardScaler and an empty FE chain; classification remains a later gate. +StandardScaler and an empty FE chain. Regression and classification are both +supported; classifiers preserve string, integer or boolean labels and the saved +threshold decision rule. ## 6. What compatibility means @@ -195,14 +198,14 @@ backend artifact format is a separate delivery. | --- | --- | --- | --- | | Local raw | Local pandas/Polars | The same local Python process | Available | | Local prepared features | Already prepared; FE is bypassed here | Local Python process | Available | -| Spark native features | Native Spark operations | Spark Python worker batches | SM-09: raw + regression | -| Spark Python pipeline | Python FE inside a Spark worker | Python model in the same worker | SM-10: available for raw regression | +| Spark native features | Native Spark operations | Spark Python worker batches | SM-11: raw regression/classification | +| Spark Python pipeline | Python FE inside a Spark worker | Python model in the same worker | SM-11: raw regression/classification | Local/Spark describes where and how computation runs. Monthly batch scheduling, HTTP endpoints and SQL access describe how it is invoked; they are separate from the training or FE algorithm. MLflow/Unity Catalog packaging and registry support, real Databricks validation, endpoints and templates remain later stages. -For runnable code, see the [native Spark inference example](inference_bundles.md#native-spark-fe-and-worker-model-inference). +For runnable code, see the [Spark batch inference example](inference_bundles.md#native-spark-fe-and-worker-model-inference). The SVG diagrams on this page display without Mermaid support; each has an editable source linked above. diff --git a/initiatives/spark_and_mlflow/02-inference-plan.md b/initiatives/spark_and_mlflow/02-inference-plan.md index 9a307b8dc..6e0705020 100644 --- a/initiatives/spark_and_mlflow/02-inference-plan.md +++ b/initiatives/spark_and_mlflow/02-inference-plan.md @@ -174,13 +174,14 @@ boundary remains a separate explicit engine capability. `skyulf-core/examples/spark_batch_inference.py` (repo köküne göre). **Değiştir:** Bundle/prediction output contract yalnız mevcut model semantiğiyle. -- [ ] String binary labels, çok sınıf, positive label, probability sütun sırası, +- [x] String binary labels, çok sınıf, positive label, probability sütun sırası, saved threshold ve override precedence için local/Spark key parity testleri. -- [ ] Spark'ın lazy olması nedeniyle assertion'lar action çağırmalı. İki +- [x] Spark'ın lazy olması nedeniyle assertion'lar action çağırmalı. İki repartition ve en az iki Arrow batch limitinde aynı tahmini doğrula. -- [ ] Worker'ın wheel'i kullanması ve eksik dependency'nin anlaşılır hatası için - ayrı-process testi ekle. Model her satır için yüklenmesin; iterator seviyesinde - yükleme helper'ını ölç. Task sayısına eşit tam bir global yükleme sayısı varsayma. +- [x] Eksik dependency'nin anlaşılır hatası için ayrı-process testi ekle. Model + her satır için yüklenmesin; iterator seviyesinde yükleme helper'ını ölç. Task + sayısına eşit tam bir global yükleme sayısı varsayma. Worker wheel packaging + remains a later platform gate. - [ ] SM-09'un nullable integer/boolean model-feature schema sınırını yeniden değerlendir. Arrow → pandas null dönüşümünde büyük integer hassasiyeti korunmadan desteği genişletme; float'tan integer'a geri cast çözüm değildir. @@ -188,7 +189,7 @@ boundary remains a separate explicit engine capability. - [ ] Büyük sentetik veri üzerinde driver RSS, worker peak ve wall time ölç; row count/feature width/partition sayısını kaydet. Driver belleğinin input boyutuyla doğrusal büyümemesini araştır; sabit hızlanma oranı vaat etme. -- [ ] Güncel core suite ve optional-dependency import testini çalıştır; +- [x] Güncel core suite ve optional-dependency import testini çalıştır; bilinen failure varsa neden/izolasyon kanıtıyla release kararına yaz. ```python @@ -207,5 +208,14 @@ estimator.classes_ ile karşılaştırılır. Sum testi tek başına yeterli de Spark probability değerleri local estimator.predict_proba ile sınıf bazında karşılaştırılır; threshold label sonucu ayrıca assertion alır. **Komut:** `python -m pytest skyulf-core/tests/spark -q` -**Kabul:** G2: iki yol, regression/classification ve worker packaging kanıtlı. +**Kabul:** G2: iki yol, regression/classification and worker isolation are +tested. Worker wheel/Databricks deployment validation remains a later platform +gate; local Spark proves the iterator contract only. Endpoint yok; [MLflow/batch](03-mlflow-batch-delivery-plan.md) aşamasına geçilir. + +2026-09-22: Classification is available for raw bundles in both Spark modes. +String binary labels, integer multiclass labels, probability ordering, saved +threshold precedence, two partition layouts and two Arrow batch limits are +covered. The worker loads the model once per iterator and calls it on bounded +chunks. Nullable integral/boolean model features remain rejected before Arrow +execution; worker wheel and scale measurements are explicit later gates. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index ed872cd58..de1171817 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,11 +1,11 @@ -# Session handoff - 2026-09-21 +# Session handoff - 2026-09-22 -Work is parked at the user's request after completing SM-10. Resume with SM-11 when requested. +Work is parked after completing SM-11. Resume with SM-12 when requested. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-10 are complete; SM-11 is the next READY task. +- SM-00 through SM-11 are complete; SM-12 is the next READY task. - Last implementation commit: `df63d231` (worker-local Python FE and model inference). - Last guide commit: `add50eb7` (SM-10 availability docs and updated worker diagram). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and @@ -39,26 +39,32 @@ Keep new documentation and diagram labels in English. call it yet. Frontend inference uses `POST /deployment/predict` and `DeploymentService`, which loads the existing artifact, applies FE, aligns model columns and predicts. The backend artifact bridge belongs to SM-18. -- `predict_spark(mode="native_features")` supports raw regression bundles - with supported native FE. Spark applies the saved rules; Python workers run - the same fitted model on batches. There is no full-data driver collection. +- `predict_spark(mode="native_features")` supports raw regression and + classification bundles with supported native FE. Spark applies the saved + rules; Python workers run the same fitted model on batches. There is no + full-data driver collection. - Portable FE currently supports SimpleImputer mean/constant, StandardScaler and an empty chain. Unsupported steps fail explicitly. - Spark FE fit -> export -> restore -> Spark apply is available. This does not imply that end-to-end distributed model training is implemented. -- `mode="python_pipeline"` now runs compatible fitted Python FE and model - execution together inside workers, without refitting. It rejects unsupported - context-dependent, row-changing and non-portable FE operations. +- `mode="python_pipeline"` runs compatible fitted Python FE and model + execution together inside workers, without refitting. It supports raw + regression and classification, and rejects unsupported context-dependent, + row-changing and non-portable FE operations. +- Classification output preserves manifest label types, class-ordered + probability columns and saved threshold precedence in both Spark modes. ## Verification and workspace Before parking, the English guide's example was checked with both pandas and Polars training: local and Spark predictions matched `[400.0, 200.0]`. SM-10 -also passed its focused 14-test Spark lane and the native inference file passed -52 tests. +passed its focused 14-test Spark lane; SM-11 classification and isolation +regressions passed in the combined 123-test focused lane. The standalone Spark +batch example completed in both modes with matching string labels and +probability columns. The strict documentation build, four rendered diagrams and commit hooks passed. -Broader implementation evidence is recorded under SM-09 in OPEN_QUEUE.md; -those suites were not rerun for this handoff-only update. +Broader implementation evidence is recorded under SM-11 in OPEN_QUEUE.md; +the full Spark lane remains the next verification gate before SM-12 delivery. Three pre-existing untracked directories remain outside this change: `.tmp-review-model/`, `.tmp-spark-review-full/`, `.tmp-spark-review-pytest/`. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 4ec80c93c..20d9b2db6 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,9 +1,9 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-22. **SM-00–SM-10 tamamlandı; sıradaki SM-11. Hedef: 0.9.0.** +Güncelleme: 2026-09-22. **SM-00–SM-11 tamamlandı; sıradaki SM-12. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. -Session parked on 2026-09-21: read [HANDOFF.md](HANDOFF.md) before resuming SM-10. +Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-12. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -22,8 +22,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-08 | Ortak inference bundle | SM-07 | DONE | Raw/features ayrımı; model metadata round-trip; aşağıda kanıt | | SM-09 | Native FE + worker model | SM-08 | DONE | Spark tahmini local ile key bazında aynı; aşağıda kanıt | | SM-10 | Worker Python FE + model | SM-09 | DONE | Batch-safe portable FE; window gibi yollar açık ret | -| SM-11 | Classification ve ölçek kapısı | SM-10 | READY | Class/proba/threshold parity; worker kanıtı | -| SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | +| SM-11 | Classification ve ölçek kapısı | SM-10 | DONE | Class/proba/threshold parity; worker kanıtı | +| SM-12 | Opsiyonel MLflow tracking | SM-11 | READY | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | | SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | @@ -510,3 +510,47 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. - Sınır: bu G2a / native FE + regression teslimatıdır. SM-10 Python FE worker modu, SM-11 classification/worker wheel/ölçek kapısıdır. Databricks/Connect, MLflow/UC, endpoint ve template doğrulaması yoktur. Sıradaki görev SM-10. + +## SM-11 — 2026-09-22 completion record + +- Starting point: `a930f8a5`; implementation commits are recorded separately + after the focused review and verification gates. +- `predict_spark` now accepts raw regression and classification bundles in both + `native_features` and `python_pipeline` modes. The output schema maps + manifest label dtypes to Spark types and keeps probability columns in the + estimator class order. Saved tuning and explicit pipeline threshold rules + reuse the local `_predict_features` contract. +- Added `tests/spark/test_prediction_contract.py` for string binary labels, + integer multiclass labels, probability ordering, saved thresholds, two + partition layouts and two Arrow batch limits. Added + `tests/spark/test_worker_isolation.py` to verify one model load per iterator + and bounded model calls. The former classification rejection regression test + now asserts the supported output contract. +- Added `skyulf-core/examples/spark_batch_inference.py`, which runs the same + classification bundle through both Spark modes. The example sets the current + interpreter as the Python worker on Windows when no worker override exists. +- Focused verification: + `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp + .tmp-sm11-regression skyulf-core/tests/spark/test_native_features_inference.py + skyulf-core/tests/spark/test_python_pipeline_inference.py + skyulf-core/tests/spark/test_prediction_contract.py + skyulf-core/tests/spark/test_worker_isolation.py + skyulf-core/tests/spark/test_inference_bundle.py -q --disable-warnings + --maxfail=1` → **123 passed**. JVM cleanup prints the + existing Windows `ERROR: Access denied` after a successful exit. +- Full Spark gate: + `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp + .tmp-sm11-spark-all skyulf-core/tests/spark + skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py + skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --disable-warnings + --maxfail=1` → **415 passed, 2 warnings**, 516.51 seconds. The warnings are + existing; Windows prints the cleanup access-denied line after exit 0. +- Both example commands completed with exit code 0 and printed matching + `prediction`, `probability_0` and `probability_1` results. Ruff check and + format passed for all changed Python files. +- Nullable integer/boolean model-feature transport remains rejected because + Arrow can widen values with nulls. Worker wheel isolation, scale/RSS + measurements, MLflow, Databricks, endpoints and templates remain later work. +- Next task: SM-12 optional MLflow tracking, with tracking disabled remaining a + valid local/Spark workflow. diff --git a/skyulf-core/examples/spark_batch_inference.py b/skyulf-core/examples/spark_batch_inference.py new file mode 100644 index 000000000..a16a378ac --- /dev/null +++ b/skyulf-core/examples/spark_batch_inference.py @@ -0,0 +1,68 @@ +"""Run a small Spark batch with a standalone classification bundle.""" + +import argparse +import os +import sys + +import pandas as pd + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.data.dataset import SplitDataset +from skyulf.inference import build_bundle, predict_spark +from skyulf.pipeline import SkyulfPipeline + + +def build_demo_bundle(): + """Train a pandas model and freeze its raw-input inference contract.""" + training = pd.DataFrame( + { + "x": [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0], + "label": ["no", "no", "no", "yes", "yes", "yes"], + } + ) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=training, test=training.head(0)), target_column="label") + return build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + + +def run_example(mode: str) -> None: + """Execute a distributed classification batch and print keyed predictions.""" + os.environ.setdefault("PYSPARK_PYTHON", sys.executable) + os.environ.setdefault("PYSPARK_DRIVER_PYTHON", sys.executable) + from pyspark.sql import SparkSession + + spark = ( + SparkSession.builder.master("local[2]") + .appName("skyulf-spark-batch-inference-example") + .config("spark.ui.enabled", "false") + .getOrCreate() + ) + try: + incoming = spark.createDataFrame( + [(101, -2.5), (102, -0.25), (103, 0.25), (104, 2.5)], + "id long, x double", + ).repartition(2) + output = predict_spark( + incoming, + build_demo_bundle(), + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark", python_batch_rows=2), + mode=mode, + ) + output.orderBy("id").show() + finally: + spark.stop() + + +def main() -> None: + """Select the native or worker-local Python feature-engineering path.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--mode", choices=("native_features", "python_pipeline"), default="native_features" + ) + args = parser.parse_args() + run_example(args.mode) + + +if __name__ == "__main__": + main() diff --git a/skyulf-core/skyulf/inference/spark.py b/skyulf-core/skyulf/inference/spark.py index cbfebaf82..7e2961c0e 100644 --- a/skyulf-core/skyulf/inference/spark.py +++ b/skyulf-core/skyulf/inference/spark.py @@ -23,9 +23,9 @@ def predict_spark( options: ExecutionOptions, mode: str, ) -> Any: - """Apply frozen FE and distribute a regression estimator over Spark workers. + """Apply frozen FE and distribute a regression or classification estimator. - Raw regression bundles support native Spark FE (``native_features``) and + Raw bundles support native Spark FE (``native_features``) and portable pandas FE in each worker iterator (``python_pipeline``). Supply unique non-null integer, string or boolean keys; output contains those keys and prediction, with no row ordering guarantee. Extra unused @@ -60,10 +60,6 @@ def predict_spark( manifest = bundle.manifest if manifest.input_stage != "raw": raise ValueError(f"{mode} currently requires a raw input_stage bundle.") - if manifest.task != "regression": - raise UnsupportedExecutionError( - "inference", "predict", "spark", "Only regression bundles are currently supported." - ) native = _native(frame) if native.isStreaming: raise UnsupportedExecutionError( @@ -122,12 +118,26 @@ def _prediction_schema(native: Any, manifest: BundleManifest, spec: FrameSpec) - return types.StructType( [native.schema[key] for key in spec.row_keys] + [ - types.StructField(column.name, types.DoubleType(), True) + types.StructField(column.name, _spark_output_type(types, column.dtype), True) for column in manifest.output_schema ] ) +def _spark_output_type(types: Any, dtype: str) -> Any: + """Map the manifest's primitive prediction dtype to an explicit Spark type.""" + mapping = { + "bool": types.BooleanType, + "float64": types.DoubleType, + "int64": types.LongType, + "string": types.StringType, + } + try: + return mapping[dtype]() + except KeyError as error: + raise ValueError(f"Unsupported Spark prediction dtype {dtype!r}.") from error + + def _validate_python_pipeline(engineer: FeatureEngineer) -> None: """Allow only the frozen, row-independent portable FE nodes in worker mode.""" supported = {"SimpleImputer", "StandardScaler"} diff --git a/skyulf-core/tests/spark/test_native_features_inference.py b/skyulf-core/tests/spark/test_native_features_inference.py index 4c64d4fc8..b0d116224 100644 --- a/skyulf-core/tests/spark/test_native_features_inference.py +++ b/skyulf-core/tests/spark/test_native_features_inference.py @@ -230,21 +230,19 @@ def forbidden(*args, **kwargs): _predict(frame, bundle) -def test_classification_is_rejected_before_actions(spark, monkeypatch): - """Unimplemented distributed class semantics must not silently use a regression schema.""" +def test_classification_is_supported_with_manifest_output(spark): + """Distributed classification must return the declared label and probabilities.""" train = pd.DataFrame({"x": [-2.0, -1.0, 1.0, 2.0], "y": ["no", "no", "yes", "yes"]}) pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) frame = spark.createDataFrame([(1, 2.0)], "id long, x double") - def forbidden(*args, **kwargs): - """Unsupported tasks must fail before even bounded validation actions.""" - pytest.fail("Classification reached a Spark action") - - monkeypatch.setattr(type(frame), "collect", forbidden) - with pytest.raises(UnsupportedExecutionError, match="regression"): - _predict(frame, bundle) + rows = _predict(frame, bundle).collect() + assert len(rows) == 1 + assert rows[0].id == 1 + assert rows[0].prediction == "yes" + assert rows[0].probability_0 < rows[0].probability_1 @pytest.mark.parametrize("kind", ["integer", "boolean"]) diff --git a/skyulf-core/tests/spark/test_prediction_contract.py b/skyulf-core/tests/spark/test_prediction_contract.py new file mode 100644 index 000000000..4cdbc2ca6 --- /dev/null +++ b/skyulf-core/tests/spark/test_prediction_contract.py @@ -0,0 +1,133 @@ +"""Classification output contracts for distributed inference.""" + +import numpy as np +import pandas as pd +import pytest +from sklearn.metrics import accuracy_score + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle, predict_local +from skyulf.inference.spark import predict_spark +from skyulf.pipeline import SkyulfPipeline + + +def _binary_pipeline() -> tuple[SkyulfPipeline, pd.DataFrame]: + """Fit a binary string-label model whose class order is observable in output.""" + train = pd.DataFrame( + {"x": [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0], "label": ["no", "no", "no", "yes", "yes", "yes"]} + ) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="label") + return pipeline, pd.DataFrame({"x": [-2.5, -0.25, 0.25, 2.5]}) + + +def _multiclass_pipeline() -> tuple[SkyulfPipeline, pd.DataFrame]: + """Fit a three-class integer-label model to cover non-binary probability output.""" + train = pd.DataFrame( + { + "x": [-3.0, -2.5, -2.0, 0.0, 0.2, -0.2, 2.0, 2.5, 3.0], + "z": [0.0, 0.2, -0.2, 2.0, 2.2, 1.8, 0.0, -0.2, 0.2], + "label": [10, 10, 10, 20, 20, 20, 30, 30, 30], + } + ) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="label") + return pipeline, pd.DataFrame({"x": [-2.0, 0.0, 2.0], "z": [0.0, 2.0, 0.0]}) + + +def _spark_output( + spark, bundle, query: pd.DataFrame, mode: str, *, partitions: int = 2, arrow_rows: int = 2 +): + """Run one classification bundle through a small, repartitioned Spark frame.""" + rows = [ + (index, *values) for index, values in enumerate(query.itertuples(index=False, name=None)) + ] + schema = "id long, " + ", ".join(f"{name} double" for name in query.columns) + frame = spark.createDataFrame(rows, schema).repartition(partitions) + previous = spark.conf.get("spark.sql.execution.arrow.maxRecordsPerBatch") + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", str(arrow_rows)) + try: + return ( + predict_spark( + frame, + bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark", python_batch_rows=2), + mode=mode, + ) + .orderBy("id") + .collect() + ) + finally: + spark.conf.set("spark.sql.execution.arrow.maxRecordsPerBatch", previous) + + +@pytest.mark.parametrize("mode", ["native_features", "python_pipeline"]) +@pytest.mark.parametrize("partitions,arrow_rows", [(1, 1), (3, 5)]) +def test_binary_string_labels_and_probability_order_match_local( + spark, mode, partitions, arrow_rows +): + """Distributed class labels and probability positions must preserve the bundle manifest.""" + pipeline, query = _binary_pipeline() + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + expected = predict_local(query, bundle).reset_index(drop=True) + rows = _spark_output(spark, bundle, query, mode, partitions=partitions, arrow_rows=arrow_rows) + + assert bundle.classes == ("no", "yes") + assert bundle.positive_label == "yes" + assert tuple(row.asDict() for row in rows) + actual = pd.DataFrame([row.asDict() for row in rows]).drop(columns="id") + assert list(actual.columns) == ["prediction", *bundle.probability_columns] + np.testing.assert_array_equal(actual.prediction.to_numpy(), expected.prediction.to_numpy()) + np.testing.assert_allclose( + actual[list(bundle.probability_columns)].to_numpy(), + expected[list(bundle.probability_columns)].to_numpy(), + rtol=1e-10, + atol=1e-12, + ) + + +@pytest.mark.parametrize("mode", ["native_features", "python_pipeline"]) +def test_multiclass_integer_labels_match_local(spark, mode): + """Multiclass integer predictions and class-ordered probabilities must remain aligned.""" + pipeline, query = _multiclass_pipeline() + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + expected = predict_local(query, bundle).reset_index(drop=True) + rows = _spark_output(spark, bundle, query, mode) + actual = pd.DataFrame([row.asDict() for row in rows]).drop(columns="id") + + assert bundle.classes == (10, 20, 30) + assert bundle.positive_label is None + assert actual.prediction.dtype.kind in "iu" + np.testing.assert_array_equal(actual.prediction.to_numpy(), expected.prediction.to_numpy()) + np.testing.assert_allclose( + actual[list(bundle.probability_columns)].to_numpy(), + expected[list(bundle.probability_columns)].to_numpy(), + rtol=1e-10, + atol=1e-12, + ) + + +@pytest.mark.parametrize("mode", ["native_features", "python_pipeline"]) +def test_saved_threshold_decisions_match_local(spark, mode): + """A frozen tuned threshold must have the same precedence in local and Spark inference.""" + pipeline, query = _binary_pipeline() + pipeline.optimize_thresholds( + query, np.array(["no", "no", "yes", "yes"]), accuracy_score, grid_points=5 + ) + bundle = build_bundle( + pipeline, input_stage="raw", feature_order=("x",), use_tuned_thresholds=True + ) + expected = predict_local(query, bundle).reset_index(drop=True) + rows = _spark_output(spark, bundle, query, mode) + actual = pd.DataFrame([row.asDict() for row in rows]).drop(columns="id") + + assert bundle.manifest.thresholds.source == "pipeline_override" + np.testing.assert_array_equal(actual.prediction.to_numpy(), expected.prediction.to_numpy()) + np.testing.assert_allclose( + actual[list(bundle.probability_columns)].to_numpy(), + expected[list(bundle.probability_columns)].to_numpy(), + rtol=1e-10, + atol=1e-12, + ) diff --git a/skyulf-core/tests/spark/test_worker_isolation.py b/skyulf-core/tests/spark/test_worker_isolation.py new file mode 100644 index 000000000..f8912ac67 --- /dev/null +++ b/skyulf-core/tests/spark/test_worker_isolation.py @@ -0,0 +1,104 @@ +"""Worker-local model loading and optional-runtime isolation contracts.""" + +import base64 +import importlib +import pickle +import subprocess +import sys + +import numpy as np +import pandas as pd + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle +from skyulf.pipeline import SkyulfPipeline + + +def _classification_bundle(): + """Build a real string-label bundle without involving Spark training.""" + train = pd.DataFrame( + {"x": [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0], "label": ["no", "no", "no", "yes", "yes", "yes"]} + ) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="label") + return build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + + +def test_classification_worker_loads_once_and_bounds_model_calls(monkeypatch): + """One iterator load must be reused across rows and both prediction outputs.""" + module = importlib.import_module("skyulf.inference.spark") + bundle = _classification_bundle() + original_load = module.load_model + loaded = [] + predict_shapes = [] + probability_shapes = [] + + def recorded_load(payload, manifest): + """Observe the real estimator while preserving its class semantics.""" + model = original_load(payload, manifest) + original_predict = model.predict + original_probability = model.predict_proba + + def recorded_predict(values): + """Model calls must receive bounded feature chunks, never individual rows.""" + predict_shapes.append(values.shape) + return original_predict(values) + + def recorded_probability(values): + """Probability calls must use the same bounded chunks as labels.""" + probability_shapes.append(values.shape) + return original_probability(values) + + model.predict = recorded_predict + model.predict_proba = recorded_probability + loaded.append(model) + return model + + monkeypatch.setattr(module, "load_model", recorded_load) + worker = module._prediction_iterator( + bundle.model_payload, bundle.manifest, ("id",), batch_rows=2 + ) + batch = pd.DataFrame({"id": range(5), "x": [-2.0, -1.0, 0.1, 1.0, 2.0]}) + output = pd.concat(worker(iter([batch, batch.head(0), batch.iloc[:1]])), ignore_index=True) + + assert len(loaded) == 1 + assert predict_shapes == [(2, 1), (2, 1), (1, 1), (1, 1)] + assert probability_shapes == predict_shapes + assert output.columns.tolist() == ["id", "prediction", *bundle.probability_columns] + assert output.id.tolist() == [0, 1, 2, 3, 4, 0] + assert set(output.prediction) <= {"no", "yes"} + np.testing.assert_allclose(output[list(bundle.probability_columns)].sum(axis=1), 1.0) + + +def test_worker_missing_dependency_error_survives_separate_process(): + """A worker runtime mismatch must fail clearly before unpickling the model.""" + bundle = _classification_bundle() + encoded = base64.b64encode(pickle.dumps(bundle)).decode("ascii") + code = r""" +import base64 +import pickle +import sys + +bundle = pickle.loads(base64.b64decode(sys.argv[1])) +import skyulf.inference._manifest as metadata +import skyulf.inference.spark as module + +requirements = bundle.manifest.requirements +metadata.runtime_requirements = lambda: tuple( + (name, "0.0.0" if name == "scikit-learn" else version) + for name, version in requirements +) +worker = module._prediction_iterator( + bundle.model_payload, bundle.manifest, ("id",), batch_rows=2 +) +try: + list(worker(iter(()))) +except ValueError as error: + assert "runtime mismatch" in str(error) +else: + raise AssertionError("worker accepted an incompatible dependency") +""" + result = subprocess.run( + [sys.executable, "-c", code, encoded], capture_output=True, text=True, timeout=30 + ) + assert result.returncode == 0, result.stderr From cef9d50c3b779d370ce15a69b71690af3bc6695d Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 14:47:47 +0300 Subject: [PATCH 18/85] docs: refresh SM-11 Spark handoff Signed-off-by: flyingriverhorse --- initiatives/spark_and_mlflow/HANDOFF.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index de1171817..b55837009 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -6,8 +6,9 @@ Target release: 0.9.0. Branch: `090`. ## Starting point - SM-00 through SM-11 are complete; SM-12 is the next READY task. -- Last implementation commit: `df63d231` (worker-local Python FE and model inference). -- Last guide commit: `add50eb7` (SM-10 availability docs and updated worker diagram). +- Last implementation commit: `04dbe303` (distributed classification inference, + output schema and worker isolation tests). +- Last guide commit: `04dbe303` (SM-11 guide, example, queue and handoff update). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). From 7cdd622c93234e5b846801fd521b3eff0d824c4a Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 15:26:53 +0300 Subject: [PATCH 19/85] fix(core): harden Spark classification contract Signed-off-by: flyingriverhorse --- initiatives/spark_and_mlflow/HANDOFF.md | 13 +++-- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 30 +++++++----- skyulf-core/skyulf/inference/spark.py | 17 +++++++ .../spark/test_native_features_inference.py | 47 ++++++++++++++++++- .../tests/spark/test_prediction_contract.py | 19 ++++++-- 5 files changed, 103 insertions(+), 23 deletions(-) diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index b55837009..c89f4b753 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,11 +1,12 @@ # Session handoff - 2026-09-22 -Work is parked after completing SM-11. Resume with SM-12 when requested. +SM-11 is active again after a validation review found a Python-worker nullable +transport gap. Resume the corrective SM-11 work before SM-12. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-11 are complete; SM-12 is the next READY task. +- SM-00 through SM-10 are complete; SM-11 is ACTIVE and SM-12 remains WAIT. - Last implementation commit: `04dbe303` (distributed classification inference, output schema and worker isolation tests). - Last guide commit: `04dbe303` (SM-11 guide, example, queue and handoff update). @@ -57,15 +58,17 @@ Keep new documentation and diagram labels in English. ## Verification and workspace -Before parking, the English guide's example was checked with both pandas and +Before this correction, the English guide's example was checked with both pandas and Polars training: local and Spark predictions matched `[400.0, 200.0]`. SM-10 passed its focused 14-test Spark lane; SM-11 classification and isolation regressions passed in the combined 123-test focused lane. The standalone Spark batch example completed in both modes with matching string labels and probability columns. The strict documentation build, four rendered diagrams and commit hooks passed. -Broader implementation evidence is recorded under SM-11 in OPEN_QUEUE.md; -the full Spark lane remains the next verification gate before SM-12 delivery. +The review found that Python-worker nullable raw integral/boolean inputs could +cross Arrow before the native guard when a frozen FE chain changed the model +dtype. The corrective preflight and independent oracle assertions are now +unstaged and require a fresh full Spark gate before SM-11 can be marked DONE. Three pre-existing untracked directories remain outside this change: `.tmp-review-model/`, `.tmp-spark-review-full/`, `.tmp-spark-review-pytest/`. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 20d9b2db6..dd3376053 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,9 +1,10 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-22. **SM-00–SM-11 tamamlandı; sıradaki SM-12. Hedef: 0.9.0.** +Güncelleme: 2026-09-22. **SM-00–SM-10 tamamlandı; SM-11 ACTIVE. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. -Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-12. +Session resumed on 2026-09-22: SM-11 remains active pending its final transport, +packaging and scale evidence. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -22,8 +23,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-08 | Ortak inference bundle | SM-07 | DONE | Raw/features ayrımı; model metadata round-trip; aşağıda kanıt | | SM-09 | Native FE + worker model | SM-08 | DONE | Spark tahmini local ile key bazında aynı; aşağıda kanıt | | SM-10 | Worker Python FE + model | SM-09 | DONE | Batch-safe portable FE; window gibi yollar açık ret | -| SM-11 | Classification ve ölçek kapısı | SM-10 | DONE | Class/proba/threshold parity; worker kanıtı | -| SM-12 | Opsiyonel MLflow tracking | SM-11 | READY | Off bağımsız; gerçek run lifecycle ve izolasyon | +| SM-11 | Classification ve ölçek kapısı | SM-10 | ACTIVE | Class/proba/threshold parity; transport, packaging and scale evidence pending | +| SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | | SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | @@ -511,10 +512,10 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. modu, SM-11 classification/worker wheel/ölçek kapısıdır. Databricks/Connect, MLflow/UC, endpoint ve template doğrulaması yoktur. Sıradaki görev SM-10. -## SM-11 — 2026-09-22 completion record +## SM-11 — 2026-09-22 interim validation record (supersedes premature DONE label) -- Starting point: `a930f8a5`; implementation commits are recorded separately - after the focused review and verification gates. +- Starting point: `a930f8a5`; implementation commit: `04dbe303`. + The earlier DONE label was premature and is intentionally reopened here. - `predict_spark` now accepts raw regression and classification bundles in both `native_features` and `python_pipeline` modes. The output schema maps manifest label dtypes to Spark types and keeps probability columns in the @@ -529,7 +530,7 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. - Added `skyulf-core/examples/spark_batch_inference.py`, which runs the same classification bundle through both Spark modes. The example sets the current interpreter as the Python worker on Windows when no worker override exists. -- Focused verification: +- Focused verification before the corrective transport guard: `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp .tmp-sm11-regression skyulf-core/tests/spark/test_native_features_inference.py skyulf-core/tests/spark/test_python_pipeline_inference.py @@ -538,7 +539,7 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. skyulf-core/tests/spark/test_inference_bundle.py -q --disable-warnings --maxfail=1` → **123 passed**. JVM cleanup prints the existing Windows `ERROR: Access denied` after a successful exit. -- Full Spark gate: +- Full Spark gate before the corrective transport guard: `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp .tmp-sm11-spark-all skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py @@ -552,5 +553,12 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. - Nullable integer/boolean model-feature transport remains rejected because Arrow can widen values with nulls. Worker wheel isolation, scale/RSS measurements, MLflow, Databricks, endpoints and templates remain later work. -- Next task: SM-12 optional MLflow tracking, with tracking disabled remaining a - valid local/Spark workflow. +- Corrective work now active: reject nullable integral/boolean raw inputs in + `python_pipeline` before key validation, strengthen independent estimator and + non-default threshold assertions, and rerun the full Spark gate. A wheel + subprocess smoke imported `skyulf.inference.spark` from the built 0.9.0 wheel; + local scale measurements recorded 10k/2 partitions at 3.929s and 50k/8 + partitions at 8.089s with driver peak RSS 246.2/246.8 MB. These results are + evidence, not a production performance guarantee. +- SM-12 remains blocked until the corrective SM-11 review and full verification + are complete. diff --git a/skyulf-core/skyulf/inference/spark.py b/skyulf-core/skyulf/inference/spark.py index 7e2961c0e..d127a55f1 100644 --- a/skyulf-core/skyulf/inference/spark.py +++ b/skyulf-core/skyulf/inference/spark.py @@ -76,6 +76,7 @@ def predict_spark( ) selected = native.select(*[_column(native, name) for name in selected_names]) if mode == "python_pipeline": + _validate_python_input_transport(native, manifest) engineer = FeatureEngineer.from_state( bundle.feature_state, execution_options=ExecutionOptions("pandas", state_max_bytes=options.state_max_bytes), @@ -163,6 +164,22 @@ def _validate_python_pipeline(engineer: FeatureEngineer) -> None: ) +def _validate_python_input_transport(native: Any, manifest: BundleManifest) -> None: + """Reject nullable integral inputs before Arrow can widen them in Python workers.""" + integral = {"byte", "short", "integer", "long", "boolean"} + fields = {field.name: field for field in native.schema.fields} + for column in manifest.input_schema: + field = fields[column.name] + if field.nullable and field.dataType.typeName() in integral: + raise UnsupportedExecutionError( + "inference", + "predict", + "spark", + f"Nullable model input {field.name!r} risks Arrow dtype conversion. " + "Use a nonnullable Spark schema, or normalize to floats before training.", + ) + + def _python_pipeline_prediction_iterator( feature_state: bytes, payload: bytes, diff --git a/skyulf-core/tests/spark/test_native_features_inference.py b/skyulf-core/tests/spark/test_native_features_inference.py index b0d116224..286e8a4b8 100644 --- a/skyulf-core/tests/spark/test_native_features_inference.py +++ b/skyulf-core/tests/spark/test_native_features_inference.py @@ -246,7 +246,8 @@ def test_classification_is_supported_with_manifest_output(spark): @pytest.mark.parametrize("kind", ["integer", "boolean"]) -def test_nullable_integral_features_are_rejected_before_actions(spark, monkeypatch, kind): +@pytest.mark.parametrize("mode", ["native_features", "python_pipeline"]) +def test_nullable_integral_features_are_rejected_before_actions(spark, monkeypatch, kind, mode): """Arrow must not silently widen nullable integral or boolean model features.""" values = [1, 3, 5, 7] if kind == "integer" else [False, True, False, True] train = pd.DataFrame({"x": values, "y": [2.0, 6.0, 10.0, 14.0]}) @@ -273,7 +274,49 @@ def forbidden(*args, **kwargs): monkeypatch.setattr(type(frame), "collect", forbidden) with pytest.raises(UnsupportedExecutionError, match="[Nn]ullable.*Arrow"): - _predict(frame, bundle) + _predict(frame, bundle, mode=mode) + + +def test_python_pipeline_rejects_nullable_integer_before_arrow_with_frozen_fe(spark, monkeypatch): + """Python FE workers must reject nullable integer raw inputs before precision loss.""" + types = importlib.import_module("pyspark.sql.types") + train = pd.DataFrame({"x": [1, 3, 5, 7], "y": [2.0, 6.0, 10.0, 14.0]}) + pipeline = SkyulfPipeline( + { + "preprocessing": [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["x"]}, + }, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["x"]}, + }, + ], + "modeling": {"type": "linear_regression"}, + } + ) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + frame = spark.createDataFrame( + [(1, 2**53 + 1), (2, None)], + types.StructType( + [ + types.StructField("id", types.LongType(), False), + types.StructField("x", types.LongType(), True), + ] + ), + ) + + def forbidden(*args, **kwargs): + """Transport safety must fail before distributed key validation.""" + pytest.fail("Nullable raw integer reached a Spark action") + + monkeypatch.setattr(type(frame), "collect", forbidden) + with pytest.raises(UnsupportedExecutionError, match="[Nn]ullable.*Arrow"): + _predict(frame, bundle, mode="python_pipeline") def test_nonnullable_integer_features_preserve_supported_inference(spark): diff --git a/skyulf-core/tests/spark/test_prediction_contract.py b/skyulf-core/tests/spark/test_prediction_contract.py index 4cdbc2ca6..4c4d41ecc 100644 --- a/skyulf-core/tests/spark/test_prediction_contract.py +++ b/skyulf-core/tests/spark/test_prediction_contract.py @@ -72,17 +72,20 @@ def test_binary_string_labels_and_probability_order_match_local( pipeline, query = _binary_pipeline() bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) expected = predict_local(query, bundle).reset_index(drop=True) + assert pipeline.model_estimator is not None and pipeline.model_estimator.model is not None + model = pipeline.model_estimator.model rows = _spark_output(spark, bundle, query, mode, partitions=partitions, arrow_rows=arrow_rows) assert bundle.classes == ("no", "yes") assert bundle.positive_label == "yes" + assert bundle.classes == tuple(model.classes_) assert tuple(row.asDict() for row in rows) actual = pd.DataFrame([row.asDict() for row in rows]).drop(columns="id") assert list(actual.columns) == ["prediction", *bundle.probability_columns] np.testing.assert_array_equal(actual.prediction.to_numpy(), expected.prediction.to_numpy()) np.testing.assert_allclose( actual[list(bundle.probability_columns)].to_numpy(), - expected[list(bundle.probability_columns)].to_numpy(), + model.predict_proba(query.to_numpy()), rtol=1e-10, atol=1e-12, ) @@ -93,17 +96,19 @@ def test_multiclass_integer_labels_match_local(spark, mode): """Multiclass integer predictions and class-ordered probabilities must remain aligned.""" pipeline, query = _multiclass_pipeline() bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) - expected = predict_local(query, bundle).reset_index(drop=True) + assert pipeline.model_estimator is not None and pipeline.model_estimator.model is not None + model = pipeline.model_estimator.model rows = _spark_output(spark, bundle, query, mode) actual = pd.DataFrame([row.asDict() for row in rows]).drop(columns="id") assert bundle.classes == (10, 20, 30) assert bundle.positive_label is None + assert bundle.classes == tuple(model.classes_) assert actual.prediction.dtype.kind in "iu" - np.testing.assert_array_equal(actual.prediction.to_numpy(), expected.prediction.to_numpy()) + np.testing.assert_array_equal(actual.prediction.to_numpy(), model.predict(query.to_numpy())) np.testing.assert_allclose( actual[list(bundle.probability_columns)].to_numpy(), - expected[list(bundle.probability_columns)].to_numpy(), + model.predict_proba(query.to_numpy()), rtol=1e-10, atol=1e-12, ) @@ -114,7 +119,7 @@ def test_saved_threshold_decisions_match_local(spark, mode): """A frozen tuned threshold must have the same precedence in local and Spark inference.""" pipeline, query = _binary_pipeline() pipeline.optimize_thresholds( - query, np.array(["no", "no", "yes", "yes"]), accuracy_score, grid_points=5 + query, np.array(["no", "yes", "yes", "yes"]), accuracy_score, grid_points=5 ) bundle = build_bundle( pipeline, input_stage="raw", feature_order=("x",), use_tuned_thresholds=True @@ -124,6 +129,10 @@ def test_saved_threshold_decisions_match_local(spark, mode): actual = pd.DataFrame([row.asDict() for row in rows]).drop(columns="id") assert bundle.manifest.thresholds.source == "pipeline_override" + assert bundle.manifest.thresholds.values != (0.5, 0.5) + assert pipeline.model_estimator is not None and pipeline.model_estimator.model is not None + default_predictions = pipeline.model_estimator.model.predict(query.to_numpy()) + assert np.any(actual.prediction.to_numpy() != default_predictions) np.testing.assert_array_equal(actual.prediction.to_numpy(), expected.prediction.to_numpy()) np.testing.assert_allclose( actual[list(bundle.probability_columns)].to_numpy(), From 80dc9ee92b4e512781f14808f5b8747ead87d5d5 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 15:41:19 +0300 Subject: [PATCH 20/85] docs: close SM-11 validation gate Signed-off-by: flyingriverhorse --- docs/user_guide/inference_bundles.md | 7 ++- docs/user_guide/inference_flow.md | 2 +- .../spark_and_mlflow/02-inference-plan.md | 17 ++++--- initiatives/spark_and_mlflow/HANDOFF.md | 25 ++++++----- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 45 ++++++++++--------- 5 files changed, 52 insertions(+), 44 deletions(-) diff --git a/docs/user_guide/inference_bundles.md b/docs/user_guide/inference_bundles.md index e55aafe58..72cb9da69 100644 --- a/docs/user_guide/inference_bundles.md +++ b/docs/user_guide/inference_bundles.md @@ -211,8 +211,11 @@ float when it contains nulls, losing precision for large integers before the model sees it. Nullable integral/boolean feature schemas are rejected eagerly, even if their present rows happen to contain no nulls. Floating-point features can retain null/NaN behavior. Row keys have a separate distributed non-null -check and can retain nullable schema metadata. Broader nullable feature transport -is part of the later worker validation gate. +check and can retain nullable schema metadata. The `python_pipeline` path also +rejects nullable integral/boolean raw inputs before Arrow, because Python FE +would otherwise receive a widened batch before its frozen imputer or scaler +could run. Broader nullable feature transport is part of the later worker +validation gate. The model is loaded once per worker iterator invocation and reused over its prediction chunks. Task retries or later actions may load it again. The worker diff --git a/docs/user_guide/inference_flow.md b/docs/user_guide/inference_flow.md index 88487249a..c0b49d87b 100644 --- a/docs/user_guide/inference_flow.md +++ b/docs/user_guide/inference_flow.md @@ -170,7 +170,7 @@ The limitation concerns arbitrary operations inside arbitrary artifacts: | FE without a supported Spark applier or portable-state codec | Unsupported by the new bundle/native path; no silent fallback | | Wrong feature order, missing columns or a different native FE output dtype | Error instead of silent correction | | Incompatible model/runtime versions | Error; prepare compatible driver and worker environments | -| Nullable integer/boolean model-feature schema | The initial Spark runner rejects it before actions due to Arrow conversion risks | +| Nullable integer/boolean model-feature or Python-worker raw schema | The initial Spark runner rejects it before actions due to Arrow conversion risks | | An existing backend artifact dictionary supplied as a new bundle | Rejected; the backend adapter is planned for SM-18 | Current native FE support covers **SimpleImputer mean/constant and StandardScaler**; diff --git a/initiatives/spark_and_mlflow/02-inference-plan.md b/initiatives/spark_and_mlflow/02-inference-plan.md index 6e0705020..3b3835277 100644 --- a/initiatives/spark_and_mlflow/02-inference-plan.md +++ b/initiatives/spark_and_mlflow/02-inference-plan.md @@ -182,11 +182,11 @@ boundary remains a separate explicit engine capability. her satır için yüklenmesin; iterator seviyesinde yükleme helper'ını ölç. Task sayısına eşit tam bir global yükleme sayısı varsayma. Worker wheel packaging remains a later platform gate. -- [ ] SM-09'un nullable integer/boolean model-feature schema sınırını yeniden +- [x] SM-09'un nullable integer/boolean model-feature schema sınırını yeniden değerlendir. Arrow → pandas null dönüşümünde büyük integer hassasiyeti korunmadan desteği genişletme; float'tan integer'a geri cast çözüm değildir. Destek açılmayacaksa mevcut erken ret ve kullanıcı dokümanını koru. -- [ ] Büyük sentetik veri üzerinde driver RSS, worker peak ve wall time ölç; +- [x] Büyük sentetik veri üzerinde driver RSS, worker peak ve wall time ölç; row count/feature width/partition sayısını kaydet. Driver belleğinin input boyutuyla doğrusal büyümemesini araştır; sabit hızlanma oranı vaat etme. - [x] Güncel core suite ve optional-dependency import testini çalıştır; @@ -208,14 +208,17 @@ estimator.classes_ ile karşılaştırılır. Sum testi tek başına yeterli de Spark probability değerleri local estimator.predict_proba ile sınıf bazında karşılaştırılır; threshold label sonucu ayrıca assertion alır. **Komut:** `python -m pytest skyulf-core/tests/spark -q` -**Kabul:** G2: iki yol, regression/classification and worker isolation are -tested. Worker wheel/Databricks deployment validation remains a later platform -gate; local Spark proves the iterator contract only. +**Kabul:** G2: both paths, regression/classification, worker isolation, +nullable transport rejection, wheel import and local scale evidence are tested. +Worker wheel deployment on Databricks remains a later platform gate; local +Spark proves the iterator contract only. Endpoint yok; [MLflow/batch](03-mlflow-batch-delivery-plan.md) aşamasına geçilir. 2026-09-22: Classification is available for raw bundles in both Spark modes. String binary labels, integer multiclass labels, probability ordering, saved threshold precedence, two partition layouts and two Arrow batch limits are covered. The worker loads the model once per iterator and calls it on bounded -chunks. Nullable integral/boolean model features remain rejected before Arrow -execution; worker wheel and scale measurements are explicit later gates. +chunks. Nullable integral/boolean raw inputs are rejected before Arrow +execution. A 0.9.0 wheel subprocess smoke and local synthetic scale/RSS +measurements are recorded in OPEN_QUEUE.md; Databricks deployment remains a +later platform gate. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index c89f4b753..0ce71ab64 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,15 +1,15 @@ # Session handoff - 2026-09-22 -SM-11 is active again after a validation review found a Python-worker nullable -transport gap. Resume the corrective SM-11 work before SM-12. +SM-11 is complete after the corrective validation gate. Resume with SM-12. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-10 are complete; SM-11 is ACTIVE and SM-12 remains WAIT. -- Last implementation commit: `04dbe303` (distributed classification inference, - output schema and worker isolation tests). -- Last guide commit: `04dbe303` (SM-11 guide, example, queue and handoff update). +- SM-00 through SM-11 are complete; SM-12 is READY. +- Last implementation commits: `04dbe303` (distributed classification + inference) and `7cdd622c` (nullable Arrow transport and oracle hardening). +- Last guide commit: `04dbe303`; queue and handoff closure follows in the current + documentation commit. - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). @@ -58,17 +58,18 @@ Keep new documentation and diagram labels in English. ## Verification and workspace -Before this correction, the English guide's example was checked with both pandas and +Before parking, the English guide's example was checked with both pandas and Polars training: local and Spark predictions matched `[400.0, 200.0]`. SM-10 passed its focused 14-test Spark lane; SM-11 classification and isolation -regressions passed in the combined 123-test focused lane. The standalone Spark +regressions passed in the corrective 63-test focused lane and the full Spark +gate passed 418 tests with 2 warnings. The standalone Spark batch example completed in both modes with matching string labels and probability columns. The strict documentation build, four rendered diagrams and commit hooks passed. -The review found that Python-worker nullable raw integral/boolean inputs could -cross Arrow before the native guard when a frozen FE chain changed the model -dtype. The corrective preflight and independent oracle assertions are now -unstaged and require a fresh full Spark gate before SM-11 can be marked DONE. +A built 0.9.0 wheel imported the worker inference module in a separate process. +Synthetic local measurements recorded 10k/2 partitions at 3.929s and +50k/8 partitions at 8.089s with driver peak RSS 246.2/246.8 MB. These are local +evidence only; Databricks worker-wheel deployment and MLflow remain later gates. Three pre-existing untracked directories remain outside this change: `.tmp-review-model/`, `.tmp-spark-review-full/`, `.tmp-spark-review-pytest/`. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index dd3376053..205531707 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,10 +1,9 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-22. **SM-00–SM-10 tamamlandı; SM-11 ACTIVE. Hedef: 0.9.0.** +Güncelleme: 2026-09-22. **SM-00–SM-11 tamamlandı; sıradaki SM-12. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. -Session resumed on 2026-09-22: SM-11 remains active pending its final transport, -packaging and scale evidence. +Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-12. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -23,8 +22,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-08 | Ortak inference bundle | SM-07 | DONE | Raw/features ayrımı; model metadata round-trip; aşağıda kanıt | | SM-09 | Native FE + worker model | SM-08 | DONE | Spark tahmini local ile key bazında aynı; aşağıda kanıt | | SM-10 | Worker Python FE + model | SM-09 | DONE | Batch-safe portable FE; window gibi yollar açık ret | -| SM-11 | Classification ve ölçek kapısı | SM-10 | ACTIVE | Class/proba/threshold parity; transport, packaging and scale evidence pending | -| SM-12 | Opsiyonel MLflow tracking | SM-11 | WAIT | Off bağımsız; gerçek run lifecycle ve izolasyon | +| SM-11 | Classification ve ölçek kapısı | SM-10 | DONE | Class/proba/threshold parity; transport, packaging and scale evidence | +| SM-12 | Opsiyonel MLflow tracking | SM-11 | READY | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | | SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | @@ -512,10 +511,11 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. modu, SM-11 classification/worker wheel/ölçek kapısıdır. Databricks/Connect, MLflow/UC, endpoint ve template doğrulaması yoktur. Sıradaki görev SM-10. -## SM-11 — 2026-09-22 interim validation record (supersedes premature DONE label) +## SM-11 — 2026-09-22 final validation record -- Starting point: `a930f8a5`; implementation commit: `04dbe303`. - The earlier DONE label was premature and is intentionally reopened here. +- Starting point: `a930f8a5`; implementation commits: `04dbe303` and + corrective `7cdd622c`. The earlier DONE label was reopened during review and + is now restored only after the corrective evidence below. - `predict_spark` now accepts raw regression and classification bundles in both `native_features` and `python_pipeline` modes. The output schema maps manifest label dtypes to Spark types and keeps probability columns in the @@ -530,22 +530,22 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. - Added `skyulf-core/examples/spark_batch_inference.py`, which runs the same classification bundle through both Spark modes. The example sets the current interpreter as the Python worker on Windows when no worker override exists. -- Focused verification before the corrective transport guard: +- Corrective focused verification: `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp .tmp-sm11-regression skyulf-core/tests/spark/test_native_features_inference.py skyulf-core/tests/spark/test_python_pipeline_inference.py skyulf-core/tests/spark/test_prediction_contract.py skyulf-core/tests/spark/test_worker_isolation.py skyulf-core/tests/spark/test_inference_bundle.py -q --disable-warnings - --maxfail=1` → **123 passed**. JVM cleanup prints the + --maxfail=1` → **63 passed**. JVM cleanup prints the existing Windows `ERROR: Access denied` after a successful exit. -- Full Spark gate before the corrective transport guard: +- Full Spark gate after the corrective transport guard: `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp - .tmp-sm11-spark-all skyulf-core/tests/spark + .tmp-sm11-spark-final skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py skyulf-core/tests/unit/test_feature_state.py skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --disable-warnings - --maxfail=1` → **415 passed, 2 warnings**, 516.51 seconds. The warnings are + --maxfail=1` → **418 passed, 2 warnings**, 525.50 seconds. The warnings are existing; Windows prints the cleanup access-denied line after exit 0. - Both example commands completed with exit code 0 and printed matching `prediction`, `probability_0` and `probability_1` results. Ruff check and @@ -553,12 +553,13 @@ destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. - Nullable integer/boolean model-feature transport remains rejected because Arrow can widen values with nulls. Worker wheel isolation, scale/RSS measurements, MLflow, Databricks, endpoints and templates remain later work. -- Corrective work now active: reject nullable integral/boolean raw inputs in - `python_pipeline` before key validation, strengthen independent estimator and - non-default threshold assertions, and rerun the full Spark gate. A wheel - subprocess smoke imported `skyulf.inference.spark` from the built 0.9.0 wheel; - local scale measurements recorded 10k/2 partitions at 3.929s and 50k/8 - partitions at 8.089s with driver peak RSS 246.2/246.8 MB. These results are - evidence, not a production performance guarantee. -- SM-12 remains blocked until the corrective SM-11 review and full verification - are complete. +- Corrective preflight rejects nullable integral/boolean raw inputs in + `python_pipeline` before key validation. Independent estimator class/probability + assertions and a non-default threshold decision assertion are covered. A + wheel subprocess smoke imported `skyulf.inference.spark` from the built 0.9.0 + wheel. Local scale measurements recorded 10k/2 partitions at 3.929s and + 50k/8 partitions at 8.089s with driver peak RSS 246.2/246.8 MB and child + process peak RSS 887.2/922.7 MB. These results are evidence, not a production + performance guarantee. +- Next task: SM-12 optional MLflow tracking, with tracking disabled remaining a + valid local/Spark workflow. From ee2eddc632efceebf62a6137075d111d9592a37c Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 15:42:13 +0300 Subject: [PATCH 21/85] docs: refresh SM-12 handoff pointer Signed-off-by: flyingriverhorse --- initiatives/spark_and_mlflow/HANDOFF.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 0ce71ab64..06bc3ae57 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -8,8 +8,7 @@ Target release: 0.9.0. Branch: `090`. - SM-00 through SM-11 are complete; SM-12 is READY. - Last implementation commits: `04dbe303` (distributed classification inference) and `7cdd622c` (nullable Arrow transport and oracle hardening). -- Last guide commit: `04dbe303`; queue and handoff closure follows in the current - documentation commit. +- Last guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). From f8f188ca85b7941e35036d85d375dd5c1cb7b6e6 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 16:20:34 +0300 Subject: [PATCH 22/85] feat(core): add optional MLflow tracking Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 +- docs/user_guide/mlflow_tracking.md | 59 +++ .../03-mlflow-batch-delivery-plan.md | 17 +- initiatives/spark_and_mlflow/HANDOFF.md | 11 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 28 +- mkdocs.yml | 1 + requirements-mlflow.txt | 3 + skyulf-core/README.md | 3 + skyulf-core/setup.py | 2 + skyulf-core/skyulf/integrations/__init__.py | 1 + .../skyulf/integrations/mlflow/__init__.py | 5 + .../skyulf/integrations/mlflow/tracking.py | 180 +++++++ .../integrations/test_mlflow_tracking.py | 197 ++++++++ uv.lock | 452 +++++++++++++++++- 14 files changed, 952 insertions(+), 13 deletions(-) create mode 100644 docs/user_guide/mlflow_tracking.md create mode 100644 requirements-mlflow.txt create mode 100644 skyulf-core/skyulf/integrations/__init__.py create mode 100644 skyulf-core/skyulf/integrations/mlflow/__init__.py create mode 100644 skyulf-core/skyulf/integrations/mlflow/tracking.py create mode 100644 skyulf-core/tests/integrations/test_mlflow_tracking.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index bffd0aaae..de9b2f44d 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -90,12 +90,16 @@ execution and MLflow adapters remain under development. - [Illustrated inference guide](../docs/user_guide/inference_flow.md) covering fitted FE/model reuse, a numerical local/Spark example, and available inference paths. Includes four SVG diagrams and editable Mermaid sources. +- Optional MLflow tracking through `TrackingConfig` and `track_run`, with a + dependency-free disabled mode, explicit client-bound run IDs, FINISHED/FAILED + lifecycle, `raise`/`warn` failure policy, and opt-in config artifact digest. + Install it with `skyulf-core[mlflow]` or `requirements-mlflow.txt`. ### Planned scope — not yet available - Further native Spark nodes and broader portable-state coverage. - Worker wheel packaging and scale/RSS validation for production Spark clusters. -- Optional MLflow tracking/model packaging and Unity Catalog model resolution. +- Optional MLflow model packaging and Unity Catalog model resolution. - Scheduled batch inference with reproducible model versions and Delta outputs. Endpoint integrations and template/Databricks Bundle generation follow the diff --git a/docs/user_guide/mlflow_tracking.md b/docs/user_guide/mlflow_tracking.md new file mode 100644 index 000000000..2d9240ad5 --- /dev/null +++ b/docs/user_guide/mlflow_tracking.md @@ -0,0 +1,59 @@ +# Optional MLflow tracking + +Skyulf Core keeps experiment tracking separate from training and inference. The +base installation does not import or require MLflow. Install the optional +extra only for jobs that should create tracking runs: + +```bash +pip install skyulf-core[mlflow] +# or, from this repository: +uv pip install -r requirements-mlflow.txt +``` + +Use `TrackingConfig(enabled=False)` for a local or Spark job that does not need +tracking. The returned handle has the same logging methods, but they are no-op +and do not construct a client or make a network call: + +```python +from skyulf.integrations.mlflow import TrackingConfig, track_run + +with track_run(TrackingConfig(), run_name="offline-fit") as run: + # The training code remains unchanged when tracking is off. + run.log_metrics({"rmse": 0.5}) +``` + +Enable tracking with a tracking URI and, optionally, a named experiment. The +adapter uses a client-bound run ID instead of MLflow's process-global active +run. This makes concurrent jobs independent and leaves a caller-owned active +run open: + +```python +config = TrackingConfig( + enabled=True, + tracking_uri="sqlite:///mlflow.db", + experiment_name="skyulf-training", +) + +with track_run(config, run_name="fit-2026-09") as run: + run.log_params({"engine": "pandas", "model": "random_forest"}) + run.log_metrics({"rmse": 0.42}) + run.set_tags({"stage": "validation"}) + run.log_config({"features": ["age", "income"], "target": "label"}) +``` + +`log_config` is explicit. Skyulf does not automatically serialize an entire +pipeline configuration, input rows, or environment variables because those +may contain sensitive data. The artifact receives a deterministic SHA-256 +parameter named `config_sha256`. + +The default `failure_policy="raise"` propagates tracking failures. Use +`failure_policy="warn"` when the model result must be preserved even if the +tracking service is unavailable; inspect `run.tracking_error` and propagate it +to your job metadata if the surrounding runner has such a field. The adapter +does not write backend job metadata itself. A successful context terminates its +own run as `FINISHED`; an exception in the training body terminates it as +`FAILED`. + +This integration creates tracking metadata only. Model packaging, registry or +Unity Catalog resolution, Delta batch publication, and Databricks deployment +are separate later stages of the 0.9.0 initiative. diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index 2fe114134..20af4e9b0 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -30,12 +30,13 @@ failure_policy="raise")`; `track_run(config, *, run_name)` context manager. Yield edilen run nesnesi `log_metrics`, `log_params`, `set_tags` sunar; disabled durumda aynı arayüzle no-op ve network/import yok. -- [ ] MLflow kurulu olmayan base ortamda import ve disabled eğitim testi yaz. -- [ ] URI/experiment seçimi açık client/run_id kapsamına bağlı olsun; eşzamanlı +- [x] MLflow kurulu olmayan base ortamda import ve disabled eğitim testi yaz. +- [x] URI/experiment seçimi açık client/run_id kapsamına bağlı olsun; eşzamanlı iki çalışmanın run id'si karışmasın. Kullanıcının aktif run'ını sessizce kapatma. -- [ ] Exception'da run FAILED; başarıda FINISHED. Varsayılan `raise`; opt-in - `warn` durumunda model sonucu korunur ve tracking kaybı sonuç metadata'sında görünür. -- [ ] Explicit param/metric log; params limitinde tam config artifact + digest; +- [x] Exception'da run FAILED; başarıda FINISHED. Varsayılan `raise`; opt-in + `warn` durumunda model sonucu korunur ve tracking kaybı `run.tracking_error` + üzerinde görünür; dış runner bunu kendi sonuç metadata'sına taşır. +- [x] Explicit param/metric log; params limitinde tam config artifact + digest; veri satırları ve secret içerebilen bütün config otomatik loglanmaz. ```python @@ -54,6 +55,12 @@ def test_disabled_tracking_never_constructs_client(monkeypatch): **Komut:** `python -m pytest skyulf-core/tests/integrations/test_mlflow_tracking.py -q` **Kabul:** Base dependency isolation; local geçici tracking store'da gerçek run lifecycle. +**Validation record (2026-09-22):** `skyulf.integrations.mlflow.tracking` keeps +MLflow lazy and client-bound. Base tests passed with MLflow absent; the isolated +MLflow 3.16.1 environment passed all 8 tracking tests, including SQLite +FINISHED/FAILED lifecycle, concurrent run-ID isolation, caller active-run +preservation, explicit config digest/artifact, and warn-mode failure handling. + ## SM-13 — MLflow model flavor ve bağımsız yükleme **Bağımlılık:** SM-12. **Oluştur:** `skyulf/integrations/mlflow/model.py`, diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 06bc3ae57..826a6bd21 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,11 +1,12 @@ # Session handoff - 2026-09-22 -SM-11 is complete after the corrective validation gate. Resume with SM-12. +SM-11 is complete after the corrective validation gate. SM-12 is now complete; +resume with SM-13. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-11 are complete; SM-12 is READY. +- SM-00 through SM-12 are complete; SM-13 is READY. - Last implementation commits: `04dbe303` (distributed classification inference) and `7cdd622c` (nullable Arrow transport and oracle hardening). - Last guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). @@ -68,7 +69,11 @@ The strict documentation build, four rendered diagrams and commit hooks passed. A built 0.9.0 wheel imported the worker inference module in a separate process. Synthetic local measurements recorded 10k/2 partitions at 3.929s and 50k/8 partitions at 8.089s with driver peak RSS 246.2/246.8 MB. These are local -evidence only; Databricks worker-wheel deployment and MLflow remain later gates. +evidence only; Databricks worker-wheel deployment remains a later gate. SM-12 +also added optional MLflow tracking: the base environment keeps MLflow absent, +while an isolated MLflow 3.16.1 environment passed all 8 tracking tests for +explicit client-bound lifecycle, concurrency, caller-run preservation, config +digest/artifact logging, and warn-mode degradation. Three pre-existing untracked directories remain outside this change: `.tmp-review-model/`, `.tmp-spark-review-full/`, `.tmp-spark-review-pytest/`. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 205531707..c31ded5b9 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-22. **SM-00–SM-11 tamamlandı; sıradaki SM-12. Hedef: 0.9.0.** +Güncelleme: 2026-09-22. **SM-00–SM-12 tamamlandı; sıradaki SM-13. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-12. @@ -23,8 +23,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-09 | Native FE + worker model | SM-08 | DONE | Spark tahmini local ile key bazında aynı; aşağıda kanıt | | SM-10 | Worker Python FE + model | SM-09 | DONE | Batch-safe portable FE; window gibi yollar açık ret | | SM-11 | Classification ve ölçek kapısı | SM-10 | DONE | Class/proba/threshold parity; transport, packaging and scale evidence | -| SM-12 | Opsiyonel MLflow tracking | SM-11 | READY | Off bağımsız; gerçek run lifecycle ve izolasyon | -| SM-13 | MLflow model packaging | SM-12 | WAIT | Temiz ortamda pyfunc yükleme ve parity | +| SM-12 | Opsiyonel MLflow tracking | SM-11 | DONE | Off bağımsız; gerçek run lifecycle ve izolasyon | +| SM-13 | MLflow model packaging | SM-12 | READY | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | | SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | | SM-16 | Gerçek Databricks kapısı | SM-15 | WAIT | Job/run kanıtı; UC load; iki inference yolu | @@ -47,6 +47,28 @@ gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. +## SM-12 — 2026-09-22 validation record + +- Added the optional `skyulf.integrations.mlflow` adapter, the `mlflow` package + extra, `requirements-mlflow.txt`, and the English tracking guide. Importing + the adapter does not import MLflow; disabled tracking is a no-op with no + client construction or network access. +- `TrackingConfig` and `track_run` use an explicit `MlflowClient` and run ID. + They do not mutate MLflow's process-global active run, so concurrent contexts + remain isolated and a caller-owned run stays open. Explicit metrics, params, + tags, and an opt-in config artifact/digest are supported. +- Successful contexts terminate `FINISHED`; body exceptions terminate `FAILED`. + The default `raise` policy propagates tracking failures. `warn` preserves the + body result and exposes `run.tracking_error`; an outer runner may propagate + that value into its own result metadata. +- Base verification (`.venv`): **4 passed, 4 skipped** for the integration + tests; MLflow is absent in that environment. Optional verification in an + isolated MLflow 3.16.1 environment: **8 passed**. Ruff and ty checks passed + for the new Python files. +- Scope boundary: this task adds run tracking only. MLflow model packaging, + registry/Unity Catalog, Databricks batch delivery, endpoints, and templates + remain SM-13 onward. + ## Bir görevi kapatma kaydı Her DONE satırına aynı dosyada aşağıdaki bilgileri içeren tarihli kayıt ekle: diff --git a/mkdocs.yml b/mkdocs.yml index b8d3bc960..3dbe9dba6 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -76,6 +76,7 @@ nav: - Spark (Development): user_guide/spark.md - Inference Bundles (Development): user_guide/inference_bundles.md - Inference Flow (Development): user_guide/inference_flow.md + - MLflow Tracking (Development): user_guide/mlflow_tracking.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/requirements-mlflow.txt b/requirements-mlflow.txt new file mode 100644 index 000000000..5061ba2b4 --- /dev/null +++ b/requirements-mlflow.txt @@ -0,0 +1,3 @@ +# Optional MLflow tracking/model integration for skyulf-core. +# This file is separate from the base and Spark environments. +mlflow>=3.10,<4.0 diff --git a/skyulf-core/README.md b/skyulf-core/README.md index 07e8d15ba..3b2eeb8a9 100644 --- a/skyulf-core/README.md +++ b/skyulf-core/README.md @@ -64,6 +64,9 @@ pip install skyulf-core[text] # All non-geo optional runtime features pip install skyulf-core[all] + +# Optional experiment tracking +pip install skyulf-core[mlflow] ``` `all` intentionally excludes the native geospatial stack; add `[geo]` only when you need geospatial nodes. diff --git a/skyulf-core/setup.py b/skyulf-core/setup.py index 78d0d06a2..23a8d2849 100644 --- a/skyulf-core/setup.py +++ b/skyulf-core/setup.py @@ -43,6 +43,7 @@ extras_require={ # Experimental test/runtime dependency only; node support is gated separately. "spark": ["pyspark>=4.0.3,<4.1.0", "pandas>=2.0.0,<3.0.0"], + "mlflow": ["mlflow>=3.10,<4.0"], "dev": [ "pytest", "pytest-cov>=4.1.0,<5.0.0", @@ -94,6 +95,7 @@ "lightgbm>=4.0.0", "sentence-transformers>=2.2.0", "shap>=0.46.0,<1.0.0", + "mlflow>=3.10,<4.0", ], }, python_requires=">=3.12", diff --git a/skyulf-core/skyulf/integrations/__init__.py b/skyulf-core/skyulf/integrations/__init__.py new file mode 100644 index 000000000..2b5cac730 --- /dev/null +++ b/skyulf-core/skyulf/integrations/__init__.py @@ -0,0 +1 @@ +"""Optional integrations for external tracking and serving systems.""" diff --git a/skyulf-core/skyulf/integrations/mlflow/__init__.py b/skyulf-core/skyulf/integrations/mlflow/__init__.py new file mode 100644 index 000000000..62e00f6a8 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/__init__.py @@ -0,0 +1,5 @@ +"""Optional MLflow adapters; importing this package does not import MLflow.""" + +from .tracking import TrackingConfig, TrackingRun, track_run + +__all__ = ["TrackingConfig", "TrackingRun", "track_run"] diff --git a/skyulf-core/skyulf/integrations/mlflow/tracking.py b/skyulf-core/skyulf/integrations/mlflow/tracking.py new file mode 100644 index 000000000..3ebec21b9 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/tracking.py @@ -0,0 +1,180 @@ +"""Explicit, optional MLflow tracking lifecycle for Skyulf jobs. + +The adapter uses ``MlflowClient`` directly instead of MLflow's process-global +fluent active-run state. This keeps independent jobs isolated and avoids +closing a run owned by a caller. MLflow is imported only after tracking is +enabled. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Iterator, Mapping +from contextlib import contextmanager, suppress +from dataclasses import dataclass, field +from typing import Any, Literal + + +@dataclass(frozen=True, slots=True) +class TrackingConfig: + """Configure optional MLflow tracking without changing local execution.""" + + enabled: bool = False + tracking_uri: str | None = None + experiment_name: str | None = None + failure_policy: Literal["raise", "warn"] = "raise" + + def __post_init__(self) -> None: + """Reject ambiguous configuration before a client or network call exists.""" + if type(self.enabled) is not bool: + raise TypeError("enabled must be a bool.") + if self.tracking_uri is not None and ( + type(self.tracking_uri) is not str or not self.tracking_uri.strip() + ): + raise ValueError("tracking_uri must be a non-empty string or None.") + if self.experiment_name is not None and ( + type(self.experiment_name) is not str or not self.experiment_name.strip() + ): + raise ValueError("experiment_name must be a non-empty string or None.") + if self.failure_policy not in ("raise", "warn"): + raise ValueError("failure_policy must be 'raise' or 'warn'.") + + +@dataclass(slots=True) +class TrackingRun: + """Client-bound run handle exposed by :func:`track_run`.""" + + client: Any = field(repr=False, default=None) + run_id: str | None = None + enabled: bool = False + failure_policy: Literal["raise", "warn"] = "raise" + tracking_error: str | None = None + + def log_metrics(self, metrics: Mapping[str, float]) -> None: + """Log explicitly selected numeric metrics for this run.""" + if not self.enabled: + return + for key, value in _items(metrics, "metrics"): + self._call(self.client.log_metric, self.run_id, key, float(value)) + + def log_params(self, params: Mapping[str, object]) -> None: + """Log explicitly selected parameters, preserving MLflow's string values.""" + if not self.enabled: + return + for key, value in _items(params, "params"): + self._call(self.client.log_param, self.run_id, key, str(value)) + + def set_tags(self, tags: Mapping[str, object]) -> None: + """Set explicitly selected run tags.""" + if not self.enabled: + return + for key, value in _items(tags, "tags"): + self._call(self.client.set_tag, self.run_id, key, str(value)) + + def log_config( + self, config: Mapping[str, object], *, artifact_file: str = "config.json" + ) -> None: + """Store an explicit config artifact and its digest without auto-logging data.""" + if not self.enabled: + return + if not isinstance(config, Mapping): + raise TypeError("config must be a mapping.") + if type(artifact_file) is not str or not artifact_file.strip(): + raise ValueError("artifact_file must be a non-empty string.") + try: + payload = json.dumps(config, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + except (TypeError, ValueError) as exc: + raise ValueError("config must be JSON serializable.") from exc + digest = hashlib.sha256(payload.encode("utf-8")).hexdigest() + self._call(self.client.log_dict, self.run_id, dict(config), artifact_file) + self.log_params({"config_sha256": digest}) + + def _call(self, operation: Any, *args: object, **kwargs: object) -> Any: + """Run one client operation and apply the configured failure policy.""" + if not self.enabled: + return None + try: + return operation(*args, **kwargs) + except Exception as exc: # noqa: BLE001 - tracking policy must contain client failures + self.tracking_error = str(exc) or type(exc).__name__ + if self.failure_policy == "raise": + raise + return None + + def _terminate(self, status: str) -> None: + """Terminate this run without touching any process-global active run.""" + if self.enabled: + self._call(self.client.set_terminated, self.run_id, status=status) + + +@contextmanager +def track_run(config: TrackingConfig, *, run_name: str) -> Iterator[TrackingRun]: + """Yield an isolated no-op or MLflow run and close it with the body status.""" + if not isinstance(config, TrackingConfig): + raise TypeError("config must be TrackingConfig.") + if type(run_name) is not str or not run_name.strip(): + raise ValueError("run_name must be a non-empty string.") + if not config.enabled: + yield TrackingRun(failure_policy=config.failure_policy) + return + + try: + client = _make_client(config.tracking_uri) + experiment_id = _get_or_create_experiment(client, config.experiment_name) + created = client.create_run(experiment_id=experiment_id, run_name=run_name) + run = TrackingRun( + client=client, + run_id=created.info.run_id, + enabled=True, + failure_policy=config.failure_policy, + ) + except Exception as exc: # noqa: BLE001 - configured policy controls optional service failure + if config.failure_policy == "raise": + raise + run = TrackingRun( + failure_policy=config.failure_policy, + tracking_error=str(exc) or type(exc).__name__, + ) + yield run + return + + try: + yield run + except BaseException: + with suppress(Exception): # Preserve the original training exception. + run._terminate("FAILED") + raise + else: + run._terminate("FINISHED") + + +def _make_client(tracking_uri: str | None) -> Any: + """Construct an MLflow client lazily, keeping the base import dependency-free.""" + from mlflow import ( # noqa: PLC0415 - optional dependency is lazy by design # ty: ignore[unresolved-import] + MlflowClient, # ty: ignore[unresolved-import] + ) + + return MlflowClient(tracking_uri=tracking_uri) + + +def _get_or_create_experiment(client: Any, experiment_name: str | None) -> str: + """Resolve an experiment through the supplied client without global MLflow state.""" + if experiment_name is None: + return "0" + existing = client.get_experiment_by_name(experiment_name) + if existing is not None: + return existing.experiment_id + return client.create_experiment(experiment_name) + + +def _items(values: Mapping[str, Any], label: str) -> list[tuple[str, Any]]: + """Validate explicit log mappings and return stable key/value pairs.""" + if not isinstance(values, Mapping): + raise TypeError(f"{label} must be a mapping.") + result: list[tuple[str, Any]] = [] + for key, value in values.items(): + if type(key) is not str or not key: + raise TypeError(f"{label} keys must be non-empty strings.") + result.append((key, value)) + return result diff --git a/skyulf-core/tests/integrations/test_mlflow_tracking.py b/skyulf-core/tests/integrations/test_mlflow_tracking.py new file mode 100644 index 000000000..911debe1b --- /dev/null +++ b/skyulf-core/tests/integrations/test_mlflow_tracking.py @@ -0,0 +1,197 @@ +"""Contract tests for the optional MLflow tracking adapter.""" + +from __future__ import annotations + +import importlib.util +import threading +from pathlib import Path + +import pytest + +from skyulf.integrations.mlflow import tracking + + +def test_disabled_tracking_never_constructs_client(monkeypatch: pytest.MonkeyPatch) -> None: + """Offline training must not import or construct an MLflow client.""" + + def forbidden(*args: object, **kwargs: object) -> object: + raise AssertionError("MLflow client was constructed") + + monkeypatch.setattr(tracking, "_make_client", forbidden) + config = tracking.TrackingConfig() + with tracking.track_run(config, run_name="offline") as run: + run.log_metrics({"rmse": 0.5}) + run.log_params({"engine": "pandas"}) + run.set_tags({"mode": "local"}) + + assert run.enabled is False + assert run.run_id is None + assert run.tracking_error is None + + +def test_tracking_config_rejects_invalid_failure_policy() -> None: + """Only explicit raise or warn policies can control tracking failures.""" + with pytest.raises(ValueError, match="failure_policy"): + tracking.TrackingConfig(failure_policy="ignore") # ty: ignore[invalid-argument-type] + + +def test_enabled_tracking_reports_missing_optional_dependency( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Enabling tracking fails explicitly when the optional client cannot be loaded.""" + + def missing_client(uri: str | None) -> object: + raise ModuleNotFoundError("No module named 'mlflow'") + + monkeypatch.setattr(tracking, "_make_client", missing_client) + config = tracking.TrackingConfig(enabled=True) + with ( + pytest.raises(ModuleNotFoundError, match="mlflow"), + tracking.track_run(config, run_name="requires-mlflow"), + ): + pass + + +@pytest.mark.skipif( + importlib.util.find_spec("mlflow") is None, + reason="MLflow is an optional test dependency", +) +def test_enabled_tracking_logs_a_real_run_and_explicit_config(tmp_path: Path) -> None: + """An enabled run stores metrics, tags, and an explicitly requested config artifact.""" + db_path = (tmp_path / "tracking.db").resolve() + uri = f"sqlite:///{db_path.as_posix()}" + config = tracking.TrackingConfig( + enabled=True, + tracking_uri=uri, + experiment_name="skyulf-sm12-real", + ) + + with tracking.track_run(config, run_name="real-run") as run: + run.log_metrics({"rmse": 0.5}) + run.log_params({"engine": "pandas"}) + run.set_tags({"mode": "local"}) + run.log_config({"engine": "pandas", "rows": 10}) + run_id = run.run_id + + assert run_id + client = tracking._make_client(uri) + stored = client.get_run(run_id) + assert stored.info.status == "FINISHED" + assert stored.data.metrics["rmse"] == 0.5 + assert stored.data.params["engine"] == "pandas" + assert stored.data.tags["mode"] == "local" + assert stored.data.params["config_sha256"] + artifacts = {item.path for item in client.list_artifacts(run_id)} + assert "config.json" in artifacts + + +@pytest.mark.skipif( + importlib.util.find_spec("mlflow") is None, + reason="MLflow is an optional test dependency", +) +def test_exception_marks_enabled_run_failed(tmp_path: Path) -> None: + """A failed training body must terminate its own MLflow run as FAILED.""" + db_path = (tmp_path / "tracking.db").resolve() + config = tracking.TrackingConfig( + enabled=True, + tracking_uri=f"sqlite:///{db_path.as_posix()}", + experiment_name="skyulf-sm12-failure", + ) + + with ( + pytest.raises(RuntimeError, match="training failed"), + tracking.track_run(config, run_name="failed-run") as run, + ): + run.log_params({"step": "fit"}) + raise RuntimeError("training failed") + + client = tracking._make_client(config.tracking_uri) + experiment = client.get_experiment_by_name(config.experiment_name) + stored = client.search_runs([experiment.experiment_id])[0] + assert stored.info.status == "FAILED" + + +@pytest.mark.skipif( + importlib.util.find_spec("mlflow") is None, + reason="MLflow is an optional test dependency", +) +def test_run_ids_are_isolated_for_concurrent_contexts(tmp_path: Path) -> None: + """Concurrent contexts use distinct client-bound run IDs without global active-run state.""" + db_path = (tmp_path / "tracking.db").resolve() + config = tracking.TrackingConfig( + enabled=True, + tracking_uri=f"sqlite:///{db_path.as_posix()}", + experiment_name="skyulf-sm12-concurrent", + ) + barrier = threading.Barrier(2) + run_ids: list[str] = [] + + def worker(name: str) -> None: + with tracking.track_run(config, run_name=name) as run: + barrier.wait(timeout=10) + run.set_tags({"worker": name}) + run_id = run.run_id + assert run_id + run_ids.append(run_id) + + first = threading.Thread(target=worker, args=("one",)) + second = threading.Thread(target=worker, args=("two",)) + first.start() + second.start() + first.join(timeout=20) + second.join(timeout=20) + + assert not first.is_alive() and not second.is_alive() + assert len(run_ids) == 2 + assert len(set(run_ids)) == 2 + + +@pytest.mark.skipif( + importlib.util.find_spec("mlflow") is None, + reason="MLflow is an optional test dependency", +) +def test_tracking_does_not_close_callers_active_run(tmp_path: Path) -> None: + """A nested Skyulf run must leave a caller-owned fluent run active.""" + import mlflow # ty: ignore[unresolved-import] + + db_path = (tmp_path / "tracking.db").resolve() + uri = f"sqlite:///{db_path.as_posix()}" + config = tracking.TrackingConfig( + enabled=True, + tracking_uri=uri, + experiment_name="skyulf-sm12-caller-run", + ) + client = tracking._make_client(uri) + experiment_id = tracking._get_or_create_experiment(client, config.experiment_name) + mlflow.set_tracking_uri(uri) + + with mlflow.start_run(experiment_id=experiment_id, run_name="caller") as caller: + with tracking.track_run(config, run_name="skyulf"): + assert mlflow.active_run().info.run_id == caller.info.run_id + assert mlflow.active_run().info.run_id == caller.info.run_id + + +def test_warn_policy_preserves_body_result_when_logging_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Warn mode exposes tracking loss while leaving the training body successful.""" + + class BrokenClient: + def create_run(self, **kwargs: object) -> object: + return type("Created", (), {"info": type("Info", (), {"run_id": "warn-run"})()})() + + def log_metric(self, *args: object, **kwargs: object) -> None: + raise RuntimeError("tracking unavailable") + + def set_terminated(self, *args: object, **kwargs: object) -> None: + return None + + monkeypatch.setattr(tracking, "_make_client", lambda uri: BrokenClient()) + config = tracking.TrackingConfig(enabled=True, failure_policy="warn") + with tracking.track_run(config, run_name="warn") as run: + result = 42 + run.log_metrics({"rmse": 0.5}) + + assert result == 42 + assert run.run_id == "warn-run" + assert run.tracking_error == "tracking unavailable" diff --git a/uv.lock b/uv.lock index 32be08ebe..67b17e4c1 100644 --- a/uv.lock +++ b/uv.lock @@ -423,6 +423,15 @@ css = [ { name = "tinycss2" }, ] +[[package]] +name = "blinker" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/21/28/9b3f50ce0e048515135495f198351908d99540d69bfdc8c1d15b73dc55ce/blinker-1.9.0.tar.gz", hash = "sha256:b4ce2265a7abece45e7cc896e98dbebe6cead56bcf805a3d23136d145f5445bf", size = 22460, upload-time = "2024-11-08T17:25:47.436Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, +] + [[package]] name = "boto3" version = "1.43.0" @@ -465,6 +474,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0d/fe/6bea5c9162869c5beba5d9c8abbed835ec85bf1ec1fba05a3822325c45f3/build-1.5.0-py3-none-any.whl", hash = "sha256:13f3eecb844759ab66efec90ca17639bbf14dc06cb2fdf37a9010322d9c50a6f", size = 26018, upload-time = "2026-04-30T03:18:23.644Z" }, ] +[[package]] +name = "cachetools" +version = "7.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/29/2c/3f18755527b03ca9ff6be724bd5370cb777c76a87f17301377cf04a4729b/cachetools-7.2.0.tar.gz", hash = "sha256:bcac1a1b8da6909994a2957238a57b8140dab7c5c5c69a43669654fe87a33c1d", size = 41129, upload-time = "2026-09-16T20:48:27.209Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/bb/1c6e7a89b11da19f137e4ef5a5c5fe47a5bb686449ba343944ccf8fb34b2/cachetools-7.2.0-py3-none-any.whl", hash = "sha256:3045213f186b89fdd95d94441354c4bd87c570b7a38d8c3fd1d9dd37f6dc90d8", size = 16918, upload-time = "2026-09-16T20:48:25.575Z" }, +] + [[package]] name = "causal-learn" version = "0.1.4.5" @@ -1002,6 +1020,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, ] +[[package]] +name = "databricks-sdk" +version = "0.140.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "google-auth" }, + { name = "protobuf" }, + { name = "requests" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/90/a1/01d3419b95570bc79a2b3481bb2876637a174e35fa195c9391e881ad7d82/databricks_sdk-0.140.0.tar.gz", hash = "sha256:e61d756bd17bf4fc1cdbdde543364ef792f45d0982e0258c913843720d06d8fd", size = 1108643, upload-time = "2026-09-19T04:31:50.193Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/43/4e95a94137d7291c0927f52e3d975f7328503c0e847e5816b39b0d865607/databricks_sdk-0.140.0-py3-none-any.whl", hash = "sha256:32d1470de6364ceb80f70350e22335be850a13376874f8764384b671f2f6a2af", size = 1052867, upload-time = "2026-09-19T04:31:48.362Z" }, +] + [[package]] name = "debugpy" version = "1.8.17" @@ -1062,6 +1095,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl", hash = "sha256:9659f7d87e46584a30b5780e43ac7a2143098441670ff0a49d5f9034c54a6c16", size = 469047, upload-time = "2025-07-17T16:51:58.613Z" }, ] +[[package]] +name = "docker" +version = "7.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "requests" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/88/7f/731ff914b0255d3d065f45fd4e626d4b8c95dbcbaada049f337a6ac16410/docker-7.2.0.tar.gz", hash = "sha256:cebb93773d334f778e023a7ee352a8d6e13ab1bd3b863a4d4a59dec897df43ac", size = 118731, upload-time = "2026-07-09T14:53:46.39Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/23/529140fe1aab80fc6992f93a706deec709140a6397439139a054e1515c45/docker-7.2.0-py3-none-any.whl", hash = "sha256:a3f45fdeb9165e2d25d9a1d02ddf3bc70fb572cf5ebbf9b58558c22caf29b71f", size = 148775, upload-time = "2026-07-09T14:53:45.224Z" }, +] + [[package]] name = "docutils" version = "0.23" @@ -1177,6 +1224,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/13/37/a065dc3bd6e49423a6532c642ca7378d3f467b1ef44c2800c937af7f9739/filelock-3.29.4-py3-none-any.whl", hash = "sha256:dac1648087d5115554850d113e7dd8c83ab2d38e3435dde2d4f163847e57b767", size = 42757, upload-time = "2026-06-13T16:11:59.582Z" }, ] +[[package]] +name = "flask" +version = "3.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blinker" }, + { name = "click" }, + { name = "itsdangerous" }, + { name = "jinja2" }, + { name = "markupsafe" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" }, +] + +[[package]] +name = "flask-cors" +version = "6.0.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flask" }, + { name = "werkzeug" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/47/03/4e464a50860f9adf08b5c1d3479cb8ea1f12af2aa69535c7042c6e628135/flask_cors-6.0.5.tar.gz", hash = "sha256:30c5031552cd59f620ac0c8211dac45b345d3b2df310e7721879e4f46ef9c601", size = 101386, upload-time = "2026-06-08T20:20:17.765Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/55/5bb1a2d918e9f02f131e47a59032bae70e48050e986e941511fd737a935c/flask_cors-6.0.5-py3-none-any.whl", hash = "sha256:68fcf75693e961f3af26683b23c4b9a8fb6b64de17d20d0c37b95e8de7ab2ed8", size = 16692, upload-time = "2026-06-08T20:20:16.247Z" }, +] + [[package]] name = "fonttools" version = "4.63.0" @@ -1313,6 +1390,79 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3c/78/6a04792ace63a93e162f1305392d500ae8ddcb620e7eb88a22fd622b35bb/geopandas-1.1.3-py3-none-any.whl", hash = "sha256:90d62a64f95eaa3be2ccc115c5f3d6e24208bb11983b390fdc0621a3eccd0230", size = 342514, upload-time = "2026-03-09T21:49:07.973Z" }, ] +[[package]] +name = "gitdb" +version = "4.0.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "smmap" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" }, +] + +[[package]] +name = "gitpython" +version = "3.1.62" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gitdb" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/db/3ca813cbacb23ab6fe46ff38a9b5ef8e73e970c8051f2ce903aacafe0446/gitpython-3.1.62.tar.gz", hash = "sha256:1791de66309bc0c7cfca40bf8d2e3de7ca091cbf94e6051be1ad0722c61062af", size = 231728, upload-time = "2026-09-07T02:57:21.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/0b/29d7965215f8ef830a7ca1f42997fe13e5693d85e9edb18f938d063ef5f2/gitpython-3.1.62-py3-none-any.whl", hash = "sha256:7002251225e10e29d2e1f49e6532613fe5d5d9f0b6f1f02997a52b38fe56899e", size = 222753, upload-time = "2026-09-07T02:57:19.762Z" }, +] + +[[package]] +name = "google-auth" +version = "2.58.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/ca/f398a483ce5aad18ca2f735646e45ccee2439bd94a41a4ad0cfa646bd495/google_auth-2.58.0.tar.gz", hash = "sha256:55e30cf15e737de92c5323d78cda8a83fcd57e7ffbaf900c4600039fd60a80fd", size = 380018, upload-time = "2026-09-09T20:49:38.043Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/59/13/477d90d09591b3938b45c4e11f4d8a51291682112cb5efcac961e815d562/google_auth-2.58.0-py3-none-any.whl", hash = "sha256:8a9c4645bb4c8e91668fb1934b95ae6a8687084232753639220ba9bf04a1610d", size = 262404, upload-time = "2026-09-09T20:49:33.951Z" }, +] + +[[package]] +name = "graphene" +version = "3.4.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "graphql-core" }, + { name = "graphql-relay" }, + { name = "python-dateutil" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cc/f6/bf62ff950c317ed03e77f3f6ddd7e34aaa98fe89d79ebd660c55343d8054/graphene-3.4.3.tar.gz", hash = "sha256:2a3786948ce75fe7e078443d37f609cbe5bb36ad8d6b828740ad3b95ed1a0aaa", size = 44739, upload-time = "2024-11-09T20:44:25.757Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/66/e0/61d8e98007182e6b2aca7cf65904721fb2e4bce0192272ab9cb6f69d8812/graphene-3.4.3-py2.py3-none-any.whl", hash = "sha256:820db6289754c181007a150db1f7fff544b94142b556d12e3ebc777a7bf36c71", size = 114894, upload-time = "2024-11-09T20:44:23.851Z" }, +] + +[[package]] +name = "graphql-core" +version = "3.2.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/11/7f/671c1046fe72ba5b62be2de3979ea9e61cb3dba8f1edfb880b811f8bdf8b/graphql_core-3.2.12.tar.gz", hash = "sha256:4579094d5fc8a1a59555a9b18e51b320779d9bbc63e2302c519af0c4919d9543", size = 531478, upload-time = "2026-08-27T20:25:48.607Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/b6/304c572e79b9e82982dbd5091e26a89f5018e565868091d804c2142f6ba5/graphql_core-3.2.12-py3-none-any.whl", hash = "sha256:3d8f104532070485e13caa4092c1e71cda2ba6cffd96e98f285111ee10ed1e51", size = 216042, upload-time = "2026-08-27T20:25:47.234Z" }, +] + +[[package]] +name = "graphql-relay" +version = "3.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "graphql-core" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d1/13/98fbf8d67552f102488ffc16c6f559ce71ea15f6294728d33928ab5ff14d/graphql-relay-3.2.0.tar.gz", hash = "sha256:1ff1c51298356e481a0be009ccdff249832ce53f30559c1338f22a0e0d17250c", size = 50027, upload-time = "2022-04-16T11:03:45.447Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/74/16/a4cf06adbc711bd364a73ce043b0b08d8fa5aae3df11b6ee4248bcdad2e0/graphql_relay-3.2.0-py3-none-any.whl", hash = "sha256:c9b22bd28b170ba1fe674c74384a8ff30a76c8e26f88ac3aa1584dd3179953e5", size = 16940, upload-time = "2022-04-16T11:03:43.895Z" }, +] + [[package]] name = "graphviz" version = "0.21" @@ -1361,6 +1511,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e3/a5/6ddab2b4c112be95601c13428db1d8b6608a8b6039816f2ba09c346c08fc/greenlet-3.2.4-cp314-cp314-win_amd64.whl", hash = "sha256:e37ab26028f12dbb0ff65f29a8d3d44a765c61e729647bf2ddfbbed621726f01", size = 303425, upload-time = "2025-08-07T13:32:27.59Z" }, ] +[[package]] +name = "gunicorn" +version = "26.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/8a/e4ef6ee11701b6cd64702848415ffb69eeff85cb388a3c6c7fe86f22f3f8/gunicorn-26.2.0.tar.gz", hash = "sha256:62b864895d9ebff0b2f9867ba04fe811c93121596540830c9c916d0769668447", size = 787921, upload-time = "2026-08-24T15:05:59.3Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/85/7522a52e5e2f42faf1a129113ab63e548c42e103e9af395b7bfe65e403e2/gunicorn-26.2.0-py3-none-any.whl", hash = "sha256:bd249d0b3f7972f7432f0a6b6ff3b3ee2d129f70cd1ff6c09a9dd9e29a2b88e3", size = 228389, upload-time = "2026-08-24T15:05:57.67Z" }, +] + [[package]] name = "h11" version = "0.16.0" @@ -1481,6 +1640,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[[package]] +name = "huey" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/57/25/1281d8f3febc30b5facbfc5e4163447241711591c094dac642d32c827eb0/huey-3.4.0.tar.gz", hash = "sha256:ac9b02e741f13da4092ea19bcaafc73669e97d3153914d2fed2868df144f6dfa", size = 630013, upload-time = "2026-09-04T02:04:34.521Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/57/31/cee585bd4d1e39947a426a6736f4e17d22b454952370fb9cf48eb3103085/huey-3.4.0-py3-none-any.whl", hash = "sha256:d0580762397744026f83baae5f2b97a62474a62b8565ac75bbafefe72f9c784f", size = 136493, upload-time = "2026-09-04T02:04:32.848Z" }, +] + [[package]] name = "huggingface-hub" version = "1.16.1" @@ -1560,6 +1728,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/b5/56f1ceb568676c0231d12b2fed17ebfd606dd1f627e7372aaed5dd56bd97/imbalanced_learn-0.14.1-py3-none-any.whl", hash = "sha256:fcdff8d27870d6992ea3496230788b97ff98e24302e7f6c598701da525ae440f", size = 235365, upload-time = "2025-12-21T21:59:14.959Z" }, ] +[[package]] +name = "importlib-metadata" +version = "9.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/7e/1e7e8dc30634b93ebb3d58a3dea569ad146e656218d3960ab04f62047b29/importlib_metadata-9.0.1.tar.gz", hash = "sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99", size = 59124, upload-time = "2026-08-28T15:30:34.646Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/55/ecca97ae19075f1fac62def77731e7f535e6c1fb8f92ff08160c5e6dade8/importlib_metadata-9.0.1-py3-none-any.whl", hash = "sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0", size = 27920, upload-time = "2026-08-28T15:30:33.433Z" }, +] + [[package]] name = "iniconfig" version = "2.3.0" @@ -1654,6 +1834,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/55/e5326141505c5d5e34c5e0935d2908a74e4561eca44108fbfb9c13d2911a/isoduration-20.11.0-py3-none-any.whl", hash = "sha256:b2904c2a4228c3d44f409c8ae8e2370eb21a26f7ac2ec5446df141dde3452042", size = 11321, upload-time = "2020-11-01T10:59:58.02Z" }, ] +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + [[package]] name = "jaraco-classes" version = "3.4.0" @@ -2352,6 +2541,88 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/77/e4/288365afae98953bc01de09f686f40d8ee84578135aa7767d5d4e60b5278/mistune-3.3.4-py3-none-any.whl", hash = "sha256:ee015381e955e370962968befe1d729ab60fafb6a715ac6751763fbce38c8d4a", size = 66862, upload-time = "2026-07-22T05:22:29.419Z" }, ] +[[package]] +name = "mlflow" +version = "3.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohttp" }, + { name = "alembic" }, + { name = "cryptography" }, + { name = "docker" }, + { name = "flask" }, + { name = "flask-cors" }, + { name = "graphene" }, + { name = "gunicorn", marker = "sys_platform != 'win32'" }, + { name = "huey" }, + { name = "matplotlib" }, + { name = "mlflow-skinny" }, + { name = "mlflow-tracing" }, + { name = "numpy" }, + { name = "pandas" }, + { name = "pyarrow" }, + { name = "scikit-learn" }, + { name = "scipy" }, + { name = "skops" }, + { name = "sqlalchemy" }, + { name = "waitress", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/65/30/a7105a50760f31aa5a6514e18d32e9087011c1bcb4ad56e0cfcc1e356f8c/mlflow-3.16.1.tar.gz", hash = "sha256:044bd17d49ed216d3e38a537436622154daa5197ea41c1f3dedf155cbd8f40c0", size = 10830822, upload-time = "2026-09-16T23:14:20.369Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/37/5a0bffe04625c906be3c3482915ba0b9d824c48c53f8963cfdcfb9251547/mlflow-3.16.1-py3-none-any.whl", hash = "sha256:e4dfe69ceae31dfc7b8480e76ffe6a7f36752bdfac30e058e6430ade1fb5920b", size = 11650889, upload-time = "2026-09-16T23:14:16.557Z" }, +] + +[[package]] +name = "mlflow-skinny" +version = "3.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "cachetools" }, + { name = "click" }, + { name = "cloudpickle" }, + { name = "databricks-sdk" }, + { name = "fastapi" }, + { name = "gitpython" }, + { name = "importlib-metadata" }, + { name = "opentelemetry-api" }, + { name = "opentelemetry-proto" }, + { name = "opentelemetry-sdk" }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "pydantic" }, + { name = "python-dotenv" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "sqlparse" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "uvicorn" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f6/21/5b8e556d3fc3030affe5d6b3ecf58d9dcc972c644ebf941d77bf8b4a5769/mlflow_skinny-3.16.1.tar.gz", hash = "sha256:7298b47942b1b0e826e02191653b8c203c3bb242fb699f8beec98e928dbec115", size = 3193879, upload-time = "2026-09-16T22:08:20.298Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/f1/89f8a4386ddde208806b57f6dc8e89138e0b92ae667c0dfc5fc2d8a4d418/mlflow_skinny-3.16.1-py3-none-any.whl", hash = "sha256:41ec1697710b91d001f8951bdc2d00391a277065ed82268c81706238fa2b918e", size = 3797284, upload-time = "2026-09-16T22:08:18.176Z" }, +] + +[[package]] +name = "mlflow-tracing" +version = "3.16.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cachetools" }, + { name = "databricks-sdk" }, + { name = "opentelemetry-api" }, + { name = "opentelemetry-proto" }, + { name = "opentelemetry-sdk" }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/88/62/64068c0d17a7ba479f4dadfa78b3e48921cde8d20878414e7a4a929e66c0/mlflow_tracing-3.16.1.tar.gz", hash = "sha256:315ba1ace00d43498da2ad2b2bbb751f3198d6f9cd328168dfeb49911df41925", size = 1525331, upload-time = "2026-09-16T22:40:58.167Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/8c/f40c01433254f49f3b18ef88a4eba481a73a29494f27c072fb7a53812a76/mlflow_tracing-3.16.1-py3-none-any.whl", hash = "sha256:b3ab97c7b4f919704e0cbe0653e6e9b89cf1f8a790f8bb1b4cf7f236df258e9e", size = 1812478, upload-time = "2026-09-16T22:40:56.332Z" }, +] + [[package]] name = "momentchi2" version = "0.1.8" @@ -2817,6 +3088,57 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ee/8b/aa9e2d8b8dfa7c946f7dec5d1f8f6ba8eca062f43509a06bdb5ce93d26c0/opentelemetry_api-1.44.0.tar.gz", hash = "sha256:67647e5e9566edcf421166fdf022b3537f818635daa852b289e34604dc6fb33a", size = 72406, upload-time = "2026-07-16T15:25:32.678Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ca/6f/a04e900f465ff3221ccc395522503e2d10e79fa21f2723c8e177aae1e0d1/opentelemetry_api-1.44.0-py3-none-any.whl", hash = "sha256:94b98c893a91b88657eaac1e3ba89618cdb85be6918196705354f34728b2cdef", size = 60018, upload-time = "2026-07-16T15:25:11.657Z" }, +] + +[[package]] +name = "opentelemetry-proto" +version = "1.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/64/01/40ac4ae9a149263cc52c2cee200ddd80cb6d8db1a4610abf8eabce0fe771/opentelemetry_proto-1.44.0.tar.gz", hash = "sha256:c547a79c2f8c0c515d31509154682e5921c7cfd5ca67b70e1f9266e2c3e103f3", size = 46488, upload-time = "2026-07-16T15:25:45.34Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/7c/8be563d68e93bbefa5c8affb82ddcff91b3ad858ce49957ba7b16fd3e0ab/opentelemetry_proto-1.44.0-py3-none-any.whl", hash = "sha256:898b155a0e1557afd867478fb6158e8122a46329ca0bb8dc53cc55e98f017f56", size = 72483, upload-time = "2026-07-16T15:25:28.429Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5d/77/a6592cbc7c8d9bcc9d6757a9df45e04a7c585e3e6e7a13456da522b21109/opentelemetry_sdk-1.44.0.tar.gz", hash = "sha256:cebe7f65dc12f26ead75c6064de12fd2a9052e5060c0272d402cfa203aae123b", size = 208624, upload-time = "2026-07-16T15:25:46.078Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/23/ff077e61886ee020a17ce9c8b6fa11c601c8d8345b09ea24f605445df62a/opentelemetry_sdk-1.44.0-py3-none-any.whl", hash = "sha256:df081c4c6bcfdb1211e3e86140376792643128a25f8d72d1d27675936e7e96ad", size = 137221, upload-time = "2026-07-16T15:25:29.534Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.65b0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8f/73/0cbdebcb4cf545fdd328da14f5137e37d0770c3f26185e478b0d15d94f50/opentelemetry_semantic_conventions-0.65b0.tar.gz", hash = "sha256:f9b2b81e9d5b64f11bc952075e7e9c7fb0aab075c7fd1c46d597f1b919852d60", size = 148774, upload-time = "2026-07-16T15:25:46.902Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a6/0e/49df70d9b81fb5cbae4bbf2a49d865b09bcbcbc4eb53f5851b1027738d78/opentelemetry_semantic_conventions-0.65b0-py3-none-any.whl", hash = "sha256:1cacde7b0ad306f84c5ef08c3dbe1bbaf20165bba6f8bff43b670e555a086bcb", size = 204645, upload-time = "2026-07-16T15:25:30.688Z" }, +] + [[package]] name = "optuna" version = "4.5.0" @@ -3167,6 +3489,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/46/eba9be9daa403fa94854ce16a458c29df9a01c6c047931c3d8be6016cd9a/pre_commit_hooks-6.0.0-py2.py3-none-any.whl", hash = "sha256:76161b76d321d2f8ee2a8e0b84c30ee8443e01376121fd1c90851e33e3bd7ee2", size = 41338, upload-time = "2025-08-09T19:25:03.513Z" }, ] +[[package]] +name = "prettytable" +version = "3.17.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "wcwidth" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/45/b0847d88d6cfeb4413566738c8bbf1e1995fad3d42515327ff32cc1eb578/prettytable-3.17.0.tar.gz", hash = "sha256:59f2590776527f3c9e8cf9fe7b66dd215837cca96a9c39567414cbc632e8ddb0", size = 67892, upload-time = "2025-11-14T17:33:20.212Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ee/8c/83087ebc47ab0396ce092363001fa37c17153119ee282700c0713a195853/prettytable-3.17.0-py3-none-any.whl", hash = "sha256:aad69b294ddbe3e1f95ef8886a060ed1666a0b83018bbf56295f6f226c43d287", size = 34433, upload-time = "2025-11-14T17:33:19.093Z" }, +] + [[package]] name = "prometheus-client" version = "0.23.1" @@ -3245,6 +3579,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cc/35/cc0aaecf278bb4575b8555f2b137de5ab821595ddae9da9d3cd1da4072c7/propcache-0.3.2-py3-none-any.whl", hash = "sha256:98f1ec44fb675f5052cccc8e609c46ed23a35a1cfd18545ad4e29002d858a43f", size = 12663, upload-time = "2025-06-09T22:56:04.484Z" }, ] +[[package]] +name = "protobuf" +version = "6.33.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, +] + [[package]] name = "psutil" version = "5.9.8" @@ -3378,6 +3727,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9a/3b/6163796d69c3977d1e4287bea4a6979161cbbdd170ebb430511e8e1999ce/pyasn1-0.6.4-py3-none-any.whl", hash = "sha256:deda9277cfd454080ec40b207fb6df82206a3a2688735233cdcd8d3d565f088b", size = 84410, upload-time = "2026-07-09T01:12:32.92Z" }, ] +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + [[package]] name = "pycparser" version = "2.23" @@ -3721,6 +4082,25 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/c4/34e93fe5f5429d7570ec1fa436f1986fb1f00c3e0f43a589fe2bbcd22c3f/pytz-2025.2-py2.py3-none-any.whl", hash = "sha256:5ddf76296dd8c44c26eb8f4b6f35488f3ccbf6fbbd7adee0b7262d43f0ec2f00", size = 509225, upload-time = "2025-03-25T02:24:58.468Z" }, ] +[[package]] +name = "pywin32" +version = "312" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/ff/32aa7d2ed0ab12b323aaa64f9b75e6ad4f8fd09f9ccfc28c79414d46838d/pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b", size = 6371877, upload-time = "2026-06-04T07:49:28.836Z" }, + { url = "https://files.pythonhosted.org/packages/03/d9/77040d3b43df3f3be32ea289433d660d2727f5ba327bc73be835127d9d60/pywin32-312-cp312-cp312-win_amd64.whl", hash = "sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc", size = 6914841, upload-time = "2026-06-04T07:49:31.85Z" }, + { url = "https://files.pythonhosted.org/packages/e3/cc/7b1ec671775756020a0ee7f4feeaf3c568f0ab86bd3900088cf986937a92/pywin32-312-cp312-cp312-win_arm64.whl", hash = "sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950", size = 6727901, upload-time = "2026-06-04T07:49:34.244Z" }, + { url = "https://files.pythonhosted.org/packages/2d/41/12fbfd7f36ed2146d8bc9de96c2741296bf0d490b98508496cff322e274c/pywin32-312-cp313-cp313-win32.whl", hash = "sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c", size = 6370184, upload-time = "2026-06-04T07:49:36.253Z" }, + { url = "https://files.pythonhosted.org/packages/ba/db/36a78e3403099d31d9746d13fdcde5accc43c1155f375a34d15983a479a7/pywin32-312-cp313-cp313-win_amd64.whl", hash = "sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9", size = 6914298, upload-time = "2026-06-04T07:49:38.876Z" }, + { url = "https://files.pythonhosted.org/packages/84/37/c1697194092b76de9ed47ca124323f02c57ffc8a45c06f88a3d5acaf01eb/pywin32-312-cp313-cp313-win_arm64.whl", hash = "sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831", size = 6727640, upload-time = "2026-06-04T07:49:41.083Z" }, + { url = "https://files.pythonhosted.org/packages/fc/2b/1f3cded5822fd49c02f40544cbb5f58c7cfd6b1694869fd476cb6170ee97/pywin32-312-cp314-cp314-win32.whl", hash = "sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b", size = 6468928, upload-time = "2026-06-04T07:49:43.188Z" }, + { url = "https://files.pythonhosted.org/packages/21/82/3bf86d2e2808902013132e1ce905a7da0da53790f3836c64bf44d55e24f3/pywin32-312-cp314-cp314-win_amd64.whl", hash = "sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e", size = 7024157, upload-time = "2026-06-04T07:49:45.34Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0e/73f6d6800b4f27655abd9e9f6aaeaefcddb2b946e4674efa2bab184a7f7b/pywin32-312-cp314-cp314-win_arm64.whl", hash = "sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa", size = 6839598, upload-time = "2026-06-04T07:49:47.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/61/caa39686032d2ebdd04ff0ab5cbe163126c0066d98e00c9018646e42393b/pywin32-312-cp315-cp315-win32.whl", hash = "sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed", size = 6471159, upload-time = "2026-06-04T07:49:50.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/7e1de64a4a6f69c04214169657ccab0d93a670ea50e35eb8f489d7378249/pywin32-312-cp315-cp315-win_amd64.whl", hash = "sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5", size = 7025293, upload-time = "2026-06-04T07:49:54.857Z" }, + { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, +] + [[package]] name = "pywin32-ctypes" version = "0.2.3" @@ -4524,6 +4904,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/53/60/08cb1b41563a0a8f26a72b8c5d1726986ab535fee67aa95541b2a2cc1dfa/sklearn_compat-0.1.5-py3-none-any.whl", hash = "sha256:dddd00c442027b6a2c2fd4a86667b804a7353cdb5093bfd0d5431f5e3c135fce", size = 20966, upload-time = "2025-12-21T14:54:16.349Z" }, ] +[[package]] +name = "skops" +version = "0.15.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "packaging" }, + { name = "prettytable" }, + { name = "scikit-learn" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bf/38/19dcddf49341b4f7193b942550701b8a694ba29fed73277efd734ba1ff64/skops-0.15.0.tar.gz", hash = "sha256:29bb4585d254e895b37f74d3274a17a21ef9910702675b244e1c5edd90cd8a75", size = 668624, upload-time = "2026-09-16T13:07:42.41Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/57/ab/835d7115d2b58d8618a2bc328ae1dcd5e5503e5212cf7986e5bd06f041b9/skops-0.15.0-py3-none-any.whl", hash = "sha256:5984ac51d9b4a12af69a9e9e5f6961379933a293941197fac59a6371865f375c", size = 144572, upload-time = "2026-09-16T13:07:40.768Z" }, +] + [[package]] name = "skyulf" version = "0.9.0" @@ -4752,6 +5148,7 @@ all = [ { name = "imbalanced-learn" }, { name = "lightgbm" }, { name = "matplotlib" }, + { name = "mlflow" }, { name = "optuna" }, { name = "optuna-integration" }, { name = "rich" }, @@ -4786,6 +5183,9 @@ geo = [ { name = "rtree" }, { name = "shapely" }, ] +mlflow = [ + { name = "mlflow" }, +] modeling-lightgbm = [ { name = "lightgbm" }, ] @@ -4835,6 +5235,8 @@ requires-dist = [ { name = "lizard", marker = "extra == 'dev'", specifier = ">=1.17.0" }, { name = "matplotlib", marker = "extra == 'all'", specifier = ">=3.7.0" }, { name = "matplotlib", marker = "extra == 'viz'", specifier = ">=3.7.0" }, + { name = "mlflow", marker = "extra == 'all'", specifier = ">=3.10,<4.0" }, + { name = "mlflow", marker = "extra == 'mlflow'", specifier = ">=3.10,<4.0" }, { name = "numpy", specifier = ">=1.24.0" }, { name = "optuna", marker = "extra == 'all'", specifier = ">=3.0.0" }, { name = "optuna", marker = "extra == 'tuning'", specifier = ">=3.0.0" }, @@ -4869,7 +5271,7 @@ requires-dist = [ { name = "xgboost", marker = "extra == 'all'", specifier = ">=2.1.4" }, { name = "xgboost", marker = "extra == 'modeling-xgboost'", specifier = ">=2.1.4" }, ] -provides-extras = ["spark", "dev", "viz", "eda", "text", "nlp", "geo", "tuning", "preprocessing-imbalanced", "modeling-xgboost", "modeling-lightgbm", "explainability", "all"] +provides-extras = ["spark", "mlflow", "dev", "viz", "eda", "text", "nlp", "geo", "tuning", "preprocessing-imbalanced", "modeling-xgboost", "modeling-lightgbm", "explainability", "all"] [[package]] name = "slicer" @@ -4892,6 +5294,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2b/bb/f71c4b7d7e7eb3fc1e8c0458a8979b912f40b58002b9fbf37729b8cb464b/slowapi-0.1.9-py3-none-any.whl", hash = "sha256:cfad116cfb84ad9d763ee155c1e5c5cbf00b0d47399a769b227865f5df576e36", size = 14670, upload-time = "2024-02-05T12:11:50.898Z" }, ] +[[package]] +name = "smmap" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/ea/49c993d6dfdd7338c9b1000a0f36817ed7ec84577ae2e52f890d1a4ff909/smmap-5.0.3.tar.gz", hash = "sha256:4d9debb8b99007ae47165abc08670bd74cb74b5227dda7f643eccc4e9eb5642c", size = 22506, upload-time = "2026-03-09T03:43:26.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, +] + [[package]] name = "sortedcontainers" version = "2.4.0" @@ -4944,6 +5355,15 @@ asyncio = [ { name = "greenlet" }, ] +[[package]] +name = "sqlparse" +version = "0.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/d3/3f06a1006f2261d1342aefb3c71eed02f5d4ca5bdbecd86ebc12ad38306e/sqlparse-0.6.0.tar.gz", hash = "sha256:113c35c75365ab9cc9c7231d68c6428fb11c085fc8e9eb1ad659b7ddbf6cd2b9", size = 178477, upload-time = "2026-08-13T19:16:06.396Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/50/f00935da0ec7cbf325f8dc4f772ae46fbc7b672dd62876e73f0a94adda57/sqlparse-0.6.0-py3-none-any.whl", hash = "sha256:b861c0288ce2fa56209a9a6412d2e066ac664b3873b89c26c9d8415e8e32996f", size = 50070, upload-time = "2026-08-13T19:16:04.062Z" }, +] + [[package]] name = "stack-data" version = "0.6.3" @@ -5398,6 +5818,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4b/a7/ded126c19495158a05c7202b3389139839d4cf78d622d453867778e0f7a8/virtualenv-21.7.1-py3-none-any.whl", hash = "sha256:6394973f990536e34c05157179146c020284c42fe01da1dfeb0ba16c345280d9", size = 5504576, upload-time = "2026-07-30T15:40:34.512Z" }, ] +[[package]] +name = "waitress" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/cb/04ddb054f45faa306a230769e868c28b8065ea196891f09004ebace5b184/waitress-3.0.2.tar.gz", hash = "sha256:682aaaf2af0c44ada4abfb70ded36393f0e307f4ab9456a215ce0020baefc31f", size = 179901, upload-time = "2024-11-16T20:02:35.195Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8d/57/a27182528c90ef38d82b636a11f606b0cbb0e17588ed205435f8affe3368/waitress-3.0.2-py3-none-any.whl", hash = "sha256:c56d67fd6e87c2ee598b76abdd4e96cfad1f24cacdea5078d382b1f9d7b5ed2e", size = 56232, upload-time = "2024-11-16T20:02:33.858Z" }, +] + [[package]] name = "watchfiles" version = "1.1.0" @@ -5532,6 +5961,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743, upload-time = "2025-03-05T20:03:39.41Z" }, ] +[[package]] +name = "werkzeug" +version = "3.1.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/dd/b2/381be8cfdee792dd117872481b6e378f85c957dd7c5bca38897b08f765fd/werkzeug-3.1.8.tar.gz", hash = "sha256:9bad61a4268dac112f1c5cd4630a56ede601b6ed420300677a869083d70a4c44", size = 875852, upload-time = "2026-04-02T18:49:14.268Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/93/8c/2e650f2afeb7ee576912636c23ddb621c91ac6a98e66dc8d29c3c69446e1/werkzeug-3.1.8-py3-none-any.whl", hash = "sha256:63a77fb8892bf28ebc3178683445222aa500e48ebad5ec77b0ad80f8726b1f50", size = 226459, upload-time = "2026-04-02T18:49:12.72Z" }, +] + [[package]] name = "widgetsnbextension" version = "4.0.15" @@ -5698,3 +6139,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/c3/b2e9f38bc3e11191981d57ea08cab2166e74ea770024a646617c9cddd9f6/yarl-1.20.1-cp313-cp313t-win_amd64.whl", hash = "sha256:541d050a355bbbc27e55d906bc91cb6fe42f96c01413dd0f4ed5a5240513874f", size = 93003, upload-time = "2025-06-10T00:45:27.752Z" }, { url = "https://files.pythonhosted.org/packages/b4/2d/2345fce04cfd4bee161bf1e7d9cdc702e3e16109021035dbb24db654a622/yarl-1.20.1-py3-none-any.whl", hash = "sha256:83b8eb083fe4683c6115795d9fc1cfaf2cbbefb19b3a1cb68f6527460f483a77", size = 46542, upload-time = "2025-06-10T00:46:07.521Z" }, ] + +[[package]] +name = "zipp" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b9/d8/eab98a517c14134c0b2eb4e2387bc5f457334293ec5d2dd3857ec2966802/zipp-4.1.0.tar.gz", hash = "sha256:4cb57381f544315db7688e976e922a2b18cdb513d21cc194eb42232ba2a3e602", size = 26214, upload-time = "2026-05-18T20:08:57.967Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3a/13/547360d81e6d88d58492968ffda9f9542854f11310ee556fef14260cc886/zipp-4.1.0-py3-none-any.whl", hash = "sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f", size = 10238, upload-time = "2026-05-18T20:08:57.045Z" }, +] From 673152531a17329e09e79b61eae86554eb1b493b Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 16:21:27 +0300 Subject: [PATCH 23/85] docs: close SM-12 handoff Signed-off-by: flyingriverhorse --- initiatives/spark_and_mlflow/HANDOFF.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 826a6bd21..dfb80cf54 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -7,9 +7,9 @@ Target release: 0.9.0. Branch: `090`. ## Starting point - SM-00 through SM-12 are complete; SM-13 is READY. -- Last implementation commits: `04dbe303` (distributed classification - inference) and `7cdd622c` (nullable Arrow transport and oracle hardening). -- Last guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). +- Last implementation commit: `f8f188ca` (optional MLflow tracking, + dependency metadata, tests and guide). +- Previous guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). From be058e78d8ae1052c3310e7542701ef36d7dd0a7 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 17:42:10 +0300 Subject: [PATCH 24/85] feat(core): add MLflow pyfunc packaging Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 9 +- docs/user_guide/mlflow_models.md | 93 +++++ docs/user_guide/mlflow_tracking.md | 6 +- .../03-mlflow-batch-delivery-plan.md | 71 ++-- initiatives/spark_and_mlflow/HANDOFF.md | 28 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 51 ++- mkdocs.yml | 1 + .../skyulf/integrations/mlflow/model.py | 223 +++++++++++ .../tests/integrations/test_mlflow_model.py | 377 ++++++++++++++++++ 9 files changed, 810 insertions(+), 49 deletions(-) create mode 100644 docs/user_guide/mlflow_models.md create mode 100644 skyulf-core/skyulf/integrations/mlflow/model.py create mode 100644 skyulf-core/tests/integrations/test_mlflow_model.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index de9b2f44d..bcd12bf02 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -6,7 +6,7 @@ For the version index, see root [CHANGELOG.md](../CHANGELOG.md). Target: optional Spark execution and MLflow integration for Skyulf Core. Development version: 0.9.0. This release has not been published; Spark node -execution and MLflow adapters remain under development. +execution, MLflow registry and Databricks delivery remain under development. ### Added @@ -94,12 +94,17 @@ execution and MLflow adapters remain under development. dependency-free disabled mode, explicit client-bound run IDs, FINISHED/FAILED lifecycle, `raise`/`warn` failure policy, and opt-in config artifact digest. Install it with `skyulf-core[mlflow]` or `requirements-mlflow.txt`. +- Optional MLflow `pyfunc` packaging for trusted inference bundles. Explicit + run IDs and client-bound artifact upload preserve run isolation; raw/features + prediction parity, class/threshold metadata, named signatures, synthetic + input examples, and clean wheel/subprocess loading are covered. Registry, + Unity Catalog, Spark UDF and endpoint delivery remain separate gates. ### Planned scope — not yet available - Further native Spark nodes and broader portable-state coverage. - Worker wheel packaging and scale/RSS validation for production Spark clusters. -- Optional MLflow model packaging and Unity Catalog model resolution. +- Unity Catalog model resolution and registry adapters. - Scheduled batch inference with reproducible model versions and Delta outputs. Endpoint integrations and template/Databricks Bundle generation follow the diff --git a/docs/user_guide/mlflow_models.md b/docs/user_guide/mlflow_models.md new file mode 100644 index 000000000..d3241bd11 --- /dev/null +++ b/docs/user_guide/mlflow_models.md @@ -0,0 +1,93 @@ +# MLflow model packaging (development) + +Skyulf can package an existing `InferenceBundle` as an MLflow `pyfunc` model. +The package contains the frozen feature state, estimator payload, manifest, and +runtime requirements already produced by the bundle workflow. It does not fit +again, capture a notebook session, or serialize a Spark session. + +Install the optional dependency only in environments that log or load these +models: + +```bash +uv pip install "skyulf-core[mlflow]" +``` + +`log_model` requires the concrete MLflow run ID. Pass the same tracking URI +used to create a client-bound `track_run` when it is not already configured as +MLflow's process-wide URI: + +```python +import mlflow + +from skyulf.inference.bundle import build_bundle +from skyulf.integrations.mlflow import TrackingConfig, track_run +from skyulf.integrations.mlflow.model import log_model + +bundle = build_bundle( + fitted_pipeline, + input_stage="raw", # use "features" when callers already apply FE + feature_order=("age", "income"), +) +config = TrackingConfig( + enabled=True, + tracking_uri="sqlite:///mlflow.db", + experiment_name="customer-risk", +) + +with track_run(config, run_name="fit-2026-09") as run: + model_uri = log_model( + bundle, + run_id=run.run_id, + artifact_path="skyulf-model", + tracking_uri=config.tracking_uri, + ) + +mlflow.set_tracking_uri(config.tracking_uri) +loaded = mlflow.pyfunc.load_model(model_uri) +predictions = loaded.predict(request_frame) +``` + +The returned URI is `runs://`. Uploading uses an +explicit MLflow client and run ID, so an unrelated fluent active run cannot +receive the artifact. The `raw` bundle path applies the frozen FE state before +prediction; the `features` path validates that the caller supplies the saved +feature schema. Regression outputs and classification labels, class order, +probability columns, and saved threshold decisions remain the bundle's +contract. + +The model signature uses named tabular columns. MLflow may reorder named input +columns and safely cast compatible values before the adapter receives the +`pandas.DataFrame`; undeclared extra columns are ignored by MLflow. Positional +NumPy or list input, and inputs missing a declared column, are rejected. +Bundle dtypes that MLflow cannot represent exactly, such as `int8`, are +rejected during packaging instead of being silently widened. Input examples +are one synthetic row derived from the manifest schema and never a training or +production row. This is MLflow's input transport contract; direct +`predict_local` calls still reject different column orders, extra columns and +dtype mismatches. See [MLflow signature enforcement](https://mlflow.org/docs/latest/model/signatures/). + +The pyfunc entry point accepts named pandas frames (or named inputs that MLflow +can convert). A pipeline trained with Polars can produce the same bundle; +convert a Polars request to pandas explicitly for pyfunc prediction. Supported +bundle input dtypes are `bool`, `int32`, `int64`, `float32`, and `float64`. +String classification outputs are supported; raw string FE inputs remain +outside the existing bundle contract. + +Install the recorded requirements, including the matching Skyulf wheel, before +loading the artifact. The wheel itself is not embedded: for an unpublished +version, distribute the built wheel through your package delivery process. +A worker or subprocess can load it without importing the repository checkout. The +estimator payload is a trusted pickle and must only be loaded from a trusted +producer; checksums detect corruption but do not make pickle deserialization +safe. + +Packaging uses run artifacts, not MLflow 3's separate LoggedModel entity. +Choose a fresh artifact path for each model; uploading the same run/path is +not an atomic publish operation and may overwrite files. Logging failures +propagate to the caller even when tracking was configured with `warn`. +Producer project files and the temporary source bundle path are excluded. + +This stage provides local MLflow pyfunc packaging. Registry and Unity Catalog +resolution, Databricks job delivery, Delta batch sinks, and Spark UDF/endpoint +adapters remain later initiative tasks. Until those gates are complete, +`load_model` plus `predict` is the supported packaging contract. diff --git a/docs/user_guide/mlflow_tracking.md b/docs/user_guide/mlflow_tracking.md index 2d9240ad5..d83c5b56a 100644 --- a/docs/user_guide/mlflow_tracking.md +++ b/docs/user_guide/mlflow_tracking.md @@ -54,6 +54,6 @@ does not write backend job metadata itself. A successful context terminates its own run as `FINISHED`; an exception in the training body terminates it as `FAILED`. -This integration creates tracking metadata only. Model packaging, registry or -Unity Catalog resolution, Delta batch publication, and Databricks deployment -are separate later stages of the 0.9.0 initiative. +This adapter creates tracking metadata. See [MLflow models](mlflow_models.md) +to package a fitted inference bundle in the same run. Registry/Unity Catalog, +Delta batch publication and Databricks deployment remain later stages. diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index 20af4e9b0..788e07a60 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -61,39 +61,45 @@ MLflow 3.16.1 environment passed all 8 tracking tests, including SQLite FINISHED/FAILED lifecycle, concurrent run-ID isolation, caller active-run preservation, explicit config digest/artifact, and warn-mode failure handling. -## SM-13 — MLflow model flavor ve bağımsız yükleme +## SM-13 — MLflow model packaging and independent loading -**Bağımlılık:** SM-12. **Oluştur:** `skyulf/integrations/mlflow/model.py`, +**Dependency:** SM-12. **Files:** `skyulf/integrations/mlflow/model.py`, `tests/integrations/test_mlflow_model.py`. -**Üretir:** `log_model(bundle, *, run_id, artifact_path) -> model_uri`; -`SkyulfPythonModel` pyfunc adapter; `load_context` bundle yükler, -`predict` SM-08 `predict_local` kullanır. - -- [ ] pyfunc save/load sonrası raw/features giriş sözleşmesi, class/threshold, - dtype ve feature order parity testi yaz. NumPy positional girdiye sessiz uyarlama yok. -- [ ] Signature/input example oluştur; küçük sentetik örnek kullan, üretim - verisini model example içine otomatik koyma. Wheel sürümü ve requirements kayıtlı. -- [ ] Model loglama açık run_id kullanır; track_run'ın run nesnesi bu kimliği - sunar. Süreç genelindeki active run durumuna dayanarak başka işe artifact yazma. -- [ ] Temiz subprocess/venv'de modeli yükle; çalışma dizinindeki repo importuna - güvenmediğini doğrula. Notebook closure veya SparkSession pickle etme. -- [ ] G2 runner ile registry URI'den indirilen aynı bundle'ı çalıştır. MLflow - spark_udf kullanılırsa adapter yine aynı prediction sözleşmesini uygulasın; - ikinci ayrı preprocessing implementation yazma. - -```python -def test_pyfunc_matches_bundle(logged_pyfunc, regression_bundle, raw_frame): - """MLflow packaging must not alter the established local prediction semantics.""" - import numpy as np - from skyulf.inference.bundle import predict_local - expected = predict_local(raw_frame, regression_bundle)["prediction"] - actual = logged_pyfunc.predict(raw_frame)["prediction"] - np.testing.assert_allclose(actual, expected, rtol=1e-10, atol=1e-12) -``` - -`logged_pyfunc` fixture geçici local MLflow store'da log_model + load_model yapar. -**Komut:** `python -m pytest skyulf-core/tests/integrations/test_mlflow_model.py -q` -**Kabul:** G3a: MLflow artifact bağımsız Python ortamında doğru tahmin verir. +**API:** `log_model(bundle, *, run_id, artifact_path, tracking_uri=None) -> model_uri`; +`SkyulfPythonModel.load_context` loads the existing bundle and `predict` +delegates to SM-08 `predict_local` after MLflow signature enforcement. + +- [x] Real pyfunc save/load preserves raw/features predictions for pandas and + Polars-trained pipelines, class probabilities, thresholds, index and dtypes. + Named columns reach the estimator in its recorded feature order. +- [x] Record the manifest-derived signature, a synthetic zero-like row, pinned + requirements and wheel version. Never auto-capture production examples, + notebook closures, Spark sessions or the producer's uv project. +- [x] Log through an explicit client/run ID, including when an unrelated fluent + run is active on a different store; preserve that run and global URI. +- [x] Load from a wheel-installed interpreter with Python `-I`, assert import + from site-packages, and compare predictions with the producer's bundle. + +**Transport boundary:** MLflow's named signature may reorder columns, ignore +extras and perform safe casts before the adapter receives the frame. This is +explicitly tested and documented; direct `predict_local` still requires exact +schema/order. Positional arrays/lists and missing names fail. Bundle input +types without an exact MLflow representation (`int8`, `int16`, unsigned ints) +are rejected before contacting a store; bool/int32/int64/float32/float64 work. + +**Validation (2026-09-22, Python 3.12.10, MLflow 3.16.1):** **31 passed** for +tracking and model tests with the wheel subprocess gate enabled (23 model, +8 tracking). Base bundle/schema/integration regression: **80 passed, 7 skipped**; +optional dependencies are absent there. Scoped Ruff, repository Ty/pre-commit +and strict MkDocs checks pass. Exact commands and evidence are in +[OPEN_QUEUE.md](OPEN_QUEUE.md#sm-13--2026-09-22-validation-record). +The isolated consumer environment reused installed dependencies and replaced +editable Skyulf with the final 0.9.0 wheel; this verifies independent imports, +not a fresh network dependency install. Only MLflow 3.16.1 was exercised. + +**Acceptance:** G3a is complete for local pyfunc packaging. The registry-to-G2 +item originally listed here requires SM-14 and is carried forward below; +real Unity Catalog/Databricks evidence stays in SM-16. No Spark UDF was added. ## SM-14 — Registry ve Unity Catalog adapter'ı @@ -105,6 +111,9 @@ URI çözümleme ile eşdeğer sayma, eski metotların return tipi değişmesin. ResolvedModel(name, version, model_uri, signature, digest). `register_model(model_uri, name)` explicit publish işlemidir; tahmin sırasında çağrılmaz. +- [ ] Carry-forward from SM-13: run the G2 Spark runner on the same bundle + downloaded through a concrete registry URI. If an MLflow Spark UDF is added, + reuse the existing prediction contract rather than duplicating FE. - [ ] Alias/version aynı anda verilirse ve ikisi de yoksa açık config hatası; missing model/permission failure ile dependency failure ayrı hatalar olsun. - [ ] Alias'ı bir kez resolve et, concrete version URI'yi bütün iş boyunca taşı. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index dfb80cf54..2aedfb1cf 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,17 +1,17 @@ # Session handoff - 2026-09-22 -SM-11 is complete after the corrective validation gate. SM-12 is now complete; -resume with SM-13. +SM-11 is complete after the corrective validation gate. SM-12 and SM-13 are +now complete; resume with SM-14. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-12 are complete; SM-13 is READY. -- Last implementation commit: `f8f188ca` (optional MLflow tracking, - dependency metadata, tests and guide). +- SM-00 through SM-13 are complete; SM-14 is READY. +- SM-13 starts from `67315253`; its implementation, guide and evidence are in + the delivery commit containing this handoff. - Previous guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and - the SM-11 section of [02-inference-plan.md](02-inference-plan.md) before coding. + the SM-14 section of [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md). - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). ## Confirmed terminology and intended workflow @@ -75,6 +75,16 @@ while an isolated MLflow 3.16.1 environment passed all 8 tracking tests for explicit client-bound lifecycle, concurrency, caller-run preservation, config digest/artifact logging, and warn-mode degradation. -Three pre-existing untracked directories remain outside this change: -`.tmp-review-model/`, `.tmp-spark-review-full/`, `.tmp-spark-review-pytest/`. -Preserve them; do not stage or delete them as part of the next task. +SM-13 added MLflow pyfunc packaging around the immutable inference bundle. +The MLflow 3.16.1 lane passed 31 tests, including a separate Python `-I` +subprocess loading the final 0.9.0 wheel from site-packages. Consumer dependencies +were copied from the isolated MLflow environment; Skyulf was reinstalled from +the wheel. Base bundle/schema/integration tests passed 80 with 7 optional skips. +MLflow aligns named columns and safely casts compatible inputs before bundle +prediction; direct `predict_local` remains strict. Unsupported bundle integer +dtypes fail at packaging. Producer uv files and temporary paths are excluded. +Registry-to-G2 evidence is carried into SM-14; live UC/Databricks, scheduled +batch delivery, endpoints and templates remain later gates. + +Pre-existing `.tmp-*` directories remain outside this change. Preserve them; +do not stage or delete them as part of the next task. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index c31ded5b9..046144f05 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,9 +1,9 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-22. **SM-00–SM-12 tamamlandı; sıradaki SM-13. Hedef: 0.9.0.** +Güncelleme: 2026-09-22. **SM-00–SM-13 tamamlandı; sıradaki SM-14. Hedef: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. -Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-12. +Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-14. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -24,8 +24,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-10 | Worker Python FE + model | SM-09 | DONE | Batch-safe portable FE; window gibi yollar açık ret | | SM-11 | Classification ve ölçek kapısı | SM-10 | DONE | Class/proba/threshold parity; transport, packaging and scale evidence | | SM-12 | Opsiyonel MLflow tracking | SM-11 | DONE | Off bağımsız; gerçek run lifecycle ve izolasyon | -| SM-13 | MLflow model packaging | SM-12 | READY | Temiz ortamda pyfunc yükleme ve parity | -| SM-14 | Registry/Unity Catalog adapter | SM-13 | WAIT | URI/signature; alias → sabit version | +| SM-13 | MLflow model packaging | SM-12 | DONE | Temiz ortamda pyfunc yükleme ve parity | +| SM-14 | Registry/Unity Catalog adapter | SM-13 | READY | URI/signature; alias → sabit version | | SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | | SM-16 | Gerçek Databricks kapısı | SM-15 | WAIT | Job/run kanıtı; UC load; iki inference yolu | | SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | @@ -47,6 +47,49 @@ gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. +## SM-13 — 2026-09-22 validation record + +- Added optional MLflow `pyfunc` packaging in + `skyulf/integrations/mlflow/model.py`. `log_model` serializes the existing + `InferenceBundle`, records a manifest-derived named signature and synthetic + input example, and uploads the model directory to the explicitly supplied + run ID through `MlflowClient`. `tracking_uri` can be passed when the run was + created by a client-bound tracker; no global active run is used to select the + destination. +- Raw and features bundles preserve local prediction results after MLflow + save/load for pandas and Polars-trained pipelines. Classification tests cover + class order, probabilities and tuned thresholds. Positional NumPy/list input + is rejected. Dtypes without an exact MLflow column representation are rejected + during signature creation rather than silently widened. +- Baseline `67315253`; this delivery commit includes implementation, tests, + English guide and validation records. Python 3.12.10 / MLflow 3.16.1: + **31 passed** (23 model, 8 tracking) with the wheel subprocess gate enabled. + Base bundle/schema/integration regression: **80 passed, 7 skipped** with + existing numeric/protocol warnings. Base tracking/model alone: **4 passed, + 5 skipped**; MLflow is absent. Ruff, repository Ty/pre-commit and strict + MkDocs passed. Only MLflow 3.16.1 was exercised. +- The isolated consumer environment reused installed dependencies and replaced + editable Skyulf with the final 0.9.0 wheel. Python `-I` loaded the model from + a temporary working directory, asserted imports from site-packages and + matched producer predictions. This verifies independent package imports, + not a fresh network dependency install. +- MLflow aligns named columns, ignores extras and safely casts compatible + request types before bundle validation; direct `predict_local` still requires + exact names/order/dtypes. This transport boundary has an explicit regression. + Tests also exclude the producer's uv project and temporary source paths and + preserve an unrelated active run on a different tracking store. +- Scope boundary: registry/Unity Catalog resolution, G2 runner evidence, + Databricks jobs, Spark UDF/endpoint adapters and Delta batch publication stay + in SM-14–SM-16. SM-14 is now the next task. + +Reproducible verification (consumer Python must contain the final built wheel): + +```powershell +$env:SKYULF_MLFLOW_WHEEL_PYTHON = (Resolve-Path .cache/sm13-clean-env/Scripts/python.exe).Path +.cache/sm12-mlflow-env/Scripts/python.exe -m pytest skyulf-core/tests/integrations/test_mlflow_tracking.py skyulf-core/tests/integrations/test_mlflow_model.py -q -o addopts= --basetemp .cache/sm13-delivery --tb=short +.venv/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_inference_bundle.py skyulf-core/tests/unit/test_pipeline_inference_schema.py skyulf-core/tests/integrations -q -o addopts= --basetemp .cache/sm13-base-regression --tb=short +``` + ## SM-12 — 2026-09-22 validation record - Added the optional `skyulf.integrations.mlflow` adapter, the `mlflow` package diff --git a/mkdocs.yml b/mkdocs.yml index 3dbe9dba6..490ce7e0e 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -77,6 +77,7 @@ nav: - Inference Bundles (Development): user_guide/inference_bundles.md - Inference Flow (Development): user_guide/inference_flow.md - MLflow Tracking (Development): user_guide/mlflow_tracking.md + - MLflow Models (Development): user_guide/mlflow_models.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/skyulf-core/skyulf/integrations/mlflow/model.py b/skyulf-core/skyulf/integrations/mlflow/model.py new file mode 100644 index 000000000..56f7ff362 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/model.py @@ -0,0 +1,223 @@ +"""MLflow pyfunc packaging for trusted Skyulf inference bundles. + +This module is optional. Importing ``skyulf.integrations.mlflow`` does not load +it; callers must install the ``mlflow`` extra before importing this module. +The adapter transports the existing bundle directory and delegates prediction +to :func:`skyulf.inference.bundle.predict_local`. +""" + +from __future__ import annotations + +import inspect +import tempfile +from pathlib import Path +from typing import Any + +import mlflow # ty: ignore[unresolved-import] +import pandas as pd + +from ...inference.bundle import InferenceBundle, load_bundle, predict_local, save_bundle + + +class SkyulfPythonModel(mlflow.pyfunc.PythonModel): + """Load one immutable bundle artifact and reuse its local prediction contract.""" + + def __init__(self) -> None: + """Create an unloaded adapter; MLflow supplies the artifact context later.""" + self._bundle: InferenceBundle | None = None + + def load_context(self, context: Any) -> None: + """Load and validate the transported bundle from MLflow's artifact context.""" + try: + bundle_path = context.artifacts["bundle"] + except (AttributeError, KeyError) as exc: + raise ValueError("MLflow model is missing the Skyulf bundle artifact.") from exc + self._bundle = load_bundle(Path(bundle_path)) + + def predict( + self, context: Any, model_input: pd.DataFrame, params: dict[str, Any] | None = None + ) -> pd.DataFrame: + """Predict after MLflow normalizes named columns against the saved signature.""" + del context, params + if self._bundle is None: + raise RuntimeError("SkyulfPythonModel.load_context() was not called.") + if not isinstance(model_input, pd.DataFrame): + raise TypeError( + "SkyulfPythonModel requires a pandas DataFrame with named columns; " + "positional NumPy input is unsupported." + ) + return predict_local(model_input, self._bundle) + + +def log_model( + bundle: InferenceBundle, + *, + run_id: str | None, + artifact_path: str, + tracking_uri: str | None = None, +) -> str: + """Log a bundle as an MLflow pyfunc model under the explicit run ID. + + The bundle is first written to a bounded temporary directory and passed as + an MLflow artifact. The serialized pyfunc directory is then uploaded with + an explicit ``MlflowClient`` and ``run_id``; the caller's process-global + active run is never used to select the destination. ``tracking_uri`` is + optional when the process-wide MLflow URI is already configured, but should + be supplied when the run was created by a client-bound ``track_run``. + """ + run_id = _validate_arguments(bundle, run_id, artifact_path, tracking_uri) + signature = _signature(bundle) + client = _make_client(tracking_uri) + client.get_run(run_id) + with tempfile.TemporaryDirectory(prefix="skyulf-mlflow-") as directory: + bundle_path = Path(directory) / "bundle" + model_path = Path(directory) / "model" + save_bundle(bundle, bundle_path) + # Newer MLflow versions auto-copy the caller's uv project by default. + # An explicit empty project directory keeps packaging independent of + # the producer's cwd, without changing process-global settings. + save_options: dict[str, Any] = {} + if "uv_project_path" in inspect.signature(mlflow.pyfunc.save_model).parameters: + save_options["uv_project_path"] = directory + mlflow.pyfunc.save_model( + path=str(model_path), + python_model=SkyulfPythonModel(), + artifacts={"bundle": str(bundle_path)}, + signature=signature, + input_example=_input_example(bundle), + pip_requirements=_pip_requirements(bundle), + metadata=_metadata(bundle), + mlflow_model=mlflow.models.Model(run_id=run_id, artifact_path=artifact_path), + **save_options, + ) + _scrub_local_artifact_uri(model_path) + client.log_artifacts(run_id, str(model_path), artifact_path=artifact_path) + return f"runs:/{run_id}/{artifact_path}" + + +def _validate_arguments( + bundle: InferenceBundle, + run_id: str | None, + artifact_path: str, + tracking_uri: str | None, +) -> str: + """Reject missing bundle identity before serializing or contacting MLflow.""" + if not isinstance(bundle, InferenceBundle): + raise TypeError("bundle must be an InferenceBundle.") + if type(run_id) is not str or not run_id.strip(): + raise ValueError("run_id must be a non-empty string.") + if type(artifact_path) is not str or not artifact_path.strip(): + raise ValueError("artifact_path must be a non-empty string.") + if any(reserved in artifact_path for reserved in ("#", "?")): + raise ValueError("artifact_path cannot contain '#' or '?' because they are URI delimiters.") + if tracking_uri is not None and (type(tracking_uri) is not str or not tracking_uri.strip()): + raise ValueError("tracking_uri must be a non-empty string or None.") + return run_id + + +def _make_client(tracking_uri: str | None) -> Any: + """Construct the MLflow client used to validate and upload one run artifact.""" + from mlflow import ( # noqa: PLC0415 - optional module boundary # ty: ignore[unresolved-import] + MlflowClient, + ) + + return MlflowClient(tracking_uri=tracking_uri) + + +def _scrub_local_artifact_uri(model_path: Path) -> None: + """Remove the temporary producer path from the portable MLflow metadata.""" + model = mlflow.models.Model.load(str(model_path)) + flavor = model.flavors[mlflow.pyfunc.FLAVOR_NAME] + artifacts = flavor.get("artifacts", {}) + bundle_artifact = artifacts.get("bundle") + if isinstance(bundle_artifact, dict) and "uri" in bundle_artifact: + bundle_artifact["uri"] = "bundle" + model.save(str(model_path / "MLmodel")) + + +def _metadata(bundle: InferenceBundle) -> dict[str, str]: + """Record contract identity without copying rows, credentials or sessions.""" + return { + "skyulf_bundle_digest": bundle.semantic_digest, + "skyulf_input_stage": bundle.input_stage, + "skyulf_task": bundle.manifest.task, + "skyulf_feature_order": ",".join(bundle.feature_order), + } + + +def _pip_requirements(bundle: InferenceBundle) -> list[str]: + """Pin the bundle runtime and the MLflow flavor used to load this model.""" + requirements = [ + f"{name}=={value}" for name, value in bundle.manifest.requirements if name != "python" + ] + requirements.append(f"mlflow=={mlflow.__version__}") + return requirements + + +def _input_example(bundle: InferenceBundle) -> pd.DataFrame: + """Build one synthetic typed row from the manifest, never from training data.""" + return pd.DataFrame( + { + column.name: pd.Series([_example_value(column.dtype)], dtype=column.dtype) + for column in bundle.manifest.input_schema + } + ) + + +def _example_value(dtype: str) -> bool | int | float: + """Return a safe zero-like scalar for an input schema dtype.""" + if dtype == "bool": + return False + if dtype.startswith(("int", "uint")): + return 0 + if dtype.startswith("float"): + return 0.0 + raise ValueError(f"Unsupported bundle input dtype: {dtype}.") + + +def _signature(bundle: InferenceBundle) -> Any: + """Create an explicit MLflow tabular signature from the frozen bundle schema.""" + from mlflow.models import ( # noqa: PLC0415 - optional module boundary # ty: ignore[unresolved-import] + ModelSignature, + ) + from mlflow.types import ( # noqa: PLC0415 - optional module boundary # ty: ignore[unresolved-import] + ColSpec, + Schema, + ) + + inputs = Schema( + [ + ColSpec(_mlflow_dtype(column.dtype), name=column.name) + for column in bundle.manifest.input_schema + ] + ) + outputs = Schema( + [ + ColSpec(_mlflow_dtype(column.dtype), name=column.name) + for column in bundle.manifest.output_schema + ] + ) + return ModelSignature(inputs=inputs, outputs=outputs) + + +def _mlflow_dtype(dtype: str) -> Any: + """Map the bundle's primitive dtype vocabulary to MLflow tabular types.""" + from mlflow.types import ( # noqa: PLC0415 - optional module boundary # ty: ignore[unresolved-import] + DataType, + ) + + mapping = { + "bool": DataType.boolean, + "int32": DataType.integer, + "int64": DataType.long, + "float32": DataType.float, + "float64": DataType.double, + "string": DataType.string, + } + try: + return mapping[dtype] + except KeyError as exc: + raise ValueError( + "MLflow column signatures cannot preserve this bundle dtype exactly: " + f"{dtype}. Use int32/int64, float32/float64, bool or string." + ) from exc diff --git a/skyulf-core/tests/integrations/test_mlflow_model.py b/skyulf-core/tests/integrations/test_mlflow_model.py new file mode 100644 index 000000000..bee81c486 --- /dev/null +++ b/skyulf-core/tests/integrations/test_mlflow_model.py @@ -0,0 +1,377 @@ +"""Contract tests for the optional MLflow pyfunc bundle adapter.""" + +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path + +import numpy as np +import pandas as pd +import polars as pl +import pytest +from sklearn.metrics import accuracy_score + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle, predict_local +from skyulf.integrations.mlflow import tracking +from skyulf.pipeline import SkyulfPipeline + +mlflow = pytest.importorskip("mlflow") +from skyulf.integrations.mlflow.model import log_model # noqa: E402 +from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run # noqa: E402 + + +@pytest.fixture(autouse=True) +def restore_tracking_uri(): + """MLflow configuration from one test must not leak into the next test.""" + previous = mlflow.get_tracking_uri() + try: + yield + finally: + mlflow.set_tracking_uri(previous) + + +def _regression_pipeline(engine: str) -> tuple[SkyulfPipeline, pd.DataFrame]: + """Fit the same small regression pipeline through pandas or Polars.""" + rng = np.random.default_rng(17) + frame = pd.DataFrame({"x": rng.normal(100, 20, 40), "z": rng.normal(5, 2, 40)}) + frame["target"] = 2 * frame.x - 3 * frame.z + 7 + pipeline = SkyulfPipeline( + { + "preprocessing": [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["x", "z"]}, + }, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": ["x", "z"]}, + }, + ], + "modeling": {"type": "linear_regression"}, + } + ) + data = pl.from_pandas(frame) if engine == "polars" else frame + pipeline.fit(SplitDataset(train=data, test=data.head(0)), target_column="target") + query = pd.DataFrame({"x": [150.0, 80.0], "z": [9.0, 3.0]}, index=[17, 4]) + return pipeline, query + + +def _classification_pipeline() -> tuple[SkyulfPipeline, pd.DataFrame]: + """Fit a binary string-label pipeline with a non-default threshold.""" + train = pd.DataFrame( + { + "x": [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0], + "label": ["no", "no", "no", "yes", "yes", "yes"], + } + ) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="label") + query = pd.DataFrame({"x": [-2.5, -0.25, 0.25, 2.5]}) + pipeline.optimize_thresholds( + query, + np.array(["no", "yes", "yes", "yes"]), + accuracy_score, + grid_points=5, + ) + return pipeline, query + + +def _config(tmp_path: Path, name: str) -> TrackingConfig: + """Create an isolated SQLite tracking configuration for one test.""" + db_path = (tmp_path / f"{name}.db").resolve() + return TrackingConfig( + enabled=True, + tracking_uri=f"sqlite:///{db_path.as_posix()}", + experiment_name=name, + ) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize("stage", ["raw", "features"]) +def test_pyfunc_save_load_matches_bundle( + engine: str, stage: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """MLflow save/load must preserve raw/features local regression predictions.""" + monkeypatch.chdir(tmp_path) + pipeline, raw = _regression_pipeline(engine) + bundle = build_bundle(pipeline, input_stage=stage, feature_order=("x", "z")) + query = raw if stage == "raw" else pipeline.feature_engineer.transform(raw) + expected = predict_local(query, bundle) + config = _config(tmp_path, f"regression-{engine}-{stage}") + + with track_run(config, run_name="package-regression") as run: + model_uri = log_model( + bundle, + run_id=run.run_id, + artifact_path="skyulf-model", + tracking_uri=config.tracking_uri, + ) + + mlflow.set_tracking_uri(config.tracking_uri) + loaded = mlflow.pyfunc.load_model(model_uri) + actual = loaded.predict(query) + pd.testing.assert_frame_equal(actual, expected, check_dtype=True) + assert loaded.metadata.signature is not None + mlmodel_path = mlflow.artifacts.download_artifacts( + f"{model_uri}/MLmodel", dst_path=str(tmp_path / "download") + ) + mlmodel_text = Path(mlmodel_path).read_text(encoding="utf-8") + assert "uri: bundle" in mlmodel_text + assert "skyulf-mlflow-" not in mlmodel_text + assert str(tmp_path) not in mlmodel_text + + +def test_pyfunc_preserves_class_order_and_threshold( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Pyfunc classification must retain classes, probabilities, and saved threshold decisions.""" + monkeypatch.chdir(tmp_path) + pipeline, query = _classification_pipeline() + bundle = build_bundle( + pipeline, + input_stage="raw", + feature_order=("x",), + use_tuned_thresholds=True, + ) + expected = predict_local(query, bundle).reset_index(drop=True) + config = _config(tmp_path, "classification") + + with track_run(config, run_name="package-classification") as run: + model_uri = log_model( + bundle, + run_id=run.run_id, + artifact_path="skyulf-model", + tracking_uri=config.tracking_uri, + ) + + mlflow.set_tracking_uri(config.tracking_uri) + loaded = mlflow.pyfunc.load_model(model_uri) + actual = loaded.predict(query).reset_index(drop=True) + pd.testing.assert_frame_equal(actual, expected, check_dtype=True) + assert list(actual.columns) == ["prediction", *bundle.probability_columns] + assert bundle.classes == ("no", "yes") + assert bundle.manifest.thresholds.values != (0.5, 0.5) + + +def test_log_model_uses_requested_run_with_unrelated_active_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Explicit client upload must leave an unrelated fluent run without model artifacts.""" + monkeypatch.chdir(tmp_path) + pipeline, query = _regression_pipeline("pandas") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + config = _config(tmp_path, "explicit-target") + caller_config = _config(tmp_path, "caller-store") + mlflow.set_tracking_uri(caller_config.tracking_uri) + caller_client = mlflow.MlflowClient(tracking_uri=caller_config.tracking_uri) + caller_experiment = caller_client.create_experiment("caller") + client = tracking._make_client(config.tracking_uri) + + with ( + mlflow.start_run(experiment_id=caller_experiment, run_name="caller") as caller, + track_run(config, run_name="target") as target, + ): + model_uri = log_model( + bundle, + run_id=target.run_id, + artifact_path="skyulf-model", + tracking_uri=config.tracking_uri, + ) + assert mlflow.active_run().info.run_id == caller.info.run_id + assert mlflow.get_tracking_uri() == caller_config.tracking_uri + target_artifacts = {item.path for item in client.list_artifacts(target.run_id)} + caller_artifacts = {item.path for item in caller_client.list_artifacts(caller.info.run_id)} + + assert model_uri == f"runs:/{target.run_id}/skyulf-model" + assert "skyulf-model" in target_artifacts + assert "skyulf-model" not in caller_artifacts + mlflow.set_tracking_uri(config.tracking_uri) + pd.testing.assert_frame_equal( + mlflow.pyfunc.load_model(model_uri).predict(query).reset_index(drop=True), + predict_local(query, bundle).reset_index(drop=True), + check_dtype=True, + ) + + +def test_pyfunc_aligns_by_name_and_rejects_positional_or_missing_input( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """MLflow transport aligns names while the estimator always sees the saved feature order.""" + monkeypatch.chdir(tmp_path) + pipeline, query = _regression_pipeline("pandas") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + config = _config(tmp_path, "order-contract") + + with track_run(config, run_name="package-order") as run: + model_uri = log_model( + bundle, + run_id=run.run_id, + artifact_path="skyulf-model", + tracking_uri=config.tracking_uri, + ) + + mlflow.set_tracking_uri(config.tracking_uri) + loaded = mlflow.pyfunc.load_model(model_uri) + expected = predict_local(query, bundle) + pd.testing.assert_frame_equal(loaded.predict(query[["z", "x"]]), expected) + pd.testing.assert_frame_equal(loaded.predict(query.assign(unused_id=123)), expected) + pd.testing.assert_frame_equal(loaded.predict(query.astype("int32")), expected) + for invalid in (query.to_numpy(), query.to_numpy().tolist(), query.drop(columns="x")): + with pytest.raises(mlflow.exceptions.MlflowException, match="missing inputs"): + loaded.predict(invalid) + with pytest.raises(ValueError, match="order"): + predict_local(query[["z", "x"]], bundle) + + +def test_log_model_requires_explicit_run_id() -> None: + """Packaging must associate the model with the requested run instead of an active caller run.""" + pipeline, _ = _regression_pipeline("pandas") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + with pytest.raises(ValueError, match="run_id"): + log_model(bundle, run_id=None, artifact_path="skyulf-model") + + +@pytest.mark.parametrize("artifact_path", ["model#candidate", "model?candidate"]) +def test_log_model_rejects_uri_delimiters( + artifact_path: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Artifact paths must remain unambiguous when embedded in a runs URI.""" + pipeline, _ = _regression_pipeline("pandas") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + monkeypatch.setattr( + "skyulf.integrations.mlflow.model._make_client", + lambda *args, **kwargs: pytest.fail("invalid artifact path contacted MLflow"), + ) + with pytest.raises(ValueError, match="URI delimiters"): + log_model(bundle, run_id="run-id", artifact_path=artifact_path) + + +@pytest.mark.parametrize("dtype", ["int8", "int16", "uint8", "uint16", "uint32", "uint64"]) +def test_signature_rejects_dtypes_mlflow_cannot_preserve( + dtype: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Packaging must fail rather than silently widen unsupported integer inputs.""" + train = pd.DataFrame({"x": np.arange(6, dtype=dtype), "target": [0.0] * 6}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="target") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + + def forbidden_client(*args: object, **kwargs: object) -> object: + raise AssertionError("unsupported dtype must fail before contacting MLflow") + + monkeypatch.setattr("skyulf.integrations.mlflow.model._make_client", forbidden_client) + with pytest.raises(ValueError, match="preserve this bundle dtype exactly"): + log_model(bundle, run_id="never-contact-store", artifact_path="model") + + +@pytest.mark.parametrize("dtype", ["bool", "int32", "int64", "float32", "float64"]) +def test_pyfunc_preserves_supported_dtypes( + dtype: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each supported MLflow scalar type must remain usable after a real save/load.""" + monkeypatch.chdir(tmp_path) + train = pd.DataFrame({"x": pd.Series([0, 1, 0, 1, 0, 1], dtype=dtype), "y": [0.0, 2.0] * 3}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + query = train[["x"]] + config = _config(tmp_path, "types") + with track_run(config, run_name=dtype) as run: + uri = log_model( + bundle, run_id=run.run_id, artifact_path="model", tracking_uri=config.tracking_uri + ) + mlflow.set_tracking_uri(config.tracking_uri) + pd.testing.assert_frame_equal( + mlflow.pyfunc.load_model(uri).predict(query), predict_local(query, bundle) + ) + + +def test_package_excludes_producer_project_and_records_synthetic_example( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Packaging must not auto-capture the producer's project files or real input rows.""" + monkeypatch.chdir(tmp_path) + (tmp_path / "uv.lock").write_text("version = 1\n", encoding="utf-8") + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "producer-private"\n', encoding="utf-8" + ) + pipeline, _ = _regression_pipeline("pandas") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + config = _config(tmp_path, "privacy") + with track_run(config, run_name="package") as run: + uri = log_model( + bundle, run_id=run.run_id, artifact_path="model", tracking_uri=config.tracking_uri + ) + path = Path( + mlflow.artifacts.download_artifacts( + uri, tracking_uri=config.tracking_uri, dst_path=str(tmp_path / "download") + ) + ) + assert not (path / "uv.lock").exists() + assert not (path / "pyproject.toml").exists() + example = json.loads((path / "input_example.json").read_text(encoding="utf-8")) + assert example["columns"] == ["x", "z"] + assert example["data"] == [[0.0, 0.0]] + requirements = (path / "requirements.txt").read_text(encoding="utf-8") + for package, version in bundle.manifest.requirements: + if package != "python": + assert f"{package}=={version}" in requirements + assert f"mlflow=={mlflow.__version__}" in requirements + + +@pytest.mark.skipif( + not os.environ.get("SKYULF_MLFLOW_WHEEL_PYTHON"), reason="Requires wheel-installed Python" +) +def test_wheel_subprocess_loads_bundle_without_checkout( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A separate wheel-installed interpreter must load and score the uploaded artifact in isolation.""" + monkeypatch.chdir(tmp_path) + pipeline, query = _regression_pipeline("polars") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x", "z")) + config = _config(tmp_path, "wheel") + with track_run(config, run_name="package-wheel") as run: + uri = log_model( + bundle, run_id=run.run_id, artifact_path="model", tracking_uri=config.tracking_uri + ) + script = """ +import sys +import sysconfig +from pathlib import Path +import mlflow +import pandas as pd +import skyulf +assert Path(skyulf.__file__).resolve().is_relative_to(Path(sysconfig.get_path("purelib")).resolve()) +mlflow.set_tracking_uri(sys.argv[1]) +query = pd.DataFrame({"x": [150.0, 80.0], "z": [9.0, 3.0]}, index=[17, 4]) +mlflow.pyfunc.load_model(sys.argv[2]).predict(query).to_json(sys.argv[3], orient="split") +""" + output = tmp_path / "predictions.json" + wheel_python = os.environ.get("SKYULF_MLFLOW_WHEEL_PYTHON") + assert wheel_python is not None + tracking_uri = config.tracking_uri + assert tracking_uri is not None + completed = subprocess.run( + [ + wheel_python, + "-I", + "-c", + script, + tracking_uri, + uri, + str(output), + ], + cwd=tmp_path, + check=False, + capture_output=True, + text=True, + timeout=90, + ) + assert completed.returncode == 0, completed.stdout + completed.stderr + actual = pd.read_json(output, orient="split", dtype={"prediction": "float64"}) + pd.testing.assert_frame_equal(actual, predict_local(query, bundle)) From 4a613cb534f2f44207c464e5beb73c1c2725c4b0 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 18:47:33 +0300 Subject: [PATCH 25/85] feat(core): add MLflow registry adapter Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 + docs/user_guide/mlflow_models.md | 9 +- docs/user_guide/mlflow_registry.md | 71 ++++++ .../03-mlflow-batch-delivery-plan.md | 23 +- initiatives/spark_and_mlflow/HANDOFF.md | 17 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 22 +- mkdocs.yml | 1 + .../skyulf/integrations/mlflow/registry.py | 224 ++++++++++++++++++ .../integrations/test_mlflow_registry.py | 207 ++++++++++++++++ 9 files changed, 563 insertions(+), 16 deletions(-) create mode 100644 docs/user_guide/mlflow_registry.md create mode 100644 skyulf-core/skyulf/integrations/mlflow/registry.py create mode 100644 skyulf-core/tests/integrations/test_mlflow_registry.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index bcd12bf02..417b334b9 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -99,6 +99,11 @@ execution, MLflow registry and Databricks delivery remain under development. prediction parity, class/threshold metadata, named signatures, synthetic input examples, and clean wheel/subprocess loading are covered. Registry, Unity Catalog, Spark UDF and endpoint delivery remain separate gates. +- Optional MLflow registry adapter with explicit run-artifact publication and + alias-or-version resolution. Alias selection is pinned to a concrete version + URI, signatures and bundle digests are exposed, tracking and registry stores + may be separate, and missing/access/dependency failures are typed. Live Unity + Catalog and Databricks validation remain in SM-16. ### Planned scope — not yet available diff --git a/docs/user_guide/mlflow_models.md b/docs/user_guide/mlflow_models.md index d3241bd11..fe46ce80c 100644 --- a/docs/user_guide/mlflow_models.md +++ b/docs/user_guide/mlflow_models.md @@ -87,7 +87,8 @@ not an atomic publish operation and may overwrite files. Logging failures propagate to the caller even when tracking was configured with `warn`. Producer project files and the temporary source bundle path are excluded. -This stage provides local MLflow pyfunc packaging. Registry and Unity Catalog -resolution, Databricks job delivery, Delta batch sinks, and Spark UDF/endpoint -adapters remain later initiative tasks. Until those gates are complete, -`load_model` plus `predict` is the supported packaging contract. +This stage provides local MLflow pyfunc packaging. The optional registry adapter +can now publish and resolve concrete local registry versions; live Unity Catalog, +Databricks job delivery, Delta batch sinks, and Spark UDF/endpoint adapters +remain later initiative tasks. Until those platform gates are complete, +`load_model` plus `predict` is the supported pyfunc packaging contract. diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md new file mode 100644 index 000000000..0e3ff4bc0 --- /dev/null +++ b/docs/user_guide/mlflow_registry.md @@ -0,0 +1,71 @@ +# MLflow model registry (development) + +Skyulf keeps model publication and model selection as explicit operations. The +registry adapter is optional: importing the core package does not import MLflow, +open a client, or contact a registry. + +Install the integration in the environment that publishes or resolves models: + +```bash +uv pip install "skyulf-core[mlflow]" +``` + +`register_model` publishes a model already logged by `log_model` as a new +registered-model version. It accepts a `runs://` URI and +returns MLflow's model-version object. Registration never assigns an alias: +promotion is a separate operation owned by the caller. + +```python +from skyulf.integrations.mlflow.model import log_model +from skyulf.integrations.mlflow.registry import register_model + +model_uri = log_model( + bundle, + run_id=run_id, + artifact_path="model", + tracking_uri="sqlite:///tracking.db", +) +version = register_model( + model_uri, + "customer_risk", + tracking_uri="sqlite:///tracking.db", + registry_uri="sqlite:///registry.db", +) +print(version.version) +``` + +Resolve exactly one selector at the start of a job. An alias is looked up once; +the returned object carries the concrete version URI, so a later alias move does +not change the model used by the running job. + +```python +from skyulf.integrations.mlflow.registry import resolve_model + +resolved = resolve_model( + "customer_risk", + alias="champion", + tracking_uri="sqlite:///tracking.db", + registry_uri="sqlite:///registry.db", +) +assert resolved.model_uri == f"models:/{resolved.name}/{resolved.version}" + +# The versioned URI can be carried into a Spark batch or another runner. +print(resolved.signature, resolved.digest) +``` + +Passing both `alias` and `version`, or neither, is a configuration error. The +adapter reports missing models, access failures, and missing MLflow as separate +exception types so a runner can choose the right remediation. The `signature` +and `digest` fields are read from the packaged MLflow model metadata; they are +validation data, not a second feature-engineering implementation. + +For Unity Catalog, pass a three-part model name (`catalog.schema.model`) and a +`databricks-uc` registry URI. Tracking and registry URIs remain separate. The +local tests cover this configuration validation and separate local stores; a +live Databricks/Unity Catalog connection is deliberately reserved for the SM-16 +platform gate. + +Registry resolution does not run prediction, mutate aliases, start Spark, or +write a table. A later Spark runner downloads the concrete model artifact and +uses the existing inference-bundle contract. HTTP/SQL endpoints, scheduled +Delta delivery, and Databricks Bundle generation remain later initiative tasks. diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index 788e07a60..924ef9f26 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -114,13 +114,13 @@ ResolvedModel(name, version, model_uri, signature, digest). - [ ] Carry-forward from SM-13: run the G2 Spark runner on the same bundle downloaded through a concrete registry URI. If an MLflow Spark UDF is added, reuse the existing prediction contract rather than duplicating FE. -- [ ] Alias/version aynı anda verilirse ve ikisi de yoksa açık config hatası; +- [x] Alias/version aynı anda verilirse ve ikisi de yoksa açık config hatası; missing model/permission failure ile dependency failure ayrı hatalar olsun. -- [ ] Alias'ı bir kez resolve et, concrete version URI'yi bütün iş boyunca taşı. - İlk local registry store testleri, sonra UC integration fixture'ı. -- [ ] UC için üç parçalı model ismi, signature ve ayrı registry URI doğrula; - local client'tan erişim de test senaryosuna dahil olsun. -- [ ] Alias değiştirme otomatik başarı yan etkisi olmasın; model kaydı ve +- [x] Resolve an alias once and carry the concrete version URI through the job. + Local registry tests are complete; the live UC integration fixture remains in SM-16. +- [x] Validate the UC three-part model name, signature and separate registry URI + with a local client; live UC access remains in the SM-16 platform gate. +- [x] Alias değiştirme otomatik başarı yan etkisi olmasın; model kaydı ve promotion ayrı explicit operasyonlar olsun. Testten sonra yalnız test-owned kaynaklar temizlenir; var olan alias değiştirilmez. @@ -136,6 +136,17 @@ def test_registry_rejects_ambiguous_reference(): **Komut:** `python -m pytest skyulf-core/tests/integrations/test_mlflow_registry.py -q` **Kabul:** G3b: local registry gerçek test; UC smoke için SM-16 platform kanıtı gerekir. +**Validation record (2026-09-22):** `register_model` publishes only +`runs:/...` artifacts through an explicit MLflow client and does not assign an +alias. `resolve_model` requires exactly one alias or version, resolves aliases +once, downloads the version's recorded source URI, and returns the concrete +`models:/name/version` URI with the packaged signature and bundle digest. Local +SQLite tests cover missing-model, permission, dependency, separate +tracking/registry stores, alias movement, and Unity Catalog three-part-name +validation. MLflow 3.16.1 isolated lane: **10 passed**. Base environment: +registry module skipped because MLflow is absent. Live Unity Catalog and Spark +runner validation remain SM-16 carry-forward items. + ## SM-15 — Aylık batch ve Delta yayınlama **Bağımlılık:** SM-14. **Oluştur:** diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 2aedfb1cf..04b482d48 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,17 +1,17 @@ # Session handoff - 2026-09-22 -SM-11 is complete after the corrective validation gate. SM-12 and SM-13 are -now complete; resume with SM-14. +SM-11 is complete after the corrective validation gate. SM-12, SM-13 and SM-14 +are now complete; resume with SM-15. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-13 are complete; SM-14 is READY. +- SM-00 through SM-14 are complete; SM-15 is READY. - SM-13 starts from `67315253`; its implementation, guide and evidence are in the delivery commit containing this handoff. - Previous guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and - the SM-14 section of [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md). + the SM-15 section of [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md). - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). ## Confirmed terminology and intended workflow @@ -86,5 +86,14 @@ dtypes fail at packaging. Producer uv files and temporary paths are excluded. Registry-to-G2 evidence is carried into SM-14; live UC/Databricks, scheduled batch delivery, endpoints and templates remain later gates. +SM-14 added explicit MLflow registry publication and resolution. The adapter +publishes only `runs:/...` artifacts, leaves alias promotion explicit, resolves +an alias once to a concrete `models:/name/version` URI, and returns the packaged +signature and bundle digest. MLflow 3.16.1 local validation passed 10 tests, +including separate tracking/registry stores, missing/access/dependency failures, +alias movement and Unity Catalog name validation. Live UC and Databricks +validation remain SM-16; the G2 Spark runner consumes this concrete artifact in +that later platform gate. + Pre-existing `.tmp-*` directories remain outside this change. Preserve them; do not stage or delete them as part of the next task. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 046144f05..221fc3190 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -25,8 +25,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-11 | Classification ve ölçek kapısı | SM-10 | DONE | Class/proba/threshold parity; transport, packaging and scale evidence | | SM-12 | Opsiyonel MLflow tracking | SM-11 | DONE | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | DONE | Temiz ortamda pyfunc yükleme ve parity | -| SM-14 | Registry/Unity Catalog adapter | SM-13 | READY | URI/signature; alias → sabit version | -| SM-15 | Aylık batch + Delta sink | SM-14 | WAIT | Dönem izolasyonu, retry ve conflict kontrolü | +| SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | +| SM-15 | Monthly batch + Delta sink | SM-14 | READY | Period isolation, retry and conflict control | | SM-16 | Gerçek Databricks kapısı | SM-15 | WAIT | Job/run kanıtı; UC load; iki inference yolu | | SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | | SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | @@ -112,6 +112,24 @@ $env:SKYULF_MLFLOW_WHEEL_PYTHON = (Resolve-Path .cache/sm13-clean-env/Scripts/py registry/Unity Catalog, Databricks batch delivery, endpoints, and templates remain SM-13 onward. +## SM-14 — 2026-09-22 validation record + +- Added `skyulf/integrations/mlflow/registry.py` and + `tests/integrations/test_mlflow_registry.py`. Publication accepts only the + `runs:/...` URI produced by the packaging adapter, uses explicit tracking and + registry clients, and leaves alias promotion to the caller. +- Resolution requires exactly one alias or version, pins an alias to a concrete + `models:/name/version` URI, and returns the packaged signature and bundle + digest. The version's recorded source URI is used for artifact metadata so + separate tracking and registry stores work without process-global MLflow state. +- The isolated MLflow 3.16.1 lane passed **10 tests**. It covers local SQLite + registration, alias movement, separate stores, missing model, access and + dependency failures, non-run publication rejection, and Unity Catalog + three-part-name validation. The base environment skips the optional module + because MLflow is absent. +- Scope boundary: live Unity Catalog/Databricks validation and the G2 Spark + runner remain SM-16 carry-forward work. SM-15 is now READY. + ## Bir görevi kapatma kaydı Her DONE satırına aynı dosyada aşağıdaki bilgileri içeren tarihli kayıt ekle: diff --git a/mkdocs.yml b/mkdocs.yml index 490ce7e0e..caa35de30 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -78,6 +78,7 @@ nav: - Inference Flow (Development): user_guide/inference_flow.md - MLflow Tracking (Development): user_guide/mlflow_tracking.md - MLflow Models (Development): user_guide/mlflow_models.md + - MLflow Registry (Development): user_guide/mlflow_registry.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py new file mode 100644 index 000000000..a0e55c569 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -0,0 +1,224 @@ +"""Explicit MLflow model registry publication and version resolution. + +The adapter keeps registry selection separate from prediction. Callers publish +an already logged model explicitly, resolve an alias or version once, and carry +the resulting concrete ``models:/.../`` URI through the rest of a job. +MLflow remains an optional dependency and is imported only when an operation is +requested. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +__all__ = [ + "RegistryAccessError", + "RegistryDependencyError", + "RegistryError", + "RegistryModelNotFoundError", + "RegistryOperationError", + "ResolvedModel", + "register_model", + "resolve_model", +] + + +class RegistryError(RuntimeError): + """Base class for typed MLflow registry failures.""" + + +class RegistryDependencyError(RegistryError): + """The optional MLflow package is unavailable in the current environment.""" + + +class RegistryModelNotFoundError(RegistryError): + """The requested registered model or concrete version does not exist.""" + + +class RegistryAccessError(RegistryError): + """The registry rejected the operation because credentials or permissions are insufficient.""" + + +class RegistryOperationError(RegistryError): + """The registry returned an error that is neither a missing resource nor an access failure.""" + + +@dataclass(frozen=True, slots=True) +class ResolvedModel: + """An immutable model reference after alias selection has been pinned.""" + + name: str + version: str + model_uri: str + signature: Any | None + digest: str | None + + +def resolve_model( + name: str, + *, + alias: str | None = None, + version: str | int | None = None, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> ResolvedModel: + """Resolve exactly one alias or version and return a concrete model URI. + + Alias resolution is performed once. The returned ``model_uri`` contains the + resolved version, so later inference does not follow a moving alias. + ``tracking_uri`` and ``registry_uri`` are explicit client settings; neither + operation uses MLflow's process-global active run. + """ + _validate_reference(name, alias, version, tracking_uri, registry_uri) + mlflow = _require_mlflow() + client = _make_client(mlflow, tracking_uri, registry_uri) + try: + model_version = ( + client.get_model_version_by_alias(name, alias) + if alias is not None + else client.get_model_version(name, str(version)) + ) + except Exception as exc: # noqa: BLE001 - translate MLflow's backend errors at the boundary + raise _translate_error(exc, name=name, version=str(version or alias)) from exc + + concrete_version = str(model_version.version) + model_uri = f"models:/{name}/{concrete_version}" + # The registry response carries the source URI that was recorded at + # publication time. Resolving that source avoids relying on MLflow's + # process-global registry store when a caller supplied explicit stores. + source_uri = getattr(model_version, "source", None) + artifact_uri = source_uri if isinstance(source_uri, str) and source_uri else model_uri + try: + local_path = mlflow.artifacts.download_artifacts( + artifact_uri=artifact_uri, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + model = mlflow.models.Model.load(Path(local_path)) + except Exception as exc: # noqa: BLE001 - artifact metadata is another registry boundary + raise _translate_error(exc, name=name, version=concrete_version) from exc + metadata = model.metadata or {} + digest = metadata.get("skyulf_bundle_digest") + return ResolvedModel( + name=name, + version=concrete_version, + model_uri=model_uri, + signature=model.signature, + digest=digest if isinstance(digest, str) else None, + ) + + +def register_model( + model_uri: str, + name: str, + *, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> Any: + """Publish a run artifact as a new registered-model version explicitly. + + ``model_uri`` must be a ``runs://`` URI produced by + the packaging step. This function never changes an alias and is never called + implicitly during prediction. It returns MLflow's created model-version + object so callers can persist its concrete version and status. + """ + _validate_registry_options(name, tracking_uri, registry_uri) + run_id = _parse_runs_uri(model_uri) + mlflow = _require_mlflow() + client = _make_client(mlflow, tracking_uri, registry_uri) + try: + client.create_registered_model(name) + except Exception as exc: # noqa: BLE001 - existing registration is the only benign result + if _error_code(exc) not in {"RESOURCE_ALREADY_EXISTS", "ALREADY_EXISTS"}: + raise _translate_error(exc, name=name, version="new") from exc + try: + return client.create_model_version(name=name, source=model_uri, run_id=run_id) + except Exception as exc: # noqa: BLE001 - translate MLflow's backend errors at the boundary + raise _translate_error(exc, name=name, version="new") from exc + + +def _require_mlflow() -> Any: + """Import the optional MLflow package and expose a typed dependency failure.""" + try: + import mlflow # noqa: PLC0415 # ty: ignore[unresolved-import] + except ImportError as exc: + raise RegistryDependencyError( + "MLflow registry support requires the optional 'mlflow' extra." + ) from exc + return mlflow + + +def _make_client(mlflow: Any, tracking_uri: str | None, registry_uri: str | None) -> Any: + """Create a client with explicit tracking and registry stores.""" + return mlflow.MlflowClient(tracking_uri=tracking_uri, registry_uri=registry_uri) + + +def _validate_reference( + name: str, + alias: str | None, + version: str | int | None, + tracking_uri: str | None, + registry_uri: str | None, +) -> None: + """Validate selector cardinality and UC-qualified names before any network call.""" + _validate_registry_options(name, tracking_uri, registry_uri) + if (alias is None) == (version is None): + raise ValueError("Provide exactly one of alias or version.") + if alias is not None and (type(alias) is not str or not alias.strip()): + raise ValueError("alias must be a non-empty string.") + if version is not None and ( + isinstance(version, bool) or type(version) not in (str, int) or not str(version).strip() + ): + raise ValueError("version must be a non-empty string or positive integer.") + if version is not None and str(version).isdigit() and int(version) <= 0: + raise ValueError("version must be a positive integer.") + + +def _validate_registry_options( + name: str, tracking_uri: str | None, registry_uri: str | None +) -> None: + """Validate registry names and URI options without constructing an MLflow client.""" + if type(name) is not str or not name.strip() or "/" in name: + raise ValueError("name must be a non-empty model name without '/'.") + parts = name.split(".") + if any(not part for part in parts) or len(parts) not in (1, 3): + raise ValueError("name must be model or catalog.schema.model.") + if _is_unity_catalog(registry_uri) and len(parts) != 3: + raise ValueError("Unity Catalog names must use catalog.schema.model.") + for value, label in ((tracking_uri, "tracking_uri"), (registry_uri, "registry_uri")): + if value is not None and (type(value) is not str or not value.strip()): + raise ValueError(f"{label} must be a non-empty string or None.") + + +def _is_unity_catalog(registry_uri: str | None) -> bool: + """Identify the explicit MLflow Unity Catalog registry scheme.""" + return registry_uri is not None and registry_uri.startswith("databricks-uc") + + +def _parse_runs_uri(model_uri: str) -> str: + """Extract and validate the source run ID from one packaging URI.""" + if type(model_uri) is not str or not model_uri.startswith("runs:/"): + raise ValueError("model_uri must be a runs:// URI.") + value = model_uri.removeprefix("runs:/") + run_id, separator, artifact_path = value.partition("/") + if not run_id or not separator or not artifact_path: + raise ValueError("model_uri must include a run ID and artifact path.") + return run_id + + +def _error_code(exc: Exception) -> str: + """Read an MLflow error code without importing optional exception classes.""" + value = getattr(exc, "error_code", "") + return str(getattr(value, "value", value)).upper() + + +def _translate_error(exc: Exception, *, name: str, version: str) -> RegistryError: + """Translate backend errors into stable caller-facing registry categories.""" + code = _error_code(exc) + if code in {"RESOURCE_DOES_NOT_EXIST", "NOT_FOUND"}: + return RegistryModelNotFoundError(f"Model '{name}' version '{version}' was not found.") + if code in {"PERMISSION_DENIED", "UNAUTHENTICATED", "UNAUTHORIZED"}: + return RegistryAccessError(f"Access denied for model '{name}' version '{version}'.") + return RegistryOperationError(f"MLflow registry operation failed for model '{name}'.") diff --git a/skyulf-core/tests/integrations/test_mlflow_registry.py b/skyulf-core/tests/integrations/test_mlflow_registry.py new file mode 100644 index 000000000..8eb6f6c0d --- /dev/null +++ b/skyulf-core/tests/integrations/test_mlflow_registry.py @@ -0,0 +1,207 @@ +"""Contract tests for the optional MLflow model registry adapter.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import InferenceBundle, build_bundle + +mlflow = pytest.importorskip("mlflow") +from skyulf.integrations.mlflow.model import log_model +from skyulf.integrations.mlflow.registry import ( + RegistryAccessError, + RegistryDependencyError, + RegistryModelNotFoundError, + register_model, + resolve_model, +) +from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run +from skyulf.pipeline import SkyulfPipeline + + +def _config(tmp_path: Path, name: str) -> TrackingConfig: + """Create an isolated tracking and registry store for one test.""" + db_path = (tmp_path / f"{name}.db").resolve() + uri = f"sqlite:///{db_path.as_posix()}" + return TrackingConfig(enabled=True, tracking_uri=uri, experiment_name=name) + + +def _bundle() -> tuple[InferenceBundle, pd.DataFrame]: + """Fit a tiny regression bundle suitable for local registry tests.""" + frame = pd.DataFrame({"x": np.arange(8, dtype="float64"), "target": np.arange(8) * 2.0}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=frame, test=frame.head(0)), target_column="target") + return build_bundle(pipeline, input_stage="raw", feature_order=("x",)), frame[["x"]].head(2) + + +def _publish(tmp_path: Path, name: str = "skyulf-registry") -> tuple[str, TrackingConfig]: + """Log and explicitly register one model in a test-owned local store.""" + bundle, _ = _bundle() + config = _config(tmp_path, name) + with track_run(config, run_name="registry-fit") as run: + model_uri = log_model( + bundle, + run_id=run.run_id, + artifact_path="model", + tracking_uri=config.tracking_uri, + ) + register_model( + model_uri, + name, + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + return model_uri, config + + +def test_register_and_resolve_concrete_version_with_signature_and_digest(tmp_path: Path) -> None: + """A registered model resolves to a versioned URI with Skyulf metadata.""" + model_uri, config = _publish(tmp_path) + client = mlflow.MlflowClient(tracking_uri=config.tracking_uri, registry_uri=config.tracking_uri) + version = client.get_model_version("skyulf-registry", "1").version + + resolved = resolve_model( + "skyulf-registry", + version=version, + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + + assert resolved.name == "skyulf-registry" + assert resolved.version == "1" + assert resolved.model_uri == "models:/skyulf-registry/1" + assert resolved.signature is not None + assert resolved.digest + assert model_uri.startswith("runs:/") + + +def test_alias_resolves_once_to_concrete_version(tmp_path: Path) -> None: + """Alias resolution returns a stable version URI rather than a moving alias URI.""" + model_uri, config = _publish(tmp_path) + client = mlflow.MlflowClient(tracking_uri=config.tracking_uri, registry_uri=config.tracking_uri) + client.set_registered_model_alias("skyulf-registry", "champion", "1") + + resolved = resolve_model( + "skyulf-registry", + alias="champion", + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + register_model( + model_uri, + "skyulf-registry", + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + client.set_registered_model_alias("skyulf-registry", "champion", "2") + + assert resolved.version == "1" + assert resolved.model_uri == "models:/skyulf-registry/1" + + +def test_register_does_not_promote_an_alias(tmp_path: Path) -> None: + """Publishing a version leaves promotion as an explicit caller operation.""" + _, config = _publish(tmp_path) + version = mlflow.MlflowClient( + tracking_uri=config.tracking_uri, registry_uri=config.tracking_uri + ).get_model_version("skyulf-registry", "1") + + assert version.aliases == [] + + +def test_registry_store_can_be_separate_from_tracking_store(tmp_path: Path) -> None: + """Registry metadata and run artifacts can use separate explicit stores.""" + bundle, _ = _bundle() + tracking = _config(tmp_path, "tracking") + registry = _config(tmp_path, "registry") + with track_run(tracking, run_name="separate-stores") as run: + model_uri = log_model( + bundle, + run_id=run.run_id, + artifact_path="model", + tracking_uri=tracking.tracking_uri, + ) + + register_model( + model_uri, + "separate-store-model", + tracking_uri=tracking.tracking_uri, + registry_uri=registry.tracking_uri, + ) + resolved = resolve_model( + "separate-store-model", + version="1", + tracking_uri=tracking.tracking_uri, + registry_uri=registry.tracking_uri, + ) + + assert resolved.model_uri == "models:/separate-store-model/1" + assert resolved.digest + + +def test_register_rejects_non_run_artifact_uri() -> None: + """Registry publication accepts only the run artifact URI produced by packaging.""" + with pytest.raises(ValueError, match="runs:/"): + register_model("models:/already-registered/1", "skyulf-registry") + + +@pytest.mark.parametrize( + ("alias", "version"), + [(None, None), ("champion", "1")], +) +def test_resolve_requires_exactly_one_reference(alias: str | None, version: str | None) -> None: + """A registry lookup must not silently choose latest or prefer one selector.""" + with pytest.raises(ValueError, match="exactly one of alias or version"): + resolve_model("skyulf-registry", alias=alias, version=version) + + +def test_missing_model_and_permission_are_typed_failures( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Missing resources and access failures remain distinct from dependency failures.""" + config = _config(tmp_path, "missing") + with pytest.raises(RegistryModelNotFoundError): + resolve_model( + "missing-model", + version="1", + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + + class ForbiddenClient: + def get_model_version(self, name: str, version: str) -> object: + error = mlflow.exceptions.MlflowException("denied") + error.error_code = "PERMISSION_DENIED" + raise error + + monkeypatch.setattr( + "skyulf.integrations.mlflow.registry._make_client", + lambda *args, **kwargs: ForbiddenClient(), + ) + with pytest.raises(RegistryAccessError): + resolve_model("private-model", version="1") + + +def test_missing_mlflow_is_a_dependency_failure(monkeypatch: pytest.MonkeyPatch) -> None: + """A missing optional package has a different remediation from registry access.""" + monkeypatch.setattr( + "skyulf.integrations.mlflow.registry._require_mlflow", + lambda: (_ for _ in ()).throw(RegistryDependencyError("install mlflow")), + ) + with pytest.raises(RegistryDependencyError): + resolve_model("skyulf-registry", version="1") + + +def test_unity_catalog_requires_three_part_model_name_without_network() -> None: + """UC registry configuration rejects non-qualified names before any client call.""" + with pytest.raises(ValueError, match="catalog.schema.model"): + resolve_model( + "skyulf-registry", + version="1", + registry_uri="databricks-uc", + ) From d43e74ca56697d5745ed1577c40e109f1eee5486 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 20:04:59 +0300 Subject: [PATCH 26/85] feat(core): add guarded monthly Spark Delta batches Signed-off-by: flyingriverhorse --- .github/workflows/spark-tests.yml | 25 ++ changelog/0.9.x.md | 11 +- docs/user_guide/databricks_batch.md | 194 +++++++++++++ .../03-mlflow-batch-delivery-plan.md | 88 +++--- initiatives/spark_and_mlflow/HANDOFF.md | 43 ++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 76 ++++- mkdocs.yml | 1 + requirements-delta.txt | 4 + skyulf-core/setup.py | 2 + .../integrations/databricks/__init__.py | 5 + .../integrations/databricks/_contracts.py | 130 +++++++++ .../integrations/databricks/admission.py | 86 ++++++ .../skyulf/integrations/databricks/batch.py | 144 ++++++++++ .../skyulf/integrations/databricks/delta.py | 131 +++++++++ skyulf-core/tests/integrations/conftest.py | 49 ++++ .../integrations/test_batch_admission.py | 33 +++ .../tests/integrations/test_batch_contract.py | 124 +++++++++ .../tests/integrations/test_delta_publish.py | 260 ++++++++++++++++++ uv.lock | 21 +- 19 files changed, 1376 insertions(+), 51 deletions(-) create mode 100644 docs/user_guide/databricks_batch.md create mode 100644 requirements-delta.txt create mode 100644 skyulf-core/skyulf/integrations/databricks/__init__.py create mode 100644 skyulf-core/skyulf/integrations/databricks/_contracts.py create mode 100644 skyulf-core/skyulf/integrations/databricks/admission.py create mode 100644 skyulf-core/skyulf/integrations/databricks/batch.py create mode 100644 skyulf-core/skyulf/integrations/databricks/delta.py create mode 100644 skyulf-core/tests/integrations/conftest.py create mode 100644 skyulf-core/tests/integrations/test_batch_admission.py create mode 100644 skyulf-core/tests/integrations/test_batch_contract.py create mode 100644 skyulf-core/tests/integrations/test_delta_publish.py diff --git a/.github/workflows/spark-tests.yml b/.github/workflows/spark-tests.yml index 8d445e8c9..a5746871e 100644 --- a/.github/workflows/spark-tests.yml +++ b/.github/workflows/spark-tests.yml @@ -6,6 +6,7 @@ on: paths: - "skyulf-core/**" - "requirements-spark.txt" + - "requirements-delta.txt" - ".github/workflows/spark-tests.yml" workflow_dispatch: @@ -32,3 +33,27 @@ jobs: run: uv pip install --system -r requirements-spark.txt - name: Exercise Spark JVM and Python workers run: python -m pytest skyulf-core/tests/spark -q -o addopts= + + delta: + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + SKYULF_REQUIRE_DELTA: "1" + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + - name: Install optional Delta test dependencies + run: uv pip install --system -r requirements-delta.txt + - name: Exercise real Delta transactions and publish admission + run: >- + python -m pytest + skyulf-core/tests/integrations/test_batch_contract.py + skyulf-core/tests/integrations/test_batch_admission.py + skyulf-core/tests/integrations/test_delta_publish.py -q -o addopts= diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 417b334b9..909946d15 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -104,13 +104,20 @@ execution, MLflow registry and Databricks delivery remain under development. URI, signatures and bundle digests are exposed, tracking and registry stores may be separate, and missing/access/dependency failures are typed. Live Unity Catalog and Databricks validation remain in SM-16. +- Experimental monthly Spark batch inference with pinned Delta source versions, + explicit UTC periods and snapshot availability cutoffs, and model/code/run + provenance in committed receipts. Atomic period replacement preserves other + periods; retries cannot undo a newer run, stale writers fail, and empty-period + deletion requires `allow_empty=True`. Real local Delta tests cover both + inference modes and process-shared admission. Distributed admission and live + Databricks validation remain SM-16. Includes an English guide and Delta CI lane. ### Planned scope — not yet available - Further native Spark nodes and broader portable-state coverage. - Worker wheel packaging and scale/RSS validation for production Spark clusters. -- Unity Catalog model resolution and registry adapters. -- Scheduled batch inference with reproducible model versions and Delta outputs. +- Live Unity Catalog and Databricks registry validation. +- Databricks scheduling and distributed publish admission for batch jobs. Endpoint integrations and template/Databricks Bundle generation follow the core and batch validation gates. Planned items are not shipped functionality; diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md new file mode 100644 index 000000000..76b77087a --- /dev/null +++ b/docs/user_guide/databricks_batch.md @@ -0,0 +1,194 @@ +# Monthly Spark inference and Delta publication + +`run_batch` reads a pinned Delta snapshot, applies a fitted inference bundle, +and atomically replaces the requested period in a precreated Delta table. +It reuses both [Spark inference modes](inference_flow.md), without refitting +feature engineering or the model. Scheduling remains the caller's responsibility. + +The current validation covers **local Spark 4.0.3 with Delta Lake 4.0.0 on Linux**. +Live Databricks, Unity Catalog, distributed publish admission and wheel delivery +remain the SM-16 platform gate. Installing this adapter does not certify those +platforms. Tracking and registry remain optional and independent of the engine. + +```mermaid +flowchart LR + A["Delta source: fixed version"] --> B["Select UTC period [start, end)"] + C["Fitted bundle: fixed model digest"] --> D["Spark inference"] + B --> D + D --> E["Validate predictions and metadata"] + E --> F["Acquire exclusive table admission"] + F --> G{"Existing run receipt?"} + G -->|"Same request"| H["Return original commit"] + G -->|"New request"| I["Check expected target version"] + I --> J["Atomic Delta replaceWhere"] + J --> K["Verify committed receipt"] +``` + +## Prepare the inputs + +Use an existing raw `InferenceBundle`, produced through +[local or Spark feature engineering](inference_flow.md). Its supported FE and +input schema restrictions still apply. A table name is required as `source`; +an arbitrary DataFrame cannot prove which snapshot it represents. + +Both tables must already exist and use Delta. For a regression model with one +`double` prediction, this is an example target schema: + +```sql +CREATE TABLE analytics.customer_predictions ( + customer_id BIGINT, + event_time TIMESTAMP, + prediction DOUBLE, + __skyulf_run_id STRING, + __skyulf_model_name STRING, + __skyulf_model_version STRING +) USING DELTA; +``` + +Use the actual prediction columns and types from the bundle for classification, +including class-ordered probability columns. The runner checks exact names and +types against the target, then uses the target's column order. It does not create +or evolve tables. Source keys must be non-null and unique within the selected +period. `event_time` must be Spark `timestamp`, not a date, string or +`timestamp_ntz`. Null period timestamps are rejected anywhere in the source. + +## Run a period + +This example assumes source version `42` was committed before the explicit +February 2 cutoff, and the target's current version is `0`. Supply the actual +versions for your data. Resolve any registry alias once before constructing +the spec, then bind its concrete version and digest to the downloaded bundle. +The runner checks the bundle digest; it does not independently contact the +registry to verify the caller's model name/version association. + +```python +from datetime import UTC, datetime +from importlib.metadata import version + +from skyulf.core.execution import ExecutionOptions +from skyulf.integrations.databricks import BatchSpec, run_batch +from skyulf.integrations.databricks.admission import LocalTableLock + +spec = BatchSpec( + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + as_of=datetime(2026, 2, 2, tzinfo=UTC), + row_keys=("customer_id",), + output_table="analytics.customer_predictions", + model_name="customer-risk", + model_version="7", + model_digest=bundle.semantic_digest, + source_version=42, + code_version=version("skyulf-core"), + run_id="customer-risk-2026-01-v7", + expected_target_version=0, + mode="native_features", # alternatively: "python_pipeline" +) + +result = run_batch( + spark, + spec, + source="analytics.customer_features", + bundle=bundle, + options=ExecutionOptions("spark"), + admission=LocalTableLock("/var/lib/skyulf/publish-locks"), +) +print(result.commit_version, result.output_count, result.replayed) +``` + +`LocalTableLock` is for local Spark drivers on **one host**, all sharing the same +lock directory. Use a writable directory managed for this purpose. Lock files +are intentionally retained; do not delete them while publishers may run. The +OS releases ownership when the process exits. This implementation is rejected +on distributed Spark masters, including `local-cluster`. + +The `PublishAdmission` protocol is an extension boundary, not an implemented +Databricks coordinator. A distributed implementation must hold exclusive +ownership by immutable Delta table ID throughout validation, write and receipt +verification. The current API does not pass fencing tokens to Delta, so an +expiring lease is insufficient. Every publisher must participate in the same +authority. Uncoordinated external writes are outside this guarantee; detected +Delta conflicts still raise `BatchConflictError`. + +## Time and reproducibility + +The period is half-open: the start is included and the end is excluded. Aware +datetimes are converted to UTC instants independently of the Spark session's +timezone. For a business calendar month, construct boundaries explicitly: + +```python +from zoneinfo import ZoneInfo + +zone = ZoneInfo("Europe/Vilnius") +start = datetime(2026, 3, 1, tzinfo=zone) # 2026-02-28 22:00 UTC +end = datetime(2026, 4, 1, tzinfo=zone) # 2026-03-31 21:00 UTC +# Pass these as period_start/period_end and business_timezone="Europe/Vilnius". +``` + +`business_timezone` records calendar intent; it does not reinterpret the supplied +instants. Naive datetimes and nonexistent local DST times are rejected. For an +ambiguous local time, select the intended `fold` when constructing the datetime. + +`as_of` is a **snapshot availability cutoff**. The runner checks the selected +Delta version's commit timestamp and then reads that exact `versionAsOf`. A newer +snapshot or expired history fails. This does not establish point-in-time +correctness of upstream feature joins: the source producer must implement its +own historical feature and availability rules. No timestamp-column filter can +retroactively reconstruct overwritten source rows. For a backfill, explicitly +choose the intended model version and source snapshot; scheduler time is never +silently substituted for either the period or cutoff. + +The Delta commit's `userMetadata` records the full request fingerprint, UTC +period/cutoff, source table ID/version/commit time, model name/version/digest, +installed Skyulf version, run ID and input/output counts. Only the three +`__skyulf_*` columns shown above are repeated on each output row. + +## Retries, conflicts and empty periods + +- Reuse the **same spec and logical run ID** for a retry. A matching committed + receipt returns its original version and counts with `replayed=True`. It does + not write again, even if a newer run has since recomputed the same period. + The runner still reads and validates the source and bundle before checking + the sink receipt, so retries require those inputs to remain available. +- Reusing a run ID with a changed request raises `BatchConflictError`. +- To intentionally recompute a period, choose a new run ID and explicitly set + `expected_target_version` to the version you have reviewed. Any intervening + target commit makes that expectation stale. Do not automatically refresh it + and retry a conflict: that would silently authorize replacing another run. +- Empty output fails unless `allow_empty=True`. With that explicit setting, + the same atomic replacement removes the selected period and records a receipt. + Other periods remain unchanged. Out-of-period/null output and incorrect run + metadata are rejected before writing. +- Success is returned only after verifying the committed receipt. If the client + loses contact after commit, the outcome may be unknown: retry the unchanged + request to check the receipt. Preserve Delta history and transaction retention + for the supported retry window; this is not unlimited replay storage. + +The first mode is `replace_period`. Append, key `MERGE`, automatic schema +evolution, streaming and endpoint deployment remain unsupported here. The sink +helper is lower-level: direct callers must supply output and a manifest with +the same provenance guarantees as `run_batch`. + +## Local verification + +Use Linux (or WSL) with Python 3.12 and Java 17. Windows Spark inference alone +does not establish that Hadoop's filesystem support can write Delta locally. +Keep this test environment separate from Databricks Runtime's bundled packages. + +```bash +uv venv .venv-delta +uv pip install --python .venv-delta/bin/python -r requirements-delta.txt +SKYULF_REQUIRE_DELTA=1 .venv-delta/bin/python -m pytest \ + skyulf-core/tests/integrations/test_batch_contract.py \ + skyulf-core/tests/integrations/test_batch_admission.py \ + skyulf-core/tests/integrations/test_delta_publish.py -q -o addopts= +``` + +The fixture configures the Delta extension/catalog and creates only temporary +test tables. Its first launch downloads the matching Maven jars. For an offline +run, `SKYULF_DELTA_JARS` may point to a prepared directory containing compatible +Delta and transitive dependency jars. Required lanes fail when Delta is missing; +the base environment skips optional Delta tests. + +Relevant upstream behavior: [Delta selective overwrite and idempotent writes](https://docs.delta.io/delta-batch/) +and [Delta concurrency control](https://docs.delta.io/concurrency-control/). diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index 924ef9f26..a26a6eaf3 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -147,46 +147,49 @@ validation. MLflow 3.16.1 isolated lane: **10 passed**. Base environment: registry module skipped because MLflow is absent. Live Unity Catalog and Spark runner validation remain SM-16 carry-forward items. -## SM-15 — Aylık batch ve Delta yayınlama - -**Bağımlılık:** SM-14. **Oluştur:** -`skyulf/integrations/databricks/{__init__,batch,delta}.py`, -`tests/integrations/test_batch_contract.py`, `tests/integrations/test_delta_publish.py`. -**Üretir:** `BatchSpec(period_start, period_end, as_of, row_keys, output_table, -model_name, model_version, publish_mode="replace_period")`; -`run_batch(spark, spec, *, source, bundle, options) -> BatchResult`. - -- [ ] UTC yarı açık `[start,end)` dönem, business timezone dönüşümü ve explicit - `as_of` doğrulansın. Scheduler saati otomatik data cutoff sayılmasın. -- [ ] Kaynak tablo sürümü/snapshot, concrete model version, code wheel sürümü, - input/output counts ve run_id manifestte kaydedilsin. `as_of` point-in-time - veri yoksa tarihsel doğruluk garantisi vermez; job açıklayıcı hata üretir. -- [ ] İlk sink `replace_period`: yalnız hedef dönem için atomic Delta replace; - boş sonuçta dönem silme explicit `allow_empty=True` gerektirir. Nonmatching - period satırları yazma öncesi reddedilir. Dönem dışı satır korunur. -- [ ] Aynı logical run retry mükerrer satır oluşturmasın. Aynı döneme eşzamanlı - farklı run için tek-writer admission + Delta conflict handling gerekir; - conflict sessiz last-writer-wins olmaz. Sonuç başarılı ancak commit sonrası. -- [ ] Append ve key MERGE ilk release'te unsupported; sonraki genişletmede - merge key `(row_keys, period, model_version)` veya business overwrite politikası - explicit seçilir. Backfill geçmiş model/current model seçimini zorunlu alır. - -```python -def test_retry_preserves_other_periods(delta_batch_harness): - """Rerunning one month must neither duplicate it nor erase another month.""" - h = delta_batch_harness - h.seed_previous_period() - first = h.run_current_period() - second = h.run_current_period() - assert h.current_keys_are_unique() - assert first.output_count == second.output_count - assert h.previous_period_matches_seed() -``` - -`delta_batch_harness` bu görevde geçici Delta tablolarına gerçek read/write yapan -fixture'dır; mock sink testin yerine geçmez. Yetkisiz/çakışan publish ayrıca test edilir. -**Komut:** `python -m pytest skyulf-core/tests/integrations/test_batch_contract.py skyulf-core/tests/integrations/test_delta_publish.py -q` -**Kabul:** G4 local/uyumlu Delta ortamında dönem izolasyonu, retry ve conflict kanıtı. +## SM-15 — Monthly batch and Delta publication + +**Dependency:** SM-14. **Files:** +`skyulf/integrations/databricks/{__init__,_contracts,admission,batch,delta}.py`, +`tests/integrations/{conftest,test_batch_contract,test_batch_admission,test_delta_publish}.py`. +**API:** `BatchSpec` pins aware period boundaries, `as_of`, keys, source version, +target name/expected version, model name/concrete version/digest, installed code +version, run ID and inference mode. `run_batch(spark, spec, *, source, bundle, +options, admission) -> BatchResult` consumes an existing Delta table by name. + +- [x] Validate UTC half-open periods, explicit calendar timezone and cutoff; + reject naive/nonexistent local times. Test a non-UTC Spark session and DST. +- [x] Read a concrete Delta `versionAsOf` and verify its commit is no later than + `as_of`. Retain table ID/version, model digest, runtime version and counts in + a committed manifest. Reject incorrect digests/runtime and unavailable history. +- [x] Use atomic `replaceWhere`, preserving other periods. Reject invalid output + timestamps/metadata/counts before writing; empty deletion requires `allow_empty`. +- [x] Enforce explicit table-wide admission and expected target version. Replays + return the original receipt without undoing newer intentional recomputation; + changed requests under the same run ID fail. Return success only after receipt + verification. Test real Delta transactions and cross-process OS lock contention. +- [x] Reject append/key MERGE. Require a concrete model version for every run, + including backfills. Intentional replacement uses a new run ID and explicitly + reviewed target version; no automatic conflict overwrite. + +**Temporal boundary:** `as_of` proves snapshot availability, not correctness of +upstream historical feature joins. The runner rejects a snapshot committed after +the cutoff. The source producer remains responsible for point-in-time joins; +there is no generic timestamp-column filter claiming to reconstruct history. +Model name/version association is caller-provided; the supplied bundle's digest +is verified. MLflow/UC downloads remain separate adapter/platform work. + +**Admission boundary:** `LocalTableLock` coordinates local Spark drivers on one +host using a common lock directory keyed by Delta table ID. It is rejected by +both public entry points on distributed masters. The provider protocol requires +non-expiring ownership through the commit; it has no sink fencing token support. +Distributed admission remains SM-16. Writers bypassing the authority are outside +the single-writer guarantee. Delta-detected concurrency failures still propagate. + +**Acceptance:** G4 local Delta period isolation, retry and conflict evidence. +The fixture performs real Delta I/O; permission denial at the admission boundary +is a fault-injection test, not evidence of live UC permissions. Exact versions, +commands and results are recorded in [OPEN_QUEUE.md](OPEN_QUEUE.md). ## SM-16 — Gerçek Databricks doğrulaması @@ -194,6 +197,11 @@ fixture'dır; mock sink testin yerine geçmez. Yetkisiz/çakışan publish ayrı `initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md` (uygulama sırasında). **Üretir:** Bir wheel ile gerçek FE → registry load → Spark inference → test Delta table. +- [ ] Implement and verify shared publish admission for the selected runtime. + SM-15's local file locks are rejected on distributed masters. The provider + must hold exclusive ownership through commit and receipt verification; + expiring leases require a new sink fencing design before they can be used. + Include actual UC write-permission and concurrent-publisher evidence. - [ ] Kullanılan DBR/Python/Spark/MLflow/Arrow, compute türü, izinli catalog/schema ve test resource isimlerini kaydet. Workspace bilgisi yoksa yalnız bu görev WAIT olur; local testler Databricks geçti sayılmaz. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 04b482d48..fac4b572d 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,17 +1,19 @@ # Session handoff - 2026-09-22 -SM-11 is complete after the corrective validation gate. SM-12, SM-13 and SM-14 -are now complete; resume with SM-15. +SM-00 through SM-15 are complete. Resume with SM-16 platform preparation; +live Databricks execution has not been validated. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-14 are complete; SM-15 is READY. +- SM-00 through SM-15 are complete; SM-16 is READY for platform preparation. +- SM-15 baseline: `4a613cb5`. Its implementation and verification are in the + delivery commit containing this handoff. No live Databricks validation yet. - SM-13 starts from `67315253`; its implementation, guide and evidence are in the delivery commit containing this handoff. - Previous guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). - Read [OPEN_QUEUE.md](OPEN_QUEUE.md), [ARCHITECTURE.md](ARCHITECTURE.md) and - the SM-15 section of [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md). + the SM-16 section of [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md). - User-facing guide: [How inference works](../../docs/user_guide/inference_flow.md). ## Confirmed terminology and intended workflow @@ -97,3 +99,36 @@ that later platform gate. Pre-existing `.tmp-*` directories remain outside this change. Preserve them; do not stage or delete them as part of the next task. + +## SM-15 delivery and next platform boundary + +The monthly runner now reads a pinned Delta snapshot, checks its availability +at `as_of`, runs either Spark inference mode and atomically replaces one period +in a precreated target. Required provenance includes the model digest and +installed code version. The source producer still owns historical feature joins; +the cutoff does not establish their point-in-time correctness. + +Local Linux validation passed **43 tests** on Spark **4.0.3** / Delta **4.0.0**: +18 real Delta cases plus 25 contract/admission cases. Base regression passed +105 with 26 optional skips. See the queue for exact commands and package versions. +The English [batch guide](../../docs/user_guide/databricks_batch.md) includes the +schema, code example, diagram, retry policy and limits. + +`LocalTableLock` uses cross-process OS locks and requires a common directory +on one host. Both public entry points reject it on distributed Spark masters. +SM-16 must implement or validate distributed publish admission; the provider +protocol is not proof that Databricks has a coordinator. Expiring leases cannot +protect this sink because it has no fencing-token mechanism. Every publisher +must use the same authority. Test actual Delta/UC permissions in that lane. + +Keep the current source snapshot and original spec available for retries. A +receipt returns the old committed version even after a newer recomputation, +without writing again. New computation needs a new run ID and reviewed target +version. History and transaction retention must cover the allowed retry window. + +Next, prepare the SM-16 wheel/job smoke and platform evidence record, including +the carried registry-to-Spark path, without creating a DAB template or endpoints. +Actual execution needs an explicitly selected runtime, permitted test namespace, +and authentication. The user retracted an accidentally pasted login command; +do not treat its host or editor-created `databricks.yml` as authorization to log +in, submit jobs or use that workspace. Those editor files remain outside SM-15. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 221fc3190..7de2f0ca9 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,9 +1,9 @@ # Spark ve MLflow — Open Queue -Güncelleme: 2026-09-22. **SM-00–SM-13 tamamlandı; sıradaki SM-14. Hedef: 0.9.0.** +Updated: 2026-09-22. **SM-00–SM-15 complete; SM-16 is next. Target: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. -Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-14. +Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-16. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -26,8 +26,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-12 | Opsiyonel MLflow tracking | SM-11 | DONE | Off bağımsız; gerçek run lifecycle ve izolasyon | | SM-13 | MLflow model packaging | SM-12 | DONE | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | -| SM-15 | Monthly batch + Delta sink | SM-14 | READY | Period isolation, retry and conflict control | -| SM-16 | Gerçek Databricks kapısı | SM-15 | WAIT | Job/run kanıtı; UC load; iki inference yolu | +| SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | +| SM-16 | Gerçek Databricks kapısı | SM-15 | READY | Platform setup, distributed admission, job/run evidence | | SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | | SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | | SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | @@ -47,6 +47,74 @@ gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. +## SM-15 — 2026-09-22 validation record + +- Baseline `4a613cb5`; branch `090`. The delivery commit containing this record + adds `skyulf.integrations.databricks`, three batch test modules and a real + Delta fixture, the optional Delta dependency profile/CI lane, and the English + [monthly batch guide](../../docs/user_guide/databricks_batch.md). +- `run_batch` pins a concrete Delta source version and verifies snapshot + availability at the explicit cutoff. Both existing Spark inference modes + feed a precreated Delta target. A committed manifest records request identity, + model digest, installed code version and counts. Source history newer than + `as_of`, mismatched bundle digest/runtime and ambiguous contracts fail. +- Atomic `replaceWhere` preserves other periods. Empty deletion requires opt-in. + Run receipts prevent duplicate publication and prevent an old retry undoing + a newer recomputation. Changed requests under one run ID and stale target + versions fail. Local OS admission locks are tested across processes; both + runner and public sink reject local locks on distributed masters. +- Final required Linux/WSL lane: **43 passed**, including **18 real Delta + integration cases** and **25 contract/admission cases**, no skips, 111.95s. + Python **3.12.3**, PySpark **4.0.3**, Delta Python/JVM **4.0.0**, Java 17; + pandas **2.3.3**, Polars **1.44.2**, Arrow **25.0.1**, sklearn **1.9.1**. + Initial exploratory tests used newer Python-package patch versions; the final + gate was rerun after aligning the environment with `requirements-delta.txt`. +- Cases include a pinned old source after a newer commit, a non-UTC Spark + session, exact period boundaries, null/wrong metadata/count rejection with + target version unchanged, stale/new/old retries and committed empty deletion. + Admission permission denial uses fault injection; it is not live UC evidence. +- Base regression: **105 passed, 26 skipped** with MLflow/Delta absent, plus + existing sklearn interchange and Windows physical-core warnings. Final narrow + Windows contract/admission run: **25 passed**. Ruff check/format, repository + Ty and strict MkDocs passed; the guide's Mermaid parsed with the real parser. + Repository pre-commit hooks passed, including the synchronized optional + dependency lock. GitHub Actions was added but has not run remotely. +- Windows Hadoop filesystem support could not run real Delta I/O, so the + required transaction gate used an isolated Linux/WSL environment. No runtime + authentication or Databricks job was performed. Preserve pre-existing temp + folders and editor-created Databricks configuration outside this commit. +- Remaining scope: the cutoff proves snapshot availability only, not upstream + point-in-time feature joins. Model registry identity is bound by the caller; + bundle digest is checked. Receipt/history retention bounds the retry window. + A shared local lock directory protects cooperative local writers on one host; + distributed admission requires a separate implementation with ownership held + throughout the commit. Expiring leases without sink fencing are unsupported. + These platform concerns and the carried registry-to-Spark gate belong to SM-16. + +Reproducible commands (Linux with Java 17 and an isolated environment): + +```bash +uv venv .venv-delta +uv pip install --python .venv-delta/bin/python -r requirements-delta.txt +SKYULF_REQUIRE_DELTA=1 .venv-delta/bin/python -m pytest \ + skyulf-core/tests/integrations/test_batch_contract.py \ + skyulf-core/tests/integrations/test_batch_admission.py \ + skyulf-core/tests/integrations/test_delta_publish.py -q -o addopts= +``` + +Exact local invocation used the prepared WSL environment and cached official jars: + +```powershell +wsl -d Ubuntu -- bash .cache/sm15-linux-run.sh -m pytest skyulf-core/tests/integrations/test_batch_contract.py skyulf-core/tests/integrations/test_batch_admission.py skyulf-core/tests/integrations/test_delta_publish.py -q -p no:cacheprovider -o addopts= --basetemp /tmp/sm15-delta-pinned-final --tb=short +.venv/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_inference_bundle.py skyulf-core/tests/unit/test_pipeline_inference_schema.py skyulf-core/tests/integrations -q -o addopts= --basetemp .cache/sm15-base-final --tb=short +.venv/Scripts/ty.exe check backend skyulf-core/skyulf skyulf-core/tests run_skyulf.py celery_worker.py +.venv/Scripts/python.exe -m mkdocs build --strict --site-dir .cache/sm15-docs +``` + +The local shell wrapper exports Java 17, its Python worker executable is selected +by the fixture, and `SKYULF_DELTA_JARS` points to the cached Delta 4.0.0 jars. +The portable command above downloads those jars through Delta's normal helper. + ## SM-13 — 2026-09-22 validation record - Added optional MLflow `pyfunc` packaging in diff --git a/mkdocs.yml b/mkdocs.yml index caa35de30..ad7cff39c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -79,6 +79,7 @@ nav: - MLflow Tracking (Development): user_guide/mlflow_tracking.md - MLflow Models (Development): user_guide/mlflow_models.md - MLflow Registry (Development): user_guide/mlflow_registry.md + - Databricks Batch (Development): user_guide/databricks_batch.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/requirements-delta.txt b/requirements-delta.txt new file mode 100644 index 000000000..8c7a0f22b --- /dev/null +++ b/requirements-delta.txt @@ -0,0 +1,4 @@ +# Local Delta Lake harness for the optional Spark batch tests. +# Databricks Runtime already provides Delta; do not install this into a DBR job. +-r requirements-spark.txt +delta-spark==4.0.0 diff --git a/skyulf-core/setup.py b/skyulf-core/setup.py index 23a8d2849..d065187a0 100644 --- a/skyulf-core/setup.py +++ b/skyulf-core/setup.py @@ -43,6 +43,8 @@ extras_require={ # Experimental test/runtime dependency only; node support is gated separately. "spark": ["pyspark>=4.0.3,<4.1.0", "pandas>=2.0.0,<3.0.0"], + # Local Delta harness only; Databricks Runtime supplies its own Delta engine. + "delta": ["delta-spark>=4.0.0,<4.1.0", "pyspark>=4.0.3,<4.1.0"], "mlflow": ["mlflow>=3.10,<4.0"], "dev": [ "pytest", diff --git a/skyulf-core/skyulf/integrations/databricks/__init__.py b/skyulf-core/skyulf/integrations/databricks/__init__.py new file mode 100644 index 000000000..8c22cd540 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/__init__.py @@ -0,0 +1,5 @@ +"""Optional Databricks batch and Delta integrations.""" + +from .batch import BatchResult, BatchSpec, run_batch + +__all__ = ["BatchResult", "BatchSpec", "run_batch"] diff --git a/skyulf-core/skyulf/integrations/databricks/_contracts.py b/skyulf-core/skyulf/integrations/databricks/_contracts.py new file mode 100644 index 000000000..ca2f2d99f --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/_contracts.py @@ -0,0 +1,130 @@ +"""Validated batch identities, independent of Spark or platform connections.""" + +import re +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Any +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + + +def table_name(value: str) -> str: + """Validate and quote a simple one-, two- or three-part catalog identifier.""" + if type(value) is not str or not re.fullmatch( + r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}", value + ): + raise ValueError("Table name must contain one to three simple identifiers.") + return ".".join(f"`{part}`" for part in value.split(".")) + + +def column_name(value: str) -> str: + """Restrict control columns to simple names outside reserved batch metadata.""" + if type(value) is not str or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", value): + raise ValueError("Control column must be a simple identifier.") + if value.lower().startswith("__skyulf_"): + raise ValueError("Control column collides with reserved __skyulf_ metadata.") + return f"`{value}`" + + +@dataclass(frozen=True, slots=True, kw_only=True) +class BatchSpec: + """Pin period, source, model and expected target version for one logical run. + + Aware dates represent instants and are converted to UTC without reinterpreting + wall-clock values. Construct local calendar boundaries with ``ZoneInfo``. + ``source_version`` is a Delta integer version, never an arbitrary label. + The output table must already exist with the intended prediction schema. + """ + + period_start: datetime + period_end: datetime + as_of: datetime + row_keys: tuple[str, ...] + output_table: str + model_name: str + model_version: str + source_version: int + code_version: str + run_id: str + model_digest: str + expected_target_version: int + period_column: str = "event_time" + business_timezone: str = "UTC" + mode: str = "native_features" + publish_mode: str = "replace_period" + allow_empty: bool = False + + def __post_init__(self) -> None: + """Reject ambiguity before any Spark action or table modification.""" + for name in ("period_start", "period_end", "as_of"): + value = getattr(self, name) + if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware.") + # Reject nonexistent local times; fold explicitly resolves ambiguous times. + if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( + tzinfo=None + ): + raise ValueError(f"{name} is not a valid local instant.") + if self.period_start_utc >= self.period_end_utc: + raise ValueError("period_start must precede period_end.") + table_name(self.output_table) + column_name(self.period_column) + if type(self.row_keys) is not tuple or not self.row_keys: + raise ValueError("row_keys must be a nonempty tuple.") + for key in self.row_keys: + column_name(key) + names = [key.lower() for key in self.row_keys] + if len(set(names)) != len(names) or self.period_column.lower() in names: + raise ValueError("row_keys and period_column must be distinct.") + for name in ("model_name", "code_version", "run_id"): + value = getattr(self, name) + if type(value) is not str or not value.strip() or len(value) > 512: + raise ValueError(f"{name} must be a nonempty string of at most 512 characters.") + if type(self.model_version) is not str or not re.fullmatch( + r"[1-9][0-9]*", self.model_version + ): + raise ValueError("model_version must be a concrete positive version, not an alias.") + for name in ("source_version", "expected_target_version"): + value = getattr(self, name) + if type(value) is not int or value < 0: + raise ValueError(f"{name} must be a nonnegative integer.") + if type(self.model_digest) is not str or not re.fullmatch( + r"[0-9a-f]{64}", self.model_digest + ): + raise ValueError("model_digest must be a SHA-256 bundle digest.") + if self.mode not in ("native_features", "python_pipeline"): + raise ValueError("mode must be native_features or python_pipeline.") + if self.publish_mode != "replace_period": + raise ValueError("Only replace_period publication is supported.") + if type(self.allow_empty) is not bool: + raise TypeError("allow_empty must be a bool.") + try: + ZoneInfo(self.business_timezone) + except (TypeError, ValueError, ZoneInfoNotFoundError) as exc: + raise ValueError("business_timezone must name an IANA timezone.") from exc + + @property + def period_start_utc(self) -> datetime: + """Return the inclusive start instant in UTC.""" + return self.period_start.astimezone(UTC) + + @property + def period_end_utc(self) -> datetime: + """Return the exclusive end instant in UTC.""" + return self.period_end.astimezone(UTC) + + @property + def as_of_utc(self) -> datetime: + """Return the source availability cutoff in UTC.""" + return self.as_of.astimezone(UTC) + + +@dataclass(frozen=True, slots=True) +class BatchResult: + """Report a verified Delta commit without retaining distributed data.""" + + spec: BatchSpec + input_count: int + output_count: int + commit_version: int + manifest: dict[str, Any] + replayed: bool = False diff --git a/skyulf-core/skyulf/integrations/databricks/admission.py b/skyulf-core/skyulf/integrations/databricks/admission.py new file mode 100644 index 000000000..302bb6e51 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/admission.py @@ -0,0 +1,86 @@ +"""Single-host publish admission; distributed providers must supply the same contract.""" + +import errno +import hashlib +import importlib +import os +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager +from pathlib import Path +from typing import Any, Protocol + + +class BatchConflictError(RuntimeError): + """Another writer or request owns the expected target state.""" + + +class PublishAdmission(Protocol): + """Hold an exclusive table lock until the commit receipt has been read. + + All publishers must use the same authority keyed by immutable Delta table ID. + Ownership must not expire while the context is active. This API does not + pass fencing tokens to Delta; time-limited distributed leases are unsupported. + """ + + local_only: bool + + def hold(self, table_id: str) -> AbstractContextManager[None]: + """Reject a competing writer, releasing ownership on context exit.""" + ... + + +def validate_admission(spark: Any, admission: PublishAdmission | None) -> PublishAdmission: + """Reject absent admission or local locks on a distributed runtime before I/O.""" + if admission is None or not callable(getattr(admission, "hold", None)): + raise ValueError("A shared publish admission is required.") + if admission.local_only: + master = spark.sparkContext.master + if master != "local" and not master.startswith("local["): + raise ValueError("LocalTableLock cannot coordinate distributed drivers.") + return admission + + +class LocalTableLock: + """Use OS file locks for local Spark drivers sharing one lock directory. + + This implementation is deliberately rejected for distributed Spark runtimes. + Lock files remain on disk: unlinking them can split the lock authority. + OS ownership is released when a process exits, including abnormal exits. + """ + + local_only = True + + def __init__(self, directory: str | Path) -> None: + """Bind admission to a caller-owned local directory.""" + self.directory = Path(directory).resolve() + + @contextmanager + def hold(self, table_id: str) -> Iterator[None]: + """Acquire a nonblocking exclusive lock for the whole Delta table.""" + self.directory.mkdir(parents=True, exist_ok=True) + filename = hashlib.sha256(table_id.encode()).hexdigest() + ".lock" + with (self.directory / filename).open("a+b") as handle: + windows = os.name == "nt" + api = importlib.import_module("msvcrt" if windows else "fcntl") + if windows: + if handle.tell() == 0: + handle.write(b"0") + handle.flush() + handle.seek(0) + try: + if windows: + api.locking(handle.fileno(), api.LK_NBLCK, 1) + else: + api.flock(handle.fileno(), api.LOCK_EX | api.LOCK_NB) + except OSError as exc: + if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK): + raise + raise BatchConflictError("Another publisher holds this table's admission.") from exc + try: + yield + finally: + if windows: + handle.seek(0) + api.locking(handle.fileno(), api.LK_UNLCK, 1) + else: + api.flock(handle.fileno(), api.LOCK_UN) diff --git a/skyulf-core/skyulf/integrations/databricks/batch.py b/skyulf-core/skyulf/integrations/databricks/batch.py new file mode 100644 index 000000000..7c1b4bb5f --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/batch.py @@ -0,0 +1,144 @@ +"""Explicit scheduled batch execution through the existing Spark predictor.""" + +import hashlib +import importlib +import json +from dataclasses import asdict +from importlib.metadata import version +from typing import Any + +from ...core.execution import ExecutionOptions, FrameSpec +from ...inference.bundle import InferenceBundle, _validate_bundle +from ...inference.spark import predict_spark +from ._contracts import BatchResult, BatchSpec, table_name +from .admission import PublishAdmission, validate_admission +from .delta import history, publish_replace_period, table_identity + +__all__ = ["BatchResult", "BatchSpec", "run_batch"] + + +def run_batch( + spark: Any, + spec: BatchSpec, + *, + source: str, + bundle: InferenceBundle, + options: ExecutionOptions, + admission: PublishAdmission | None = None, +) -> BatchResult: + """Score a pinned Delta snapshot and commit a period under explicit admission. + + Source is a Delta table name, not an arbitrary mutable DataFrame. Its recorded + commit must precede ``as_of``. This proves snapshot availability, not temporal + correctness of upstream feature joins. The caller binds a concrete registry + version to ``model_digest`` when constructing the spec. Both existing Spark + inference modes are supported. Tables and Spark sessions remain caller-owned. + """ + if not isinstance(options, ExecutionOptions) or options.engine != "spark": + raise ValueError("run_batch requires ExecutionOptions(engine='spark').") + if not isinstance(spec, BatchSpec): + raise TypeError("spec must be BatchSpec.") + admission = validate_admission(spark, admission) + table_name(source) + _validate_bundle(bundle, options) + if bundle.semantic_digest != spec.model_digest: + raise ValueError("Bundle digest differs from the selected model identity.") + runtime_version = version("skyulf-core") + if spec.code_version != runtime_version: + raise ValueError("code_version differs from the installed skyulf-core runtime.") + if bundle.input_stage != "raw": + raise ValueError("Spark batch inference requires a raw bundle.") + source_id = table_identity(spark, source) + if source_id == table_identity(spark, spec.output_table): + raise ValueError("Batch source and output table must be different.") + functions = importlib.import_module("pyspark.sql.functions") + snapshot = ( + history(spark, source) + .where(functions.col("version") == spec.source_version) + .select(functions.unix_micros("timestamp").alias("committed_us")) + .first() + ) + if snapshot is None or snapshot.committed_us > int(spec.as_of_utc.timestamp() * 1_000_000): + raise ValueError("Source snapshot was not available at as_of or its history expired.") + frame = spark.read.format("delta").option("versionAsOf", spec.source_version).table(source) + if table_identity(spark, source) != source_id: + raise ValueError("Source table was replaced while pinning the snapshot.") + period = frame[spec.period_column] + if frame.schema[spec.period_column].dataType.typeName() != "timestamp": + raise ValueError("period_column requires Spark timestamp, not a string/date/timestamp_ntz.") + if frame.where(period.isNull()).limit(1).count(): + raise ValueError("Source period_column contains null timestamps.") + selected = frame.where( + (period >= functions.lit(spec.period_start_utc)) + & (period < functions.lit(spec.period_end_utc)) + ) + input_count = selected.count() + if not input_count and not spec.allow_empty: + raise ValueError("Empty period replacement requires allow_empty=True.") + output_names = {column.name.lower() for column in bundle.manifest.output_schema} + if spec.period_column.lower() in output_names: + raise ValueError("period_column collides with a model output column.") + predictions = predict_spark( + selected, + bundle, + frame_spec=FrameSpec(row_keys=spec.row_keys), + options=options, + mode=spec.mode, + ) + output = predictions.join( + selected.select(*spec.row_keys, spec.period_column), on=list(spec.row_keys), how="inner" + ) + for name, value in ( + ("__skyulf_run_id", spec.run_id), + ("__skyulf_model_name", spec.model_name), + ("__skyulf_model_version", spec.model_version), + ): + output = output.withColumn(name, functions.lit(value)) + target = spark.table(spec.output_table) + if {f.name: f.dataType for f in output.schema} != {f.name: f.dataType for f in target.schema}: + raise ValueError("Output schema must match the precreated Delta target exactly.") + output = output.select(*target.columns).persist() + try: + output_count = output.count() + if input_count != output_count: + raise ValueError("Prediction changed source row membership.") + manifest = _manifest( + spec, source_id, source, snapshot.committed_us, input_count, output_count + ) + committed_version, recorded, replayed = publish_replace_period( + spark, output, spec, manifest=manifest, admission=admission + ) + return BatchResult( + spec, + recorded["input_count"], + recorded["output_count"], + committed_version, + recorded, + replayed, + ) + finally: + output.unpersist() + + +def _manifest( + spec: BatchSpec, + source_id: str, + source: str, + committed_us: int, + input_count: int, + output_count: int, +) -> dict[str, Any]: + """Fingerprint the complete request and retain snapshot, code and model evidence.""" + request = asdict(spec) + for key in ("period_start", "period_end", "as_of"): + request[key] = getattr(spec, key + "_utc").isoformat() + request.update(source_table_id=source_id, source_table=source) + payload = json.dumps(request, sort_keys=True, separators=(",", ":")) + return dict( + request, + request_digest=hashlib.sha256(payload.encode()).hexdigest(), + input_count=input_count, + output_count=output_count, + source_committed_us=committed_us, + source_temporal_contract="delta_snapshot_committed_by_as_of", + ) diff --git a/skyulf-core/skyulf/integrations/databricks/delta.py b/skyulf-core/skyulf/integrations/databricks/delta.py new file mode 100644 index 000000000..6f79e68ff --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/delta.py @@ -0,0 +1,131 @@ +"""Guarded Delta replacement with committed receipts and explicit retries.""" + +import importlib +import json +from typing import Any + +from ._contracts import BatchSpec, table_name +from .admission import BatchConflictError, PublishAdmission, validate_admission + +__all__ = ["BatchConflictError", "DeltaPublishError", "publish_replace_period"] + + +class DeltaPublishError(RuntimeError): + """Publication failed or its committed receipt could not be verified.""" + + +def table_identity(spark: Any, table: str) -> str: + """Read one immutable Delta table identity; targets must be provisioned explicitly.""" + detail = spark.sql(f"DESCRIBE DETAIL {table_name(table)}").first() + if detail is None or detail["format"] != "delta": + raise ValueError("Batch source and target must be existing Delta tables.") + return str(detail["id"]) + + +def history(spark: Any, table: str) -> Any: + """Expose distributed commit history without collecting it on the driver.""" + return spark.sql(f"DESCRIBE HISTORY {table_name(table)}") + + +def _receipt(spark: Any, spec: BatchSpec, manifest: dict[str, Any]) -> tuple[int, dict] | None: + """Find a bounded receipt by logical run and reject reuse for different input.""" + functions = importlib.import_module("pyspark.sql.functions") + matches = ( + history(spark, spec.output_table) + .where(functions.get_json_object("userMetadata", "$.run_id") == spec.run_id) + .select("version", "userMetadata") + .limit(2) + .collect() + ) + if not matches: + return None + if len(matches) != 1: + raise BatchConflictError("Multiple commits use the same logical run_id.") + recorded = json.loads(matches[0]["userMetadata"]) + if recorded.get("request_digest") != manifest["request_digest"]: + raise BatchConflictError("run_id was already used for a different batch request.") + return int(matches[0]["version"]), recorded + + +def publish_replace_period( + spark: Any, + frame: Any, + spec: BatchSpec, + *, + manifest: dict[str, Any], + admission: PublishAdmission, +) -> tuple[int, dict[str, Any], bool]: + """Replace a month and verify its receipt while holding whole-table admission. + + ``expected_target_version`` prevents stale publishers, including writers that + waited for admission. A recorded retry returns its original receipt without + writing, even when a later run has recomputed the same period. History and + transaction retention must cover the supported retry window. Writers outside + this admission protocol are outside the single-writer guarantee. + """ + admission = validate_admission(spark, admission) + target_id = table_identity(spark, spec.output_table) + with admission.hold(target_id): + if target_id != table_identity(spark, spec.output_table): + raise BatchConflictError("Target table was replaced during admission.") + recorded = _receipt(spark, spec, manifest) + if recorded is not None: + return recorded[0], recorded[1], True + latest = history(spark, spec.output_table).select("version").first() + if latest is None or int(latest["version"]) != spec.expected_target_version: + raise BatchConflictError("Target version changed; explicitly plan a new logical run.") + _validate_frame(frame, spec, manifest) + # A timezone offset in the literal avoids dependence on the session timezone. + start, end = spec.period_start_utc.isoformat(), spec.period_end_utc.isoformat() + predicate = ( + f"`{spec.period_column}` >= TIMESTAMP '{start}' AND " + f"`{spec.period_column}` < TIMESTAMP '{end}'" + ) + try: + ( + frame.write.format("delta") + .mode("overwrite") + .option("replaceWhere", predicate) + .option("mergeSchema", "false") + .option("txnAppId", "skyulf:" + spec.run_id) + .option("txnVersion", 0) + .option("userMetadata", json.dumps(manifest, sort_keys=True)) + .saveAsTable(spec.output_table) + ) + except Exception as exc: # noqa: BLE001 - retain Spark/Delta details as the cause + error_class = type(exc).__name__ + if "Concurrent" in error_class or "DELTA_CONCURRENT" in str(exc): + raise BatchConflictError("Delta rejected a concurrent write.") from exc + raise DeltaPublishError( + "Delta write failed; inspect the chained runtime error." + ) from exc + recorded = _receipt(spark, spec, manifest) + if recorded is None: + raise DeltaPublishError("Delta returned without a verifiable commit receipt.") + return recorded[0], recorded[1], False + + +def _validate_frame(frame: Any, spec: BatchSpec, manifest: dict[str, Any]) -> None: + """Reject null or out-of-period rows, wrong ownership and misleading row counts.""" + functions = importlib.import_module("pyspark.sql.functions") + period = frame[spec.period_column] + if frame.schema[spec.period_column].dataType.typeName() != "timestamp": + raise ValueError("period_column must be a Spark timestamp with timezone semantics.") + invalid = ( + period.isNull() + | (period < functions.lit(spec.period_start_utc)) + | (period >= functions.lit(spec.period_end_utc)) + ) + for name, expected in ( + ("__skyulf_run_id", spec.run_id), + ("__skyulf_model_name", spec.model_name), + ("__skyulf_model_version", spec.model_version), + ): + invalid = invalid | frame[name].isNull() | (frame[name] != functions.lit(expected)) + if frame.where(invalid).limit(1).count(): + raise ValueError("Output contains null/outside-period rows or invalid run metadata.") + actual = frame.count() + if actual != manifest["output_count"]: + raise ValueError("Output count does not match the batch manifest.") + if actual == 0 and not spec.allow_empty: + raise ValueError("Empty period replacement requires allow_empty=True.") diff --git a/skyulf-core/tests/integrations/conftest.py b/skyulf-core/tests/integrations/conftest.py new file mode 100644 index 000000000..0074a6eb0 --- /dev/null +++ b/skyulf-core/tests/integrations/conftest.py @@ -0,0 +1,49 @@ +"""Optional real Delta fixture shared by the batch integration tests.""" + +import importlib +import importlib.util +import os +import sys +from pathlib import Path + +import pytest + + +@pytest.fixture(scope="session") +def delta_spark(tmp_path_factory): + """Run actual Delta I/O; required lanes fail rather than silently skip.""" + if importlib.util.find_spec("delta") is None: + if os.environ.get("SKYULF_REQUIRE_DELTA") == "1": + pytest.fail("Install requirements-delta.txt and Java 17.") + pytest.skip("Delta runtime is optional; install requirements-delta.txt.") + spark_sql = importlib.import_module("pyspark.sql") + root = tmp_path_factory.mktemp("delta") + with pytest.MonkeyPatch.context() as env: + env.setenv("PYSPARK_PYTHON", sys.executable) + env.setenv("PYSPARK_DRIVER_PYTHON", sys.executable) + env.setenv("SPARK_LOCAL_IP", "127.0.0.1") + builder = ( + spark_sql.SparkSession.builder.master("local[2]") + .appName("skyulf-delta-tests") + .config("spark.ui.enabled", "false") + .config("spark.sql.session.timeZone", "UTC") + .config("spark.sql.shuffle.partitions", "2") + .config("spark.databricks.delta.snapshotPartitions", "2") + .config("spark.sql.warehouse.dir", (root / "warehouse").as_uri()) + .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") + .config( + "spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog" + ) + ) + jars_dir = os.environ.get("SKYULF_DELTA_JARS") + if jars_dir: + builder = builder.config( + "spark.jars", ",".join(str(p) for p in Path(jars_dir).glob("*.jar")) + ) + else: + builder = importlib.import_module("delta").configure_spark_with_delta_pip(builder) + session = builder.getOrCreate() + try: + yield session + finally: + session.stop() diff --git a/skyulf-core/tests/integrations/test_batch_admission.py b/skyulf-core/tests/integrations/test_batch_admission.py new file mode 100644 index 000000000..efbfb192f --- /dev/null +++ b/skyulf-core/tests/integrations/test_batch_admission.py @@ -0,0 +1,33 @@ +"""Cross-process admission checks for the local Delta harness.""" + +import os +import subprocess +import sys + + +def test_independent_process_cannot_enter_held_table_lock(tmp_path): + """Different local drivers must serialize even when periods overlap partially.""" + from skyulf.integrations.databricks.admission import LocalTableLock + + lock = LocalTableLock(tmp_path / "locks") + script = """ +import sys +from skyulf.integrations.databricks.admission import LocalTableLock, BatchConflictError +try: + with LocalTableLock(sys.argv[1]).hold("table-id"): pass +except BatchConflictError: + print("BUSY") +else: + print("ACQUIRED") +""" + with lock.hold("table-id"): + child = subprocess.run( + [sys.executable, "-c", script, str(tmp_path / "locks")], + capture_output=True, + text=True, + check=True, + env=os.environ.copy(), + ) + assert child.stdout.strip() == "BUSY" + with lock.hold("table-id"): + assert (tmp_path / "locks").is_dir() diff --git a/skyulf-core/tests/integrations/test_batch_contract.py b/skyulf-core/tests/integrations/test_batch_contract.py new file mode 100644 index 000000000..e3fee4eb2 --- /dev/null +++ b/skyulf-core/tests/integrations/test_batch_contract.py @@ -0,0 +1,124 @@ +"""Fail early on ambiguous batch identity and temporal contracts.""" + +from dataclasses import replace +from datetime import UTC, datetime +from types import SimpleNamespace +from typing import Any, cast +from zoneinfo import ZoneInfo + +import pytest + +from skyulf.core.execution import ExecutionOptions +from skyulf.integrations.databricks.batch import BatchSpec, run_batch + + +@pytest.fixture +def spec(): + """Declare concrete identities; dates are independent of scheduler time.""" + return BatchSpec( + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + as_of=datetime(2026, 2, 2, tzinfo=UTC), + row_keys=("id",), + output_table="default.predictions", + model_name="risk", + model_version="7", + source_version=0, + code_version="0.9.0", + run_id="january-v7", + model_digest="a" * 64, + expected_target_version=0, + ) + + +@pytest.mark.parametrize("field", ["period_start", "period_end", "as_of"]) +def test_naive_dates_fail(spec, field): + """Missing timezone information must not inherit the driver's timezone.""" + with pytest.raises(ValueError, match="timezone-aware"): + replace(spec, **{field: datetime(2026, 1, 1)}) + + +@pytest.mark.parametrize( + "changes", + [ + {"period_end": datetime(2025, 12, 1, tzinfo=UTC)}, + {"row_keys": ("id", "id")}, + {"row_keys": ("__skyulf_run_id",)}, + {"output_table": "default.x; DROP TABLE x"}, + {"model_version": "champion"}, + {"model_version": "-1"}, + {"source_version": True}, + {"source_version": -1}, + {"expected_target_version": -1}, + {"model_digest": "bad"}, + {"publish_mode": "append"}, + {"mode": "streaming"}, + {"run_id": ""}, + {"business_timezone": "missing/zone"}, + {"allow_empty": 1}, + ], +) +def test_invalid_contracts_fail_before_runtime(spec, changes): + """Invalid versions, names or modes cannot reach a Spark action or sink.""" + with pytest.raises((ValueError, TypeError)): + replace(spec, **changes) + + +def test_business_month_preserves_dst_instants(spec): + """UTC bounds preserve local calendar boundaries across a DST transition.""" + zone = ZoneInfo("Europe/Vilnius") + actual = replace( + spec, + period_start=datetime(2026, 3, 1, tzinfo=zone), + period_end=datetime(2026, 4, 1, tzinfo=zone), + business_timezone="Europe/Vilnius", + ) + assert actual.period_start_utc == datetime(2026, 2, 28, 22, tzinfo=UTC) + assert actual.period_end_utc == datetime(2026, 3, 31, 21, tzinfo=UTC) + + +def test_local_engine_rejected_before_reading_source(spec): + """A batch must never collect a Spark source into a local engine implicitly.""" + with pytest.raises(ValueError, match="engine='spark'"): + run_batch( + None, + spec, + source="default.source", + bundle=cast(Any, object()), + options=ExecutionOptions("pandas"), + ) + + +@pytest.mark.parametrize("master", ["local-cluster[2,1,1024]", "spark://cluster:7077"]) +def test_local_admission_cannot_protect_distributed_drivers(spec, tmp_path, master): + """A driver's local lock file must never imply distributed writer exclusion.""" + from skyulf.integrations.databricks.admission import LocalTableLock + + spark = SimpleNamespace(sparkContext=SimpleNamespace(master=master)) + with pytest.raises(ValueError, match="distributed drivers"): + run_batch( + spark, + spec, + source="default.source", + bundle=cast(Any, object()), + options=ExecutionOptions("spark"), + admission=LocalTableLock(tmp_path), + ) + + +def test_nonexistent_local_boundary_is_rejected(spec): + """A DST gap cannot silently shift the intended calendar period.""" + with pytest.raises(ValueError, match="valid local instant"): + replace(spec, period_start=datetime(2026, 3, 29, 3, 30, tzinfo=ZoneInfo("Europe/Vilnius"))) + + +def test_direct_sink_rejects_local_admission_on_distributed_runtime(spec, tmp_path): + """The lower-level writer must enforce the same admission boundary as the runner.""" + from skyulf.integrations.databricks.admission import LocalTableLock + from skyulf.integrations.databricks.delta import publish_replace_period + + spark = SimpleNamespace(sparkContext=SimpleNamespace(master="spark://cluster:7077")) + with pytest.raises(ValueError, match="distributed drivers"): + publish_replace_period( + spark, object(), spec, manifest={}, admission=LocalTableLock(tmp_path) + ) diff --git a/skyulf-core/tests/integrations/test_delta_publish.py b/skyulf-core/tests/integrations/test_delta_publish.py new file mode 100644 index 000000000..8f9886626 --- /dev/null +++ b/skyulf-core/tests/integrations/test_delta_publish.py @@ -0,0 +1,260 @@ +"""Real Delta transactions for monthly Spark batch inference.""" + +import importlib +from contextlib import contextmanager +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from importlib.metadata import version +from types import SimpleNamespace +from uuid import uuid4 + +import pandas as pd +import pytest + +from skyulf.core.execution import ExecutionOptions +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle +from skyulf.integrations.databricks.batch import BatchSpec, run_batch +from skyulf.pipeline import SkyulfPipeline + + +@pytest.fixture +def harness(delta_spark, tmp_path): + """Create test-owned source and output tables with a separate prior period.""" + from skyulf.integrations.databricks.admission import LocalTableLock + + spark = delta_spark + name = uuid4().hex + source, target = f"default.source_{name}", f"default.predictions_{name}" + data = pd.DataFrame({"x": [0.0, 1.0, 2.0], "y": [0.0, 2.0, 4.0]}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=data, test=data.head(0)), target_column="y") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + spark.createDataFrame( + [ + (1, datetime(2026, 1, 1, tzinfo=UTC), 1.0), + (2, datetime(2026, 1, 31, tzinfo=UTC), 2.0), + (3, datetime(2026, 2, 1, tzinfo=UTC), 3.0), + ], + "id long, event_time timestamp, x double", + ).write.format("delta").saveAsTable(source) + spark.createDataFrame( + [ + (9, datetime(2025, 12, 1, tzinfo=UTC), 99.0, "prior", "risk", "6"), + ], + "id long, event_time timestamp, prediction double, __skyulf_run_id string, " + "__skyulf_model_name string, __skyulf_model_version string", + ).write.format("delta").saveAsTable(target) + spec = BatchSpec( + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + as_of=datetime.now(UTC) + timedelta(minutes=10), + row_keys=("id",), + output_table=target, + model_name="risk", + model_version="7", + source_version=0, + code_version=version("skyulf-core"), + run_id="january", + model_digest=bundle.semantic_digest, + expected_target_version=0, + ) + h = SimpleNamespace( + spark=spark, + source=source, + target=target, + bundle=bundle, + spec=spec, + lock=LocalTableLock(tmp_path / "locks"), + ) + try: + yield h + finally: + spark.sql(f"DROP TABLE IF EXISTS {source}") + spark.sql(f"DROP TABLE IF EXISTS {target}") + + +def _run(h, spec=None): + """Exercise the public runner through a real Delta read and committed write.""" + return run_batch( + h.spark, + spec or h.spec, + source=h.source, + bundle=h.bundle, + options=ExecutionOptions("spark"), + admission=h.lock, + ) + + +@pytest.mark.parametrize("mode", ["native_features", "python_pipeline"]) +def test_retry_preserves_other_periods_and_predictions(harness, mode): + """Monthly retries neither duplicate rows nor overwrite December or February.""" + h = harness + spec = replace(h.spec, mode=mode) + first, second = _run(h, spec), _run(h, spec) + rows = h.spark.table(h.target).orderBy("id").collect() + assert [(r.id, round(r.prediction)) for r in rows] == [(1, 2), (2, 4), (9, 99)] + assert first.input_count == first.output_count == 2 + assert first.commit_version == second.commit_version == 1 + assert second.replayed is True + assert first.manifest["source_version"] == 0 + assert first.manifest["model_digest"] == h.bundle.semantic_digest + + +def test_stale_writer_and_reused_run_identity_fail(harness): + """Stale expectations and changed requests cannot silently replace a committed month.""" + from skyulf.integrations.databricks.delta import BatchConflictError + + h = harness + _run(h) + with pytest.raises(BatchConflictError): + _run(h, replace(h.spec, run_id="competing")) + with pytest.raises(BatchConflictError): + _run(h, replace(h.spec, model_version="8")) + assert h.spark.table(h.target).count() == 3 + + +def test_old_retry_cannot_undo_explicit_recomputation(harness): + """A replay returns the original receipt even after a newer intentional run.""" + h = harness + _run(h) + newer = _run(h, replace(h.spec, run_id="recompute", expected_target_version=1)) + old = _run(h) + assert newer.commit_version == 2 + assert old.commit_version == 1 and old.replayed + assert h.spark.table(h.target).where("id = 1").first()["__skyulf_run_id"] == "recompute" + + +def test_empty_replacement_is_explicit_and_records_a_commit(harness): + """Deleting an empty month requires opt-in and preserves a retry receipt in history.""" + h = harness + _run(h) + h.spark.table(h.source).where("id = 3").write.format("delta").mode("overwrite").saveAsTable( + h.source + ) + spec = replace(h.spec, run_id="delete-january", source_version=1, expected_target_version=1) + with pytest.raises(ValueError, match="allow_empty"): + _run(h, spec) + result = _run(h, replace(spec, allow_empty=True)) + retry = _run(h, replace(spec, allow_empty=True)) + assert result.output_count == 0 and result.commit_version == retry.commit_version == 2 + assert [r.id for r in h.spark.table(h.target).collect()] == [9] + + +@pytest.mark.parametrize( + "changes,match", + [ + ({"as_of": datetime(2020, 1, 1, tzinfo=UTC)}, "snapshot.*as_of"), + ({"model_digest": "0" * 64}, "digest"), + ({"code_version": "0.0.0"}, "code_version"), + ], +) +def test_invalid_provenance_does_not_modify_target(harness, changes, match): + """A recent snapshot, wrong model or wrong runtime cannot pretend to reproduce a run.""" + h = harness + with pytest.raises(ValueError, match=match): + _run(h, replace(h.spec, **changes)) + assert h.spark.table(h.target).count() == 1 + + +def test_missing_admission_fails_before_any_write(harness): + """A configured Delta engine alone cannot authorize competing publishers.""" + h = harness + with pytest.raises(ValueError, match="admission"): + run_batch( + h.spark, h.spec, source=h.source, bundle=h.bundle, options=ExecutionOptions("spark") + ) + assert h.spark.table(h.target).count() == 1 + + +def test_source_version_remains_pinned_after_new_source_commit(harness): + """A later source update must not change predictions for the selected snapshot.""" + h = harness + h.spark.sql(f"UPDATE {h.source} SET x = 100.0") + result = _run(h) + rows = h.spark.table(h.target).where("id < 3").orderBy("id").collect() + assert [round(row.prediction) for row in rows] == [2, 4] + assert result.manifest["source_version"] == 0 + assert h.spark.sql(f"DESCRIBE HISTORY {h.source}").first().version == 1 + + +def test_non_utc_session_preserves_period_instants(harness): + """Neither selection nor Delta replacement can reinterpret UTC as local wall time.""" + h = harness + before = h.spark.conf.get("spark.sql.session.timeZone") + try: + h.spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") + _run(h) + result = _run(h, replace(h.spec, run_id="non-utc-recompute", expected_target_version=1)) + assert result.output_count == 2 + assert sorted(r.id for r in h.spark.table(h.target).collect()) == [1, 2, 9] + finally: + h.spark.conf.set("spark.sql.session.timeZone", before) + + +@pytest.mark.parametrize("violation", ["before", "end", "null", "metadata", "count"]) +def test_sink_rejects_invalid_rows_without_modifying_target(harness, violation): + """Invalid output must fail before the real Delta transaction changes any period.""" + from skyulf.integrations.databricks.delta import publish_replace_period + + functions = importlib.import_module("pyspark.sql.functions") + h = harness + instant = { + "before": h.spec.period_start - timedelta(microseconds=1), + "end": h.spec.period_end, + "null": None, + }.get(violation, h.spec.period_start) + output = ( + h.spark.table(h.target) + .withColumn("event_time", functions.lit(instant).cast("timestamp")) + .withColumn("__skyulf_run_id", functions.lit(h.spec.run_id)) + .withColumn("__skyulf_model_version", functions.lit(h.spec.model_version)) + ) + if violation == "metadata": + output = output.withColumn("__skyulf_model_name", functions.lit(None).cast("string")) + manifest = {"output_count": 2 if violation == "count" else 1, "request_digest": "unused"} + with pytest.raises(ValueError, match="Output"): + publish_replace_period(h.spark, output, h.spec, manifest=manifest, admission=h.lock) + assert h.spark.sql(f"DESCRIBE HISTORY {h.target}").first().version == 0 + assert [r.id for r in h.spark.table(h.target).collect()] == [9] + + +def test_held_admission_rejects_publish_without_modifying_target(harness): + """A competing logical publisher cannot write while another owns the table lock.""" + from skyulf.integrations.databricks.admission import BatchConflictError + from skyulf.integrations.databricks.delta import table_identity + + h = harness + with ( + h.lock.hold(table_identity(h.spark, h.target)), + pytest.raises(BatchConflictError, match="admission"), + ): + _run(h) + assert h.spark.sql(f"DESCRIBE HISTORY {h.target}").first().version == 0 + + +def test_admission_permission_failure_preserves_target(harness): + """An authority denying admission must surface its error without publishing.""" + + class DeniedAdmission: + """Represent an external admission authority denying this caller.""" + + local_only = False + + @contextmanager + def hold(self, table_id): + """Deny access before yielding publication authority.""" + raise PermissionError("publish access denied") + yield # pragma: no cover - context manager contract + + h = harness + with pytest.raises(PermissionError, match="access denied"): + run_batch( + h.spark, + h.spec, + source=h.source, + bundle=h.bundle, + options=ExecutionOptions("spark"), + admission=DeniedAdmission(), + ) + assert h.spark.sql(f"DESCRIBE HISTORY {h.target}").first().version == 0 diff --git a/uv.lock b/uv.lock index 67b17e4c1..e998d8fb5 100644 --- a/uv.lock +++ b/uv.lock @@ -1074,6 +1074,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" }, ] +[[package]] +name = "delta-spark" +version = "4.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "importlib-metadata" }, + { name = "pyspark" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8f/4d/9670c5b109fb1c7a84814525cb116203cc36a6112eca546785d617f41a08/delta_spark-4.0.1.tar.gz", hash = "sha256:066512d723f615c9a900e1aa4d83bbc7d0f27a1703e1d5dc52606ea51b8733cc", size = 35521, upload-time = "2026-01-10T02:40:50.315Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/22/a3716bc5ea86786be5f0afd09f62b20e6a111fa2d78868e930b19367a88c/delta_spark-4.0.1-py3-none-any.whl", hash = "sha256:ae0707eda68f05c6ec20b841c8966bb1201d1a5f124d9e94e8c2232162139be8", size = 43002, upload-time = "2026-01-10T02:40:49.047Z" }, +] + [[package]] name = "deprecated" version = "1.3.1" @@ -5157,6 +5170,10 @@ all = [ { name = "vadersentiment" }, { name = "xgboost" }, ] +delta = [ + { name = "delta-spark" }, + { name = "pyspark" }, +] dev = [ { name = "build" }, { name = "hypothesis" }, @@ -5222,6 +5239,7 @@ requires-dist = [ { name = "causal-learn", marker = "extra == 'eda'", specifier = ">=0.1.3.0" }, { name = "cmaes", marker = "extra == 'all'", specifier = ">=0.10.0" }, { name = "cmaes", marker = "extra == 'tuning'", specifier = ">=0.10.0" }, + { name = "delta-spark", marker = "extra == 'delta'", specifier = ">=4.0.0,<4.1.0" }, { name = "esda", marker = "extra == 'geo'", specifier = ">=2.5.0,<3.0.0" }, { name = "geopandas", marker = "extra == 'geo'", specifier = ">=0.14.0,<1.2.0" }, { name = "h3", marker = "extra == 'geo'", specifier = ">=4.0.0,<5.0.0" }, @@ -5248,6 +5266,7 @@ requires-dist = [ { name = "pyarrow", specifier = ">=21.0.0" }, { name = "pydantic", specifier = ">=2.0.0" }, { name = "pyproj", marker = "extra == 'geo'", specifier = ">=3.6.0,<3.8.0" }, + { name = "pyspark", marker = "extra == 'delta'", specifier = ">=4.0.3,<4.1.0" }, { name = "pyspark", marker = "extra == 'spark'", specifier = ">=4.0.3,<4.1.0" }, { name = "pytest", marker = "extra == 'dev'" }, { name = "pytest-benchmark", marker = "extra == 'dev'", specifier = ">=5.0.0,<6.0.0" }, @@ -5271,7 +5290,7 @@ requires-dist = [ { name = "xgboost", marker = "extra == 'all'", specifier = ">=2.1.4" }, { name = "xgboost", marker = "extra == 'modeling-xgboost'", specifier = ">=2.1.4" }, ] -provides-extras = ["spark", "mlflow", "dev", "viz", "eda", "text", "nlp", "geo", "tuning", "preprocessing-imbalanced", "modeling-xgboost", "modeling-lightgbm", "explainability", "all"] +provides-extras = ["spark", "delta", "mlflow", "dev", "viz", "eda", "text", "nlp", "geo", "tuning", "preprocessing-imbalanced", "modeling-xgboost", "modeling-lightgbm", "explainability", "all"] [[package]] name = "slicer" From 09f3f11aeb84ef981b36db95c0c6d5b8ac8869b2 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 20:21:49 +0300 Subject: [PATCH 27/85] feat(core): load pinned registry bundles for Spark validation Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 + docs/user_guide/databricks_batch.md | 6 + docs/user_guide/mlflow_registry.md | 36 ++- .../03-mlflow-batch-delivery-plan.md | 24 +- initiatives/spark_and_mlflow/HANDOFF.md | 25 ++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 28 ++- .../spark_and_mlflow/PLATFORM_VALIDATION.md | 153 +++++++++++++ .../examples/databricks_batch_smoke.py | 206 ++++++++++++++++++ .../skyulf/integrations/mlflow/registry.py | 94 +++++++- .../test_mlflow_registry_bundle.py | 189 ++++++++++++++++ .../tests/integrations/test_platform_smoke.py | 64 ++++++ 11 files changed, 811 insertions(+), 19 deletions(-) create mode 100644 initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md create mode 100644 skyulf-core/examples/databricks_batch_smoke.py create mode 100644 skyulf-core/tests/integrations/test_mlflow_registry_bundle.py create mode 100644 skyulf-core/tests/integrations/test_platform_smoke.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 909946d15..21010ac18 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -111,6 +111,11 @@ execution, MLflow registry and Databricks delivery remain under development. deletion requires `allow_empty=True`. Real local Delta tests cover both inference modes and process-shared admission. Distributed admission and live Databricks validation remain SM-16. Includes an English guide and Delta CI lane. +- Pinned MLflow registry bundles can now be loaded directly for existing local + or Spark prediction. The loader validates the declared artifact path and + bundle identity without following a moved alias. A preliminary platform smoke + script compares a registered pandas/Polars-trained model through both Spark + modes; full live Databricks validation remains open. ### Planned scope — not yet available diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md index 76b77087a..72537e4be 100644 --- a/docs/user_guide/databricks_batch.md +++ b/docs/user_guide/databricks_batch.md @@ -10,6 +10,12 @@ Live Databricks, Unity Catalog, distributed publish admission and wheel delivery remain the SM-16 platform gate. Installing this adapter does not certify those platforms. Tracking and registry remain optional and independent of the engine. +This runner currently requires Spark. Delta itself can also be written from +pandas/Polars through [Arrow and delta-rs](https://delta-io.github.io/delta-rs/usage/writing/); a local-engine Skyulf Delta sink +with the same period/retry guarantees is planned separately as SM-15L. Choosing +Delta as the output format should not force the inference engine to be Spark. +Unity Catalog access and supported Delta features need validation for each writer. + ```mermaid flowchart LR A["Delta source: fixed version"] --> B["Select UTC period [start, end)"] diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 0e3ff4bc0..41eadd1c5 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -65,7 +65,35 @@ local tests cover this configuration validation and separate local stores; a live Databricks/Unity Catalog connection is deliberately reserved for the SM-16 platform gate. -Registry resolution does not run prediction, mutate aliases, start Spark, or -write a table. A later Spark runner downloads the concrete model artifact and -uses the existing inference-bundle contract. HTTP/SQL endpoints, scheduled -Delta delivery, and Databricks Bundle generation remain later initiative tasks. +Load the selected artifact with `load_registered_bundle`. It uses the pinned +name/version and the package's declared bundle path, rejects paths outside the +downloaded package, and checks the package/bundle digest against `resolved.digest`. +The same bundle can then be passed to `predict_local` or either Spark inference +mode, subject to their existing schema and FE capabilities. + +```python +from skyulf.integrations.mlflow.registry import load_registered_bundle + +bundle = load_registered_bundle( + resolved, + tracking_uri="sqlite:///tracking.db", + registry_uri="sqlite:///registry.db", +) +assert bundle.semantic_digest == resolved.digest +``` + +Only load trusted registry artifacts: bundle loading deserializes pickle, and +digest matching is an identity check, not authentication of an unknown producer. +Missing bundle metadata/artifacts or mismatched digests fail explicitly. A later +alias move does not redirect the pinned reference. + +The `databricks_batch_smoke.py` example logs a uniquely named test model, loads +its concrete registry version, and compares known gold predictions through both +Spark inference modes. It accepts pandas or Polars training and emits a partial +validation report. Local SQLite/Spark evidence does not certify live Unity Catalog, +wheel deployment, distributed admission, Delta publication or platform scale. + +Registry resolution/loading does not predict, mutate aliases, start Spark or +write a table. HTTP/SQL endpoints and Databricks Bundle generation remain later +initiative tasks; the monthly Spark/Delta runner has its own +[batch contract](databricks_batch.md). diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index a26a6eaf3..ebdfe26ab 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -111,9 +111,9 @@ URI çözümleme ile eşdeğer sayma, eski metotların return tipi değişmesin. ResolvedModel(name, version, model_uri, signature, digest). `register_model(model_uri, name)` explicit publish işlemidir; tahmin sırasında çağrılmaz. -- [ ] Carry-forward from SM-13: run the G2 Spark runner on the same bundle - downloaded through a concrete registry URI. If an MLflow Spark UDF is added, - reuse the existing prediction contract rather than duplicating FE. +- [x] Carry-forward from SM-13: the SM-16 preparation probe loads the bundle + selected by a concrete registry version and exercises both G2 Spark modes + against an independent gold oracle in local SQLite/Spark. Live UC remains SM-16. - [x] Alias/version aynı anda verilirse ve ikisi de yoksa açık config hatası; missing model/permission failure ile dependency failure ayrı hatalar olsun. - [x] Resolve an alias once and carry the concrete version URI through the job. @@ -226,6 +226,24 @@ def test_platform_evidence_has_concrete_versions(platform_evidence): Bu kontrol gerçek job çıktısına uygulanır; elle doldurulmuş dict platform testi değildir. **Kabul:** G4 platform kapısı: run URL/id, sürümler, parity ve tekrar yazma kanıtı. +## SM-15L — Local-engine Delta publication + +**Dependency:** SM-16. **Status:** WAIT; clarified by the user on 2026-09-22. +The SM-15 delivery covers only the Spark runner. A Delta destination must not +imply Spark inference; support for pandas/Polars publication needs its own sink. + +- [ ] Design explicit local source/target references and snapshot provenance; + do not pass filesystem paths into the Spark-only table-name contract. +- [ ] Implement an optional Arrow/delta-rs writer for supported local data sizes. + No implicit collection of distributed Spark data into pandas/Polars. +- [ ] Match period, UTC/schema, empty-result, receipt, retry and admission + guarantees using actual Delta transactions, including stale concurrent runs. +- [ ] Validate storage access, table protocol features and UC compatibility for + each supported target type. Direct path writes do not establish UC table access. +- [ ] Expose the supported engine/sink combinations before SM-20 offers them. + +This is planned work, not an available `run_batch(engine="polars")` feature. + ## SM-17 — Kalan node aileleri ve context desteği **Bağımlılık:** SM-16. **Kaynak:** rapordaki aile matrisi; diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index fac4b572d..384cfbf0a 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,12 +1,19 @@ # Session handoff - 2026-09-22 -SM-00 through SM-15 are complete. Resume with SM-16 platform preparation; +SM-00 through SM-15 are complete. SM-16 platform preparation is ACTIVE; live Databricks execution has not been validated. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-15 are complete; SM-16 is READY for platform preparation. +- SM-00 through SM-15 are complete; SM-16 local preparation is in progress. +- The registry-bundle loader and first registry-to-Spark probe are implemented. + Local validation passed 29 combined tests; the complete platform gate remains + open. A 0.9.0 wheel was built, with its checksum recorded in the platform file. +- See [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). The user will provide + the CLI profile, test namespace and compute; no workspace has been selected. +- Local-engine pandas/Polars Delta writing is tracked as SM-15L. The current + Spark writer does not implement it; templates remain SM-20. - SM-15 baseline: `4a613cb5`. Its implementation and verification are in the delivery commit containing this handoff. No live Databricks validation yet. - SM-13 starts from `67315253`; its implementation, guide and evidence are in @@ -126,9 +133,11 @@ receipt returns the old committed version even after a newer recomputation, without writing again. New computation needs a new run ID and reviewed target version. History and transaction retention must cover the allowed retry window. -Next, prepare the SM-16 wheel/job smoke and platform evidence record, including -the carried registry-to-Spark path, without creating a DAB template or endpoints. -Actual execution needs an explicitly selected runtime, permitted test namespace, -and authentication. The user retracted an accidentally pasted login command; -do not treat its host or editor-created `databricks.yml` as authorization to log -in, submit jobs or use that workspace. Those editor files remain outside SM-15. +The first SM-16 registry-to-Spark smoke and platform evidence file are prepared; +see that file for the current wheel checksum and local evidence. After the user +supplies the CLI profile, permitted test namespace and compute, prepare the +reviewable job request and finish the remaining platform gates. Databricks CLI +1.17.0 is installed but absent from the current shell PATH; use its existing +WinGet executable or a refreshed shell. The user confirmed `databricks.yml` is +not needed in this repository; it is absent. DAB/templates and endpoints remain +later work. Do not reuse the previously retracted login host as authorization. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 7de2f0ca9..54688d3b8 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-22. **SM-00–SM-15 complete; SM-16 is next. Target: 0.9.0.** +Updated: 2026-09-22. **SM-00–SM-15 complete; SM-16 ACTIVE. Target: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-16. @@ -27,7 +27,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-13 | MLflow model packaging | SM-12 | DONE | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | -| SM-16 | Gerçek Databricks kapısı | SM-15 | READY | Platform setup, distributed admission, job/run evidence | +| SM-16 | Gerçek Databricks kapısı | SM-15 | ACTIVE | Local preparation; profile/test namespace/compute pending | +| SM-15L | Local pandas/Polars Delta sink | SM-16 | WAIT | Same period/retry guarantees; real local writer and UC access tests | | SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | | SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | | SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | @@ -35,6 +36,11 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. ## Detay planlar +- Active SM-16 preparation and remaining gates: [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). +- SM-15 currently provides the Spark writer only. The user's local-engine + Delta requirement is tracked separately as SM-15L and must be satisfied before + SM-20 offers that template combination. Template work remains last. + - SM-00–SM-07: [Core/Spark](01-core-spark-plan.md) - SM-08–SM-11: [Inference](02-inference-plan.md) - SM-12–SM-20: [MLflow/batch/son teslimatlar](03-mlflow-batch-delivery-plan.md) @@ -47,6 +53,24 @@ gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. +## SM-16 — 2026-09-22 local preparation, still ACTIVE + +- Baseline `d43e74ca`. Added a trusted pinned registry-bundle loader and a + templates-free `databricks_batch_smoke.py` probe with pandas/Polars training, + an independent numerical oracle and both existing Spark inference modes. +- Combined local registry/worker gate: **29 passed**, no skips, MLflow 3.16.1 / + PySpark 4.0.3 / Python 3.12.3. Base regression: **77 passed, 28 optional skips**. + Ruff/format, repository Ty and strict MkDocs passed. Wheel built locally; + checksum, exact commands and remaining gates are in + [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). +- Databricks plugin installed; CLI **1.17.0** verified. No profile was selected, + no authentication performed and no workspace resources created. The user + will provide the test namespace and compute. `databricks.yml` is absent as + requested; DAB/template generation remains later work. +- SM-16 is **not DONE**: live UC/job evidence, clean worker wheel deployment, + distributed admission, Delta platform retries/permissions and scale are open. + SM-15L separately tracks the newly clarified local-engine Delta sink requirement. + ## SM-15 — 2026-09-22 validation record - Baseline `4a613cb5`; branch `090`. The delivery commit containing this record diff --git a/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md b/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md new file mode 100644 index 000000000..b3eba5860 --- /dev/null +++ b/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md @@ -0,0 +1,153 @@ +# SM-16 platform validation + +Status: **ACTIVE — local preparation; no live Databricks evidence yet**. +Baseline: `d43e74ca`, branch `090`, target release `0.9.0`. + +## Local preparation evidence — 2026-09-22 + +- Added `load_registered_bundle` with local registry tests: concrete version + loading after alias movement, separate stores, preservation of unrelated + MLflow state, declared artifact paths and rejection of missing/mismatched + metadata, missing directories and escaping paths. +- Combined local Linux/WSL gate: **29 passed**, no skips, 107.39s (10 existing + registry tests, 15 loader tests and 4 smoke tests). MLflow **3.16.1**, Python + **3.12.3**, PySpark **4.0.3**, Delta fixture **4.0.0**, Java **17.0.20.1**. + The worker probe used Polars training, then loaded the registered model and + exercised both Spark modes. Local gold tests cover pandas and Polars training. +- Base bundle/integration regression: **77 passed, 28 skipped**; optional + MLflow/Delta tests are absent in that environment. A known Windows physical + core detection warning was emitted. Scoped Ruff/format, repository Ty, + `--help` without optional dependencies, and strict MkDocs passed. +- Independent code review found no blocker. The integration probe's experiment + artifact root was moved under its temporary directory before the final gate. +- Wheel built locally: `.cache/sm16-dist/skyulf_core-0.9.0-py3-none-any.whl`. + SHA-256: `ede03a571bf3de480e1acca8ddd9c5179efd832906c410f4a0a98f50709b4779`. + This proves a local build only; the wheel has not been installed on Databricks + workers, uploaded or deployed. Rebuild/recompute the hash after code changes. + +Exact local commands: + +```powershell +wsl -d Ubuntu -- bash .cache/sm15-linux-run.sh -m pytest skyulf-core/tests/integrations/test_mlflow_registry.py skyulf-core/tests/integrations/test_mlflow_registry_bundle.py skyulf-core/tests/integrations/test_platform_smoke.py -q -p no:cacheprovider -o addopts= --basetemp /tmp/sm16-registry-reviewed --tb=short +.venv/Scripts/python.exe -m pytest skyulf-core/tests/integrations skyulf-core/tests/spark/test_inference_bundle.py -q -o addopts= --basetemp .cache/sm16-base-final --tb=short +uv build --wheel --out-dir .cache/sm16-dist skyulf-core +.venv/Scripts/python.exe -m mkdocs build --strict --site-dir .cache/sm16-docs +``` + +For another Linux test environment, install `requirements-delta.txt` and +`mlflow==3.16.1` with `uv pip`, then run the same three test modules with +`SKYULF_REQUIRE_DELTA=1`. The local wrapper selects the prepared Java runtime +and cached official Delta jars; those are test-environment details, not a +Databricks runtime dependency profile. + +## Confirmed local tooling + +- Databricks agent-skills plugin `0.2.20` is installed. Its `databricks-core` + and `databricks-jobs` instructions were inspected. +- Databricks CLI **1.17.0** was verified with `--version` from the existing + WinGet installation. It is absent from this agent shell's PATH, so an + explicit executable path is needed until that shell is refreshed. +- The repository root has no `databricks.yml`. The user confirmed it is not + needed here. No bundle, deployment or authentication was created. +- The user will provide the CLI profile, permitted test `catalog.schema` + and compute selection. None has been inferred from an earlier pasted host. + +## Stage 1: registry-to-Spark probe + +Script: [databricks_batch_smoke.py](../../skyulf-core/examples/databricks_batch_smoke.py). + +1. Fit a tiny pandas or Polars pipeline: mean SimpleImputer, StandardScaler, + linear regression with a known `y = 2*x` numerical oracle. +2. Log and register a uniquely suffixed test model through explicit MLflow + stores. Retain the created model and run for inspection; no alias is moved. +3. Resolve the created version and download its declared Skyulf bundle. + Compare the package and bundle digests with the pinned model identity. +4. Compare local inference and both Spark inference modes by row key. The gold + predictions are `[-2, 3, 5]`; the middle result uses the training mean `1.5`. +5. Produce a small report with runtime versions, installed module provenance, + model/run identity and individual check results. It explicitly records + `platform_gate_complete: false` and the gates still outstanding. + +Only the fixed three-row probe is collected. This is not a scale/RSS test or a +production batch collector. A successful probe is not proof of Delta delivery, +distributed admission, UC permission handling or clean wheel deployment. + +After choosing a compatible runtime and installing the built wheel in the job, +the script can be run as a Python task or from an explicitly prepared notebook: + +```bash +python databricks_batch_smoke.py \ + --model-prefix TEST_CATALOG.TEST_SCHEMA.skyulf_sm16 \ + --experiment-name /Workspace/APPROVED_TEST_EXPERIMENT \ + --tracking-uri databricks \ + --registry-uri databricks-uc \ + --training-engine polars \ + --output /tmp/skyulf-sm16-evidence.json +``` + +These are placeholders, not approved destinations. The caller must select the +Spark environment; the script never creates a local Spark master inside a +Databricks job. Both `pandas` and `polars` are training options. Outputs use the +same fitted model in Spark inference. The script prints each uniquely created +model name before registration, so failed probes can still be inspected and +their test-owned resources removed explicitly. Preserve the evidence before +cleaning up; never delete other models, experiments, tables or aliases. + +`load_registered_bundle` consumes trusted MLflow packages only: payloads may +contain pickle. Digests detect mismatched artifacts; they do not authenticate +an untrusted producer. Downloads use explicit stores and the pinned version, +including when a previously resolved alias has moved. + +## Full platform gate still required + +| Gate | Required evidence | Current state | +| --- | --- | --- | +| Selected environment | Profile, workspace, compute ID/type, DBR/Python/Spark/MLflow/Arrow | Awaiting user selection | +| Package delivery | Exact wheel/checksum, installed distribution on clean driver/workers | Pending | +| Real UC round-trip | Concrete model version, alias pinning and trusted bundle download | Pending live execution | +| Spark parity | Gold data, both FE modes, key-based predictions, job run ID/URL | Local probe preparation | +| Monthly publication | Real test Delta tables, snapshots, commits, replay, other periods preserved | SM-15 local evidence only | +| Distributed admission | Shared authority, ownership through commit, competing-job result | Not implemented/validated | +| UC permissions | Actual denied and allowed access in the approved namespace | Pending | +| Scale | Synthetic distributed dataset, runtime and driver/worker memory evidence | Pending | + +Do not use `LocalTableLock` on a distributed Databricks driver. Limiting one +job's concurrent runs does not coordinate other jobs or external writers. +An expiring lease without sink-enforced fencing is insufficient. The platform +admission choice remains an explicit design/validation step after runtime +selection, not a no-op context manager pretending to own a distributed lock. + +## DAB and templates + +A job can be submitted through the CLI/SDK without a bundle. A bundle can be +written directly in YAML or use Python resource definitions; a reusable project +template is optional. Even Python-defined bundle resources use a root +`databricks.yml` entry point. A model artifact does not automatically generate +the code, compute selection, permissions and job definition needed for a bundle. + +For SM-16, prepare the script/wheel and use a reviewed job request after the +user selects the platform. Reusable templates remain SM-20. A future generated +project can contain its own `databricks.yml`; the Skyulf library repository does +not need one for these tests. + +References: [Python bundle resources](https://docs.databricks.com/aws/en/dev-tools/bundles/python), +[CLI bundle commands](https://docs.databricks.com/aws/en/dev-tools/cli/bundle-commands). + +## Local-engine Delta follow-up + +The SM-15 runner currently requires Spark. Delta itself does not require Spark: +pandas/Polars can write through Arrow and `delta-rs`. This is a separate sink +implementation, not an implicit conversion of a Spark dataset to local memory. + +Track **SM-15L** before template support advertises local-engine Delta output: + +- Separate inference engine (`pandas`, `polars`, `spark`) from the output sink. +- Define explicit local source snapshot provenance and memory limits. +- Carry over period replacement, schema/UTC rules, empty protection, durable + receipts, retry identity and single-writer admission with real transaction tests. +- Establish supported Delta protocol features and storage credentials. Writing + a filesystem/object-store Delta path does not by itself prove that a Unity + Catalog managed table can be written through that path. +- Validate UC access separately; fail unsupported combinations explicitly. + +Reference: [delta-rs writing](https://delta-io.github.io/delta-rs/usage/writing/). diff --git a/skyulf-core/examples/databricks_batch_smoke.py b/skyulf-core/examples/databricks_batch_smoke.py new file mode 100644 index 000000000..56a03d417 --- /dev/null +++ b/skyulf-core/examples/databricks_batch_smoke.py @@ -0,0 +1,206 @@ +"""Validate registry-to-Spark parity before attempting the complete platform gate. + +Run in a caller-selected Spark environment with a compatible installed Skyulf +wheel and MLflow. This probe creates a uniquely named test model and tracking +run, retains them for inspection, and never modifies an existing alias. It does +not deploy jobs, coordinate distributed publishers or write Delta tables. +""" + +import argparse +import importlib +import json +import os +import platform +import re +from importlib.metadata import distribution, version +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import numpy as np +import pandas as pd +import polars as pl + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.data.dataset import SplitDataset +from skyulf.inference import build_bundle, predict_local, predict_spark +from skyulf.pipeline import SkyulfPipeline + + +def build_gold_bundle(engine: str): + """Fit mean imputation and scaling with an independently known y=2*x oracle.""" + if engine not in ("pandas", "polars"): + raise ValueError("training_engine must be pandas or polars.") + training = pd.DataFrame({"x": [0.0, 1.0, 2.0, 3.0], "target": [0.0, 2.0, 4.0, 6.0]}) + if engine == "polars": + training = pl.from_pandas(training) + pipeline = SkyulfPipeline( + { + "preprocessing": [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["x"], "strategy": "mean"}, + }, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}, + ], + "modeling": {"type": "linear_regression"}, + } + ) + pipeline.fit(SplitDataset(train=training, test=training.head(0)), target_column="target") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + return bundle, pd.DataFrame({"x": [-1.0, np.nan, 2.5]}) + + +def check_predictions(rows: list[tuple[int, float]]) -> None: + """Compare keyed gold predictions, including the training-only imputed mean.""" + ordered = sorted(rows) + if [row[0] for row in ordered] != [101, 102, 103]: + raise AssertionError("Prediction keys differ from the three gold input keys.") + np.testing.assert_allclose( + [row[1] for row in ordered], [-2.0, 3.0, 5.0], rtol=1e-10, atol=1e-10 + ) + + +def installation_evidence() -> dict[str, Any]: + """Report the actual imported distribution without claiming a wheel was installed.""" + package = distribution("skyulf-core") + direct = json.loads(package.read_text("direct_url.json") or "{}") + import skyulf + + return { + "module_path": str(Path(skyulf.__file__).resolve()), + "editable": bool(direct.get("dir_info", {}).get("editable", False)), + "version": package.version, + } + + +def run_smoke( + spark: Any, + *, + model_prefix: str, + experiment_name: str, + tracking_uri: str, + registry_uri: str, + training_engine: str = "pandas", +) -> dict[str, Any]: + """Publish a test-owned bundle, download its pinned version and exercise workers.""" + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}", model_prefix): + raise ValueError("model_prefix must use simple registry identifiers.") + if len(model_prefix.split(".")) not in (1, 3): + raise ValueError("model_prefix must be model or catalog.schema.model.") + if registry_uri.startswith("databricks-uc") and len(model_prefix.split(".")) != 3: + raise ValueError("Unity Catalog requires catalog.schema.model_prefix.") + from skyulf.integrations.mlflow.model import log_model + from skyulf.integrations.mlflow.registry import ( + load_registered_bundle, + register_model, + resolve_model, + ) + from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run + + original, gold = build_gold_bundle(training_engine) + check_predictions( + list(zip([101, 102, 103], predict_local(gold, original).prediction, strict=True)) + ) + model_name = model_prefix + "_" + uuid4().hex + print(f"Test-owned model (retained for inspection): {model_name}", flush=True) + config = TrackingConfig( + enabled=True, tracking_uri=tracking_uri, experiment_name=experiment_name + ) + with track_run(config, run_name="skyulf-sm16-registry-spark") as run: + uri = log_model( + original, run_id=run.run_id, artifact_path="model", tracking_uri=tracking_uri + ) + published = register_model( + uri, model_name, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + resolved = resolve_model( + model_name, + version=published.version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + downloaded = load_registered_bundle( + resolved, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + if downloaded.semantic_digest != original.semantic_digest: + raise AssertionError("Registry round-trip changed the test model digest.") + check_predictions( + list(zip([101, 102, 103], predict_local(gold, downloaded).prediction, strict=True)) + ) + frame = spark.createDataFrame( + [(101, -1.0), (102, None), (103, 2.5)], "id long, x double" + ).repartition(2) + checks = {"local_gold": True} + for mode in ("native_features", "python_pipeline"): + output = predict_spark( + frame, + downloaded, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark", python_batch_rows=2), + mode=mode, + ) + # This fixed three-row probe is bounded; production batch data stays distributed. + check_predictions([(row.id, row.prediction) for row in output.limit(4).collect()]) + checks[mode] = True + run.log_metrics({"gold_rows": 3.0, "spark_modes_passed": 2.0}) + return { + "stage": "registry_spark_parity", + "platform_gate_complete": False, + "checks": checks, + "remaining_gates": [ + "wheel_on_clean_workers", + "uc_alias_pinning", + "delta_publication", + "distributed_admission", + "uc_permissions", + "scale_measurement", + ], + "model_name": resolved.name, + "model_version": resolved.version, + "model_uri": resolved.model_uri, + "model_digest": downloaded.semantic_digest, + "mlflow_run_id": run.run_id, + "training_engine": training_engine, + "runtime": { + "python": platform.python_version(), + "spark": spark.version, + "mlflow": version("mlflow"), + "pyarrow": version("pyarrow"), + "pandas": version("pandas"), + "polars": version("polars"), + "scikit_learn": version("scikit-learn"), + "databricks_runtime": os.environ.get("DATABRICKS_RUNTIME_VERSION"), + }, + "installation": installation_evidence(), + } + + +def main() -> None: + """Run only against explicitly selected stores and a caller-configured Spark runtime.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--model-prefix", required=True) + parser.add_argument("--experiment-name", required=True) + parser.add_argument("--tracking-uri", required=True) + parser.add_argument("--registry-uri", required=True) + parser.add_argument("--training-engine", choices=("pandas", "polars"), default="pandas") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + spark = importlib.import_module("pyspark.sql").SparkSession.builder.getOrCreate() + report = run_smoke( + spark, + model_prefix=args.model_prefix, + experiment_name=args.experiment_name, + tracking_uri=args.tracking_uri, + registry_uri=args.registry_uri, + training_engine=args.training_engine, + ) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print( + f"Registry/Spark stage passed; complete platform gate remains pending. Report: {args.output}" + ) + + +if __name__ == "__main__": + main() diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py index a0e55c569..742d10f1a 100644 --- a/skyulf-core/skyulf/integrations/mlflow/registry.py +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -10,8 +10,11 @@ from __future__ import annotations from dataclasses import dataclass -from pathlib import Path -from typing import Any +from pathlib import Path, PureWindowsPath +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ...inference.bundle import InferenceBundle __all__ = [ "RegistryAccessError", @@ -20,6 +23,7 @@ "RegistryModelNotFoundError", "RegistryOperationError", "ResolvedModel", + "load_registered_bundle", "register_model", "resolve_model", ] @@ -56,6 +60,92 @@ class ResolvedModel: digest: str | None +def load_registered_bundle( + resolved: ResolvedModel, + *, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> InferenceBundle: + """Load a trusted packaged bundle using a previously pinned registry version. + + The client uses explicit stores without changing MLflow's global URIs or + active run. The concrete name/version selects the package even if an alias + has since moved. Its pyfunc artifact map locates the bundle; package and + bundle digests must agree with the resolved identity. + + This operation deserializes pickle. Only use trusted registry artifacts; + digest checks do not authenticate producers. Local MLflow stores are covered + by integration tests; remote Unity Catalog execution requires deployment + validation. + """ + if not isinstance(resolved, ResolvedModel): + raise TypeError("resolved must be a ResolvedModel.") + _validate_registry_options(resolved.name, tracking_uri, registry_uri) + if ( + not isinstance(resolved.version, str) + or not resolved.version.isascii() + or not resolved.version.isdigit() + or int(resolved.version) <= 0 + or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" + ): + raise ValueError("resolved must identify a concrete positive model version.") + if not isinstance(resolved.digest, str) or not resolved.digest.strip(): + raise ValueError("resolved must include the Skyulf bundle digest.") + mlflow = _require_mlflow() + client = _make_client(mlflow, tracking_uri, registry_uri) + try: + version = client.get_model_version(resolved.name, resolved.version) + source = getattr(version, "source", None) + artifact_uri = source if isinstance(source, str) and source else resolved.model_uri + local_path = mlflow.artifacts.download_artifacts( + artifact_uri=artifact_uri, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + model = mlflow.models.Model.load(Path(local_path)) + except Exception as exc: # noqa: BLE001 - translate registry and artifact transport failures + raise _translate_error(exc, name=resolved.name, version=resolved.version) from exc + metadata = model.metadata or {} + if metadata.get("skyulf_bundle_digest") != resolved.digest: + raise ValueError( + "Packaged Skyulf bundle digest is missing or differs from resolved digest." + ) + bundle_path = _packaged_bundle_path(Path(local_path), model.flavors) + from ...inference.bundle import ( # noqa: PLC0415 - lazy bundle dependency + load_bundle, + ) + + bundle = load_bundle(bundle_path) + if bundle.semantic_digest != resolved.digest: + raise ValueError("Loaded Skyulf bundle digest differs from resolved digest.") + return bundle + + +def _packaged_bundle_path(package: Path, flavors: dict[str, Any]) -> Path: + """Find the declared bundle directory and reject paths escaping the package.""" + try: + relative = flavors["python_function"]["artifacts"]["bundle"]["path"] + except (KeyError, TypeError) as exc: + raise ValueError("MLflow model is missing the Skyulf bundle artifact path.") from exc + if ( + not isinstance(relative, str) + or not relative.strip() + or Path(relative).is_absolute() + or PureWindowsPath(relative).anchor + or ".." in PureWindowsPath(relative).parts + ): + raise ValueError( + "Skyulf bundle artifact path must be relative and contained in the package." + ) + root = package.resolve() + candidate = (root / relative).resolve() + if not candidate.is_relative_to(root) or candidate == root: + raise ValueError("Skyulf bundle artifact path must be contained in the package.") + if not candidate.is_dir(): + raise ValueError("MLflow model is missing the Skyulf bundle artifact directory.") + return candidate + + def resolve_model( name: str, *, diff --git a/skyulf-core/tests/integrations/test_mlflow_registry_bundle.py b/skyulf-core/tests/integrations/test_mlflow_registry_bundle.py new file mode 100644 index 000000000..8fe91801b --- /dev/null +++ b/skyulf-core/tests/integrations/test_mlflow_registry_bundle.py @@ -0,0 +1,189 @@ +"""Local SQLite coverage for loading pinned registered inference bundles.""" + +from __future__ import annotations + +import shutil +from dataclasses import replace +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle, predict_local + +mlflow = pytest.importorskip("mlflow") +from skyulf.integrations.mlflow import registry +from skyulf.integrations.mlflow.model import log_model +from skyulf.pipeline import SkyulfPipeline + + +@pytest.fixture(scope="module") +def published(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Any]: + """Package two different fitted models in separate tracking and registry stores.""" + root = tmp_path_factory.mktemp("registered-bundle") + tracking_uri = f"sqlite:///{(root / 'tracking.db').as_posix()}" + registry_uri = f"sqlite:///{(root / 'registry.db').as_posix()}" + client = mlflow.MlflowClient(tracking_uri=tracking_uri, registry_uri=registry_uri) + experiment = client.create_experiment( + "bundle-load", artifact_location=(root / "artifacts").as_uri() + ) + for slope in (2.0, 3.0): + frame = pd.DataFrame({"x": np.arange(8, dtype="float64"), "target": np.arange(8) * slope}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=frame, test=frame.head(0)), target_column="target") + bundle = build_bundle(pipeline, input_stage="raw", feature_order=("x",)) + run = client.create_run(experiment) + uri = log_model( + bundle, run_id=run.info.run_id, artifact_path="model", tracking_uri=tracking_uri + ) + registry.register_model(uri, "pinned", tracking_uri=tracking_uri, registry_uri=registry_uri) + client.set_terminated(run.info.run_id) + resolved = registry.resolve_model( + "pinned", version="1", tracking_uri=tracking_uri, registry_uri=registry_uri + ) + source = client.get_model_version("pinned", "1").source + package = Path( + mlflow.artifacts.download_artifacts( + artifact_uri=source, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + ) + return { + "client": client, + "tracking_uri": tracking_uri, + "registry_uri": registry_uri, + "resolved": resolved, + "package": package, + } + + +def _load(published: dict[str, Any], resolved: registry.ResolvedModel | None = None) -> Any: + """Load through the public boundary using the fixture's explicit stores.""" + return registry.load_registered_bundle( + resolved or published["resolved"], + tracking_uri=published["tracking_uri"], + registry_uri=published["registry_uri"], + ) + + +def test_load_pinned_bundle_after_alias_moves(published: dict[str, Any]) -> None: + """Moving an alias must not replace the artifact already selected for a job.""" + client = published["client"] + client.set_registered_model_alias("pinned", "champion", "1") + resolved = registry.resolve_model( + "pinned", + alias="champion", + tracking_uri=published["tracking_uri"], + registry_uri=published["registry_uri"], + ) + client.set_registered_model_alias("pinned", "champion", "2") + loaded = _load(published, resolved) + output = predict_local(pd.DataFrame({"x": [1.0, 4.0]}), loaded) + assert loaded.semantic_digest == resolved.digest + np.testing.assert_allclose(output["prediction"], [2.0, 8.0]) + + +def test_explicit_stores_preserve_global_uris_and_active_run( + published: dict[str, Any], tmp_path: Path +) -> None: + """Loading must not use or mutate an unrelated caller's fluent MLflow state.""" + old_tracking, old_registry = mlflow.get_tracking_uri(), mlflow.get_registry_uri() + caller_uri = f"sqlite:///{(tmp_path / 'caller.db').as_posix()}" + try: + mlflow.set_tracking_uri(caller_uri) + mlflow.set_registry_uri(caller_uri) + with mlflow.start_run() as active: + loaded = _load(published) + assert mlflow.active_run().info.run_id == active.info.run_id + assert mlflow.get_tracking_uri() == caller_uri + assert mlflow.get_registry_uri() == caller_uri + assert loaded.semantic_digest == published["resolved"].digest + finally: + mlflow.set_tracking_uri(old_tracking) + mlflow.set_registry_uri(old_registry) + + +@pytest.mark.parametrize( + "changes", + [ + {"digest": None}, + {"digest": ""}, + {"version": "champion"}, + {"model_uri": "models:/pinned@champion"}, + ], +) +def test_reject_incomplete_or_unpinned_reference( + published: dict[str, Any], changes: dict[str, Any] +) -> None: + """A caller cannot bypass concrete version and digest identity requirements.""" + with pytest.raises(ValueError, match="digest|concrete|version"): + _load(published, replace(published["resolved"], **changes)) + + +def test_reject_resolved_digest_mismatch(published: dict[str, Any]) -> None: + """A changed package cannot silently replace the digest resolved earlier.""" + with pytest.raises(ValueError, match="digest"): + _load(published, replace(published["resolved"], digest="0" * 64)) + + +def _register_copy(published: dict[str, Any], package: Path) -> registry.ResolvedModel: + """Register a test-owned package copy without changing the shared model artifacts.""" + name = package.parent.name + client = published["client"] + client.create_registered_model(name) + client.create_model_version(name, package.as_uri()) + return replace(published["resolved"], name=name, model_uri=f"models:/{name}/1") + + +def test_uses_packaged_artifact_path(published: dict[str, Any], tmp_path: Path) -> None: + """The loader follows MLmodel's actual artifact map rather than a guessed directory.""" + package = Path(shutil.copytree(published["package"], tmp_path / "model")) + model = mlflow.models.Model.load(str(package)) + artifact = model.flavors["python_function"]["artifacts"]["bundle"] + (package / artifact["path"]).rename(package / "relocated") + artifact["path"] = "relocated" + model.save(str(package / "MLmodel")) + loaded = _load(published, _register_copy(published, package)) + assert loaded.semantic_digest == published["resolved"].digest + + +@pytest.mark.parametrize( + "damage", + [ + "metadata-digest", + "bundle-digest", + "missing-artifact", + "missing-directory", + "traversal", + "absolute", + "windows-drive", + ], +) +def test_reject_invalid_packaged_bundle( + published: dict[str, Any], tmp_path: Path, damage: str +) -> None: + """Missing identity and unsafe artifact paths fail before serving a registered model.""" + package = Path(shutil.copytree(published["package"], tmp_path / "model")) + model = mlflow.models.Model.load(str(package)) + artifact = model.flavors["python_function"]["artifacts"]["bundle"] + resolved = _register_copy(published, package) + if damage == "metadata-digest": + model.metadata.pop("skyulf_bundle_digest") + elif damage == "bundle-digest": + model.metadata["skyulf_bundle_digest"] = "0" * 64 + resolved = replace(resolved, digest="0" * 64) + elif damage == "missing-artifact": + model.flavors["python_function"]["artifacts"].pop("bundle") + elif damage == "missing-directory": + artifact["path"] = "missing" + else: + artifact["path"] = { + "traversal": "../outside", + "absolute": str(tmp_path.resolve()), + "windows-drive": "C:\\outside", + }[damage] + model.save(str(package / "MLmodel")) + with pytest.raises(ValueError, match="digest|artifact|relative|contained"): + _load(published, resolved) diff --git a/skyulf-core/tests/integrations/test_platform_smoke.py b/skyulf-core/tests/integrations/test_platform_smoke.py new file mode 100644 index 000000000..bdb05d793 --- /dev/null +++ b/skyulf-core/tests/integrations/test_platform_smoke.py @@ -0,0 +1,64 @@ +"""Exercise the standalone platform probe without claiming a live Databricks gate.""" + +import importlib.util +import sys +from pathlib import Path + +import numpy as np +import pytest + + +@pytest.fixture +def smoke_module(): + """Load the same script that will be uploaded as a Databricks Python task.""" + path = Path(__file__).parents[2] / "examples" / "databricks_batch_smoke.py" + spec = importlib.util.spec_from_file_location("skyulf_platform_smoke", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_gold_bundle_has_independent_expected_predictions(smoke_module, engine): + """A known numerical oracle catches matching but incorrect local/Spark predictions.""" + from skyulf.inference import predict_local + + bundle, gold = smoke_module.build_gold_bundle(engine) + predicted = predict_local(gold, bundle) + np.testing.assert_allclose(predicted.prediction, [-2.0, 3.0, 5.0], atol=1e-10) + assert bundle.input_stage == "raw" + + +def test_parity_rejects_duplicate_or_missing_keys(smoke_module): + """Equal prediction values must not conceal lost or duplicated source identities.""" + with pytest.raises(AssertionError, match="keys"): + smoke_module.check_predictions([(101, -2.0), (101, 3.0), (103, 5.0)]) + + +def test_registry_to_both_spark_modes(delta_spark, smoke_module, tmp_path): + """A downloaded registered model must reach actual Python workers in both FE modes.""" + mlflow = pytest.importorskip("mlflow") + uri = f"sqlite:///{(tmp_path / 'tracking.db').as_posix()}" + registry = f"sqlite:///{(tmp_path / 'registry.db').as_posix()}" + client = mlflow.MlflowClient(tracking_uri=uri, registry_uri=registry) + client.create_experiment("sm16-test", artifact_location=(tmp_path / "artifacts").as_uri()) + report = smoke_module.run_smoke( + delta_spark, + model_prefix="skyulf_sm16_test", + experiment_name="sm16-test", + tracking_uri=uri, + registry_uri=registry, + training_engine="polars", + ) + assert report["stage"] == "registry_spark_parity" + assert report["model_version"] == "1" + assert report["model_name"].startswith("skyulf_sm16_test_") + assert report["checks"] == { + "local_gold": True, + "native_features": True, + "python_pipeline": True, + } + assert report["platform_gate_complete"] is False + assert "delta_publication" in report["remaining_gates"] From 311547fc8ab7b69d71fbc87ea6ea1d52f6638615 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 20:56:43 +0300 Subject: [PATCH 28/85] feat(core): coordinate Delta publishers and support serverless identifiers Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 12 + docs/user_guide/databricks_batch.md | 51 +++- initiatives/spark_and_mlflow/HANDOFF.md | 26 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 9 +- .../spark_and_mlflow/PLATFORM_VALIDATION.md | 130 +++++++++- skyulf-core/skyulf/inference/spark.py | 10 +- .../databricks/delta_admission.py | 116 +++++++++ skyulf-core/skyulf/preprocessing/_spark.py | 19 +- .../skyulf/preprocessing/_spark_numeric.py | 4 +- .../integrations/test_delta_admission.py | 245 ++++++++++++++++++ .../tests/integrations/test_delta_publish.py | 31 +++ .../spark/test_serverless_identifiers.py | 71 +++++ 12 files changed, 688 insertions(+), 36 deletions(-) create mode 100644 skyulf-core/skyulf/integrations/databricks/delta_admission.py create mode 100644 skyulf-core/tests/integrations/test_delta_admission.py create mode 100644 skyulf-core/tests/spark/test_serverless_identifiers.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 21010ac18..f7fa20d06 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -8,8 +8,20 @@ Target: optional Spark execution and MLflow integration for Skyulf Core. Development version: 0.9.0. This release has not been published; Spark node execution, MLflow registry and Databricks delivery remain under development. +### Fixed + +- Spark identifier validation tolerates Databricks serverless hiding + `spark.sql.caseSensitive`, retaining conservative collision checks while + propagating unrelated errors. The failure was reproduced in a live job; + the correction passed both inference modes in a real serverless Spark Connect + 4.2.0 job using a Polars-trained model loaded from Unity Catalog. + ### Added +- Shared Delta-table publish admission with conditional ownership updates, + non-expiring claims and owner-only release. Real Delta tests cover independent + sessions, concurrent claims and malformed authorities; live Databricks + compatibility remains under validation. - Spark/MLflow initiative: architecture, implementation plans, validation gates and an ordered [task queue](../initiatives/spark_and_mlflow/OPEN_QUEUE.md). Historical readiness reports are grouped with the initiative. diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md index 72537e4be..fe34db24c 100644 --- a/docs/user_guide/databricks_batch.md +++ b/docs/user_guide/databricks_batch.md @@ -108,13 +108,50 @@ are intentionally retained; do not delete them while publishers may run. The OS releases ownership when the process exits. This implementation is rejected on distributed Spark masters, including `local-cluster`. -The `PublishAdmission` protocol is an extension boundary, not an implemented -Databricks coordinator. A distributed implementation must hold exclusive -ownership by immutable Delta table ID throughout validation, write and receipt -verification. The current API does not pass fencing tokens to Delta, so an -expiring lease is insufficient. Every publisher must participate in the same -authority. Uncoordinated external writes are outside this guarantee; detected -Delta conflicts still raise `BatchConflictError`. +### Shared Delta admission + +`DeltaTableAdmission` coordinates participating publishers through one shared +Delta control table. Real local Delta tests cover independent Spark sessions and +simultaneous claims; live Databricks validation is still pending. Operators must +provision the authority once, before starting publishers: + +```python +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + +target_id = spark.sql( + "DESCRIBE DETAIL analytics.customer_predictions" +).first()["id"] +# One-time provisioning only; do not overwrite an existing authority. +spark.createDataFrame( + [(target_id, None)], "target_id string, owner string" +).write.format("delta").mode("errorifexists").saveAsTable( + "analytics.customer_predictions_admission" +) + +admission = DeltaTableAdmission(spark, "analytics.customer_predictions_admission") +# Supply admission=admission to run_batch(...). +``` + +The provider requires exactly one row with the immutable output table ID and a +nullable string owner. It uses a conditional Delta UPDATE to claim ownership, +checks the committed token before entering, and clears only its own token after +publication and receipt verification. A competing publisher fails with +`BatchConflictError`; the provider does not automatically retry it. + +Every publisher must use the same authority. Keep its identity, schema and +target binding fixed. External control-row edits, DDL and writers bypassing this +protocol are outside the guarantee. Grant operators provisioning rights and +publishers only the required read/update access under your platform's policy. + +Ownership never expires. A driver crash or an uncertain acquisition can leave a +claim behind: inspect the job and prove that the original driver can no longer +publish before an operator clears it. Never clear a live owner's claim to unblock +another job. The sink has no fencing-token mechanism, so time-based expiry would +allow an old publisher to write after a new publisher acquired ownership. + +The provider uses Spark SQL parameter markers (Spark 3.4+) without a SparkContext +or data caching requirement. That API choice is not proof of compatibility with +every Databricks compute type; the platform gate records tested environments. ## Time and reproducibility diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 384cfbf0a..73057c801 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,7 +1,7 @@ # Session handoff - 2026-09-22 -SM-00 through SM-15 are complete. SM-16 platform preparation is ACTIVE; -live Databricks execution has not been validated. +SM-00 through SM-15 are complete. SM-16 is ACTIVE; live Databricks registry/Spark +parity passed, with Delta/concurrency/permissions/scale gates still outstanding. Target release: 0.9.0. Branch: `090`. ## Starting point @@ -10,8 +10,18 @@ Target release: 0.9.0. Branch: `090`. - The registry-bundle loader and first registry-to-Spark probe are implemented. Local validation passed 29 combined tests; the complete platform gate remains open. A 0.9.0 wheel was built, with its checksum recorded in the platform file. -- See [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). The user will provide - the CLI profile, test namespace and compute; no workspace has been selected. +- See [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). The user authorized the + supplied workspace and `skyulf` profile; OAuth authentication is verified. + No classic clusters exist. The user explicitly approved the isolated resources + and serverless probe. Run `245612415275039` failed on restricted + `spark.sql.caseSensitive` access after the UC/local round-trip. The fix passed + 75 real Spark tests. The user approved the corrected rerun; parent run + `447606109645160` completed SUCCESS. The Polars-trained registered bundle + produced the expected gold predictions in both Spark modes on serverless + Spark Connect 4.2.0 / Python 3.12.3 / MLflow 3.16.1. +- Shared `DeltaTableAdmission` is implemented. The final 18-test real Delta gate + covers forced acquisition races, lost acknowledgements and public batch replay. + Live validation is pending. - Local-engine pandas/Polars Delta writing is tracked as SM-15L. The current Spark writer does not implement it; templates remain SM-20. - SM-15 baseline: `4a613cb5`. Its implementation and verification are in the @@ -134,10 +144,10 @@ without writing again. New computation needs a new run ID and reviewed target version. History and transaction retention must cover the allowed retry window. The first SM-16 registry-to-Spark smoke and platform evidence file are prepared; -see that file for the current wheel checksum and local evidence. After the user -supplies the CLI profile, permitted test namespace and compute, prepare the -reviewable job request and finish the remaining platform gates. Databricks CLI +see that file for the current wheel checksum, approved namespace and live run. +Inspect the submitted job result and finish the remaining platform gates. Databricks CLI 1.17.0 is installed but absent from the current shell PATH; use its existing WinGet executable or a refreshed shell. The user confirmed `databricks.yml` is not needed in this repository; it is absent. DAB/templates and endpoints remain -later work. Do not reuse the previously retracted login host as authorization. +later work. The user's subsequent explicit authorization covers the `skyulf` +profile and the named isolated serverless test resources. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 54688d3b8..7de3c25a0 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -27,12 +27,12 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-13 | MLflow model packaging | SM-12 | DONE | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | -| SM-16 | Gerçek Databricks kapısı | SM-15 | ACTIVE | Local preparation; profile/test namespace/compute pending | +| SM-16 | Gerçek Databricks kapısı | SM-15 | ACTIVE | Live UC/Spark parity passed: `447606109645160`; remaining platform gates open | | SM-15L | Local pandas/Polars Delta sink | SM-16 | WAIT | Same period/retry guarantees; real local writer and UC access tests | | SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | -| SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | -| SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | -| SM-20 | Template / Databricks Bundle | SM-19 | LATER | Seçilebilir working runner; validate ve smoke | +| SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | Parked +| SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | Parked +| SM-20 | Template / Databricks Bundle | SM-19 | LATER | Seçilebilir working runner; validate ve smoke | Parked ## Detay planlar @@ -40,6 +40,7 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. - SM-15 currently provides the Spark writer only. The user's local-engine Delta requirement is tracked separately as SM-15L and must be satisfied before SM-20 offers that template combination. Template work remains last. +- The user confirmed the immediate order: finish SM-16, then SM-15L. - SM-00–SM-07: [Core/Spark](01-core-spark-plan.md) - SM-08–SM-11: [Inference](02-inference-plan.md) diff --git a/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md b/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md index b3eba5860..921f51aa7 100644 --- a/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md +++ b/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md @@ -1,6 +1,6 @@ # SM-16 platform validation -Status: **ACTIVE — local preparation; no live Databricks evidence yet**. +Status: **ACTIVE — live registry/Spark parity passed; remaining platform gates open**. Baseline: `d43e74ca`, branch `090`, target release `0.9.0`. ## Local preparation evidence — 2026-09-22 @@ -22,8 +22,8 @@ Baseline: `d43e74ca`, branch `090`, target release `0.9.0`. artifact root was moved under its temporary directory before the final gate. - Wheel built locally: `.cache/sm16-dist/skyulf_core-0.9.0-py3-none-any.whl`. SHA-256: `ede03a571bf3de480e1acca8ddd9c5179efd832906c410f4a0a98f50709b4779`. - This proves a local build only; the wheel has not been installed on Databricks - workers, uploaded or deployed. Rebuild/recompute the hash after code changes. + The wheel was uploaded to the approved workspace test folder. Installation and + worker execution remain pending the live job. Rebuild after code changes. Exact local commands: @@ -49,11 +49,117 @@ Databricks runtime dependency profile. explicit executable path is needed until that shell is refreshed. - The repository root has no `databricks.yml`. The user confirmed it is not needed here. No bundle, deployment or authentication was created. -- The user will provide the CLI profile, permitted test `catalog.schema` - and compute selection. None has been inferred from an earlier pasted host. +- On 2026-09-22 the user explicitly authorized using the supplied workspace + and existing `skyulf` or default CLI profile. `auth profiles` returned one + matching profile: `skyulf`, default, valid, OAuth CLI authentication. + `current-user me` succeeded without another login. +- Read-only discovery found catalogs `workspace`, `samples`, `system`; the + `workspace` catalog has `default` and `information_schema` schemas. No classic + clusters were listed. One stopped serverless SQL warehouse is available. +- A one-time serverless registry/Spark probe request was prepared with a + 900-second timeout and no retries. Proposed resources are the isolated + `workspace.skyulf_sm16_20260922` schema and a same-named folder under the + authenticated user's workspace directory. It uses the locally built wheel + and explicitly requests MLflow 3.16.1 without installing OSS PySpark. +- Automatic approval review initially rejected schema creation. The user then + explicitly approved these resources, uploads and the bounded serverless job. + Schema/folder creation and uploads succeeded. Parent run `245612415275039` + and task run `45737629137632` were submitted with a 900-second timeout. + [Live run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/94637315302832/run/245612415275039). ## Stage 1: registry-to-Spark probe +### First live result and correction — 2026-09-22 + +- Parent run `245612415275039`, task `45737629137632`: **FAILED** during + Spark inference identifier validation. The traceback reached `predict_spark` + after model registration, pinned bundle download and both local gold checks. +- Retained test model: + `workspace.skyulf_sm16_20260922.probe_b6b83b505a4145c192cc6be6c1ab7569`. +- Imported Skyulf came from the job's ephemeral Python 3.12 `site-packages`. + Clean worker prediction did not run, so worker wheel delivery is still open. +- Live failure: `CONFIG_NOT_AVAILABLE.WITHOUT_SUGGESTION` when reading + `spark.sql.caseSensitive`. Serverless restricts configuration access. +- Added one shared identifier-rule helper at all three read sites. Only the + structured unavailable-configuration condition falls back to conservative + case-insensitive collision checks; transport and permission failures propagate. +- Reproduced the failure before the fix. The real Spark regression gate passed + **75 tests** in 76.42s, including pandas/Polars training, both inference modes, + hidden configuration and ambiguous-case rejection. Independent review found + no blocker; scoped Ruff and Ty passed. +- Corrected wheel: `.cache/sm16-dist-r2/skyulf_core-0.9.0-py3-none-any.whl`. + SHA-256: `b10a7172cd268deec9b06168987a4d2ee4a19259417fc230d9a0bb3b5ea1b211`. + Automatic approval review initially rejected the additional upload/run as + exceeding the single-run approval. The user explicitly approved the retry; + `r2` uploads succeeded and parent run `447606109645160` was submitted with + the same 900-second timeout. Task run `987386852945959` finished **SUCCESS**. + +### Successful serverless rerun + +[Run `447606109645160`](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/541401697073405/run/447606109645160) +completed the Polars-trained bundle round-trip through Unity Catalog. Both +`native_features` and `python_pipeline` produced the keyed gold predictions +`[-2, 3, 5]`. The report intentionally keeps `platform_gate_complete: false`. + +| Evidence | Value | +| --- | --- | +| Model | `workspace.skyulf_sm16_20260922.probe_3e8e88a3d2f2435a9c2b7b280a184bc2`, version `1` | +| MLflow run | `81e30610dba14c52ae0e7e478b5abf50` | +| Bundle digest | `66890475ca608271a6115ed2505890740bd6669fd9301711f9032390b4ea8084` | +| Python / Spark | `3.12.3` / `4.2.0` | +| MLflow / Arrow | `3.16.1` / `25.0.1` | +| pandas / Polars / scikit-learn | `2.2.3` / `1.44.2` / `1.6.1` | +| Runtime environment | `client.4.10`, `pyspark.sql.connect.session.SparkSession` | +| Skyulf driver installation | `0.9.0`, non-editable ephemeral `site-packages` | + +The exact uploaded wheel is the `r2` artifact identified above. Both distributed +prediction actions succeeded; per-worker package/checksum provenance and scale +measurements were not collected by this three-row probe. Raw task output is +retained locally at `.cache/sm16-live-registry-output-r2.json` and in the run UI. +Test models and tracking runs remain in the approved namespace for inspection. + +### Restricted identity preparation + +The user requested creation of a separate test identity. Created +`skyulf-sm16-restricted-20260922`, application ID +`9559edaa-81e3-434b-a679-35703510c134` (workspace principal `75734274047655`). +It has workspace access, inherited `USE_CATALOG`, explicit `USE_SCHEMA` on the +test schema, `EXECUTE` on only the successful rerun's model and `CAN_READ` on +the isolated test folder. It has no admin role, data-modification grant or +created token/secret. The requesting account retains its existing manager role +and gained the user role on this test principal so it can submit `run_as` jobs. + +Run `2921374308246` was submitted with this `run_as` identity and a 900-second +timeout. It checks allowed model loading, denied access to the first test model, +worker package provenance and 10k/50k synthetic prediction aggregates. It does +not write tables. Its result is pending; submitting a job is not permission-test +evidence. Prepared notebook/request are under `.cache/sm16-live-permissions*`. + +References: [Serverless restrictions](https://docs.databricks.com/aws/en/compute/serverless/limitations), +[Databricks identifier rules](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-identifiers). + +### Shared Delta admission preparation + +`DeltaTableAdmission` now provides non-expiring conditional ownership through +an operator-provisioned singleton Delta table. Independent real Spark sessions +share that authority. The final focused gate passed **16 tests** in 59.07s, +including a forced race after both readers see a free row and acknowledgement +loss after acquisition commits. The failed caller never enters publication; +its retained claim blocks others until deliberate operator recovery. + +The final combined gate passed **18 tests** in 87.00s: the 16 provider tests, +the existing OS-process lock and public `run_batch` publication/replay through +shared Delta admission. Predictions, prior-period rows, the original receipt +and owner release after both calls were verified. Base regression passed +**80 tests**, with **48 optional-runtime skips** and one known Windows physical +core detection warning. Ruff/format/Ty, strict MkDocs and independent review +passed. Live serverless/UC admission, +competing jobs and permission enforcement remain pending. See the +[batch guide](../../docs/user_guide/databricks_batch.md) for provisioning and +the explicit cooperative-writer and manual-recovery boundaries. + +### Probe contract + Script: [databricks_batch_smoke.py](../../skyulf-core/examples/databricks_batch_smoke.py). 1. Fit a tiny pandas or Polars pipeline: mean SimpleImputer, StandardScaler, @@ -102,20 +208,20 @@ including when a previously resolved alias has moved. | Gate | Required evidence | Current state | | --- | --- | --- | -| Selected environment | Profile, workspace, compute ID/type, DBR/Python/Spark/MLflow/Arrow | Awaiting user selection | -| Package delivery | Exact wheel/checksum, installed distribution on clean driver/workers | Pending | -| Real UC round-trip | Concrete model version, alias pinning and trusted bundle download | Pending live execution | -| Spark parity | Gold data, both FE modes, key-based predictions, job run ID/URL | Local probe preparation | +| Selected environment | Profile, workspace, compute ID/type, DBR/Python/Spark/MLflow/Arrow | `skyulf`; serverless Connect; successful runtime recorded above | +| Package delivery | Exact wheel/checksum, installed distribution on clean driver/workers | Non-editable driver + worker prediction passed; per-worker provenance pending | +| Real UC round-trip | Concrete model version, alias pinning and trusted bundle download | Register/download/local checks reached; alias gate pending | +| Spark parity | Gold data, both FE modes, key-based predictions, job run ID/URL | Passed in live corrected run `447606109645160` | | Monthly publication | Real test Delta tables, snapshots, commits, replay, other periods preserved | SM-15 local evidence only | -| Distributed admission | Shared authority, ownership through commit, competing-job result | Not implemented/validated | +| Distributed admission | Shared authority, ownership through commit, competing-job result | Implemented; real local Delta tests passed; live gate pending | | UC permissions | Actual denied and allowed access in the approved namespace | Pending | | Scale | Synthetic distributed dataset, runtime and driver/worker memory evidence | Pending | Do not use `LocalTableLock` on a distributed Databricks driver. Limiting one job's concurrent runs does not coordinate other jobs or external writers. An expiring lease without sink-enforced fencing is insufficient. The platform -admission choice remains an explicit design/validation step after runtime -selection, not a no-op context manager pretending to own a distributed lock. +admission implementation now uses a shared non-expiring Delta claim. Its local +concurrency evidence does not substitute for validation on the selected platform. ## DAB and templates diff --git a/skyulf-core/skyulf/inference/spark.py b/skyulf-core/skyulf/inference/spark.py index d127a55f1..143538fd5 100644 --- a/skyulf-core/skyulf/inference/spark.py +++ b/skyulf-core/skyulf/inference/spark.py @@ -8,7 +8,13 @@ from ..core.capabilities import UnsupportedExecutionError from ..core.execution import ExecutionOptions, FrameSpec -from ..preprocessing._spark import _column, _native, _resolved_names, _validate_keys +from ..preprocessing._spark import ( + _case_sensitive, + _column, + _native, + _resolved_names, + _validate_keys, +) from ..preprocessing.pipeline import FeatureEngineer from ._manifest import BundleManifest, check_runtime, checksum from ._model import load_model @@ -246,7 +252,7 @@ def _validate_names_and_keys(frame: Any, manifest: BundleManifest, spec: FrameSp resolved = _resolved_names(frame) if len(resolved) != len(set(resolved)): raise ValueError("Duplicate Spark column names are unsupported.") - sensitive = frame.sparkSession.conf.get("spark.sql.caseSensitive") == "true" + sensitive = _case_sensitive(frame) def names(columns: tuple[str, ...]) -> set[str]: """Apply the same identifier resolution used by Spark for collision checks.""" diff --git a/skyulf-core/skyulf/integrations/databricks/delta_admission.py b/skyulf-core/skyulf/integrations/databricks/delta_admission.py new file mode 100644 index 000000000..c5802d838 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/delta_admission.py @@ -0,0 +1,116 @@ +"""Non-expiring distributed publish admission through a preprovisioned Delta row.""" + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any +from uuid import uuid4 + +from ._contracts import table_name +from .admission import BatchConflictError +from .delta import table_identity + + +class DeltaTableAdmission: + """Serialize participating publishers using one shared Delta control table. + + Operators must provision exactly one row with ``target_id STRING`` bound to + the immutable output Delta table ID and ``owner STRING`` initially NULL. + All publishers of that target must use this same control table. Its identity, + schema and target binding must remain fixed; external DDL, control-row edits + and publishers bypassing this protocol are outside the guarantee. + + Ownership never expires. A crashed driver or an uncertain acquisition can + leave an owner behind. Clear it manually only after proving that driver can + no longer publish. This provider does not create tables, insert rows, retry + conflicts or implement time-based leases. Spark SQL parameter markers require + Spark 3.4 or later (including compatible Spark Connect runtimes). + """ + + local_only = False + + def __init__(self, spark: Any, control_table: str) -> None: + """Bind to an existing Delta authority without creating or modifying it.""" + self._spark = spark + self._table = control_table + self._quoted_table = table_name(control_table) + self._control_id = self._identity() + + def _identity(self) -> str: + """Invalidate cached metadata and read the authority's current Delta ID.""" + self._spark.sql(f"REFRESH TABLE {self._quoted_table}").collect() + return table_identity(self._spark, self._table) + + def _state(self, target_id: str) -> str | None: + """Read fresh singleton ownership, rejecting malformed or rebound authority.""" + if self._identity() != self._control_id: + raise BatchConflictError("Control table identity changed during admission.") + frame = self._spark.table(self._table) + fields = {field.name: field for field in frame.schema} + if ( + len(frame.schema) != 2 + or set(fields) != {"target_id", "owner"} + or any(field.dataType.typeName() != "string" for field in fields.values()) + or not fields["owner"].nullable + ): + raise ValueError( + "Control table requires only target_id STRING and nullable owner STRING." + ) + rows = frame.limit(2).collect() + if len(rows) != 1 or rows[0]["target_id"] != target_id: + raise ValueError("Control table must contain exactly one row bound to this target ID.") + if self._identity() != self._control_id: + raise BatchConflictError("Control table identity changed while reading ownership.") + return rows[0]["owner"] + + def _update(self, statement: str, target_id: str, token: str) -> None: + """Execute conditional ownership changes, preserving Delta conflict causes.""" + try: + self._spark.sql(statement, args={"target_id": target_id, "token": token}).collect() + except Exception as exc: # noqa: BLE001 - Spark Connect and classic wrap Delta differently + name = type(exc).__name__ + message = str(exc) + if ( + "Concurrent" in name + or name in {"MetadataChangedException", "ProtocolChangedException"} + or any( + marker in message + for marker in ( + "DELTA_CONCURRENT", + "DELTA_METADATA_CHANGED", + "DELTA_PROTOCOL_CHANGED", + ) + ) + ): + raise BatchConflictError("Delta rejected a concurrent admission change.") from exc + raise + + @contextmanager + def hold(self, table_id: str) -> Iterator[None]: + """Claim the target until context exit, clearing only this context's token.""" + if type(table_id) is not str or not table_id: + raise ValueError("Admission requires a nonempty immutable target table ID.") + if self._state(table_id) is not None: + raise BatchConflictError("Another publisher holds this target's admission.") + token = str(uuid4()) + self._update( + f"UPDATE {self._quoted_table} SET owner = :token " + "WHERE target_id = :target_id AND owner IS NULL", + table_id, + token, + ) + if self._state(table_id) != token: + raise BatchConflictError("Admission ownership could not be verified.") + try: + yield + finally: + if self._state(table_id) != token: + raise BatchConflictError("Admission owner changed before release; nothing cleared.") + self._update( + f"UPDATE {self._quoted_table} SET owner = NULL " + "WHERE target_id = :target_id AND owner = :token", + table_id, + token, + ) + # A new publisher may acquire immediately after this release commits. + if self._state(table_id) == token: + raise BatchConflictError("Admission release could not be verified.") diff --git a/skyulf-core/skyulf/preprocessing/_spark.py b/skyulf-core/skyulf/preprocessing/_spark.py index 727c60f73..fc0274ff6 100644 --- a/skyulf-core/skyulf/preprocessing/_spark.py +++ b/skyulf-core/skyulf/preprocessing/_spark.py @@ -107,9 +107,26 @@ def _validate_keys(frame: Any, spec: FrameSpec) -> None: raise ValueError("Spark row_keys must be unique and non-null.") +def _case_sensitive(frame: Any) -> bool: + """Read identifier rules, conservatively folding names when config is hidden. + + Databricks serverless rejects this configuration read. Its identifiers are + case-insensitive; folding also rejects ambiguous names conservatively on any + runtime hiding this setting. Unrelated transport/access errors still surface. + """ + try: + return frame.sparkSession.conf.get("spark.sql.caseSensitive") == "true" + except Exception as exc: # noqa: BLE001 - optional classic/Connect error classes differ + condition = getattr(exc, "getCondition", None) or getattr(exc, "getErrorClass", None) + code = condition() if callable(condition) else None + if isinstance(code, str) and code.split(".")[0] == "CONFIG_NOT_AVAILABLE": + return False + raise + + def _resolved_names(frame: Any) -> list[str]: """Use session identifier rules for schema collisions and internal aliases.""" - if frame.sparkSession.conf.get("spark.sql.caseSensitive") == "true": + if _case_sensitive(frame): return frame.columns return [name.lower() for name in frame.columns] diff --git a/skyulf-core/skyulf/preprocessing/_spark_numeric.py b/skyulf-core/skyulf/preprocessing/_spark_numeric.py index 1af7b4e74..624fdcab0 100644 --- a/skyulf-core/skyulf/preprocessing/_spark_numeric.py +++ b/skyulf-core/skyulf/preprocessing/_spark_numeric.py @@ -2,7 +2,7 @@ from typing import Any -from ._spark import _column, _resolved_names +from ._spark import _case_sensitive, _column, _resolved_names NUMERIC_DTYPES = {"byte", "short", "integer", "long", "float", "double"} @@ -13,7 +13,7 @@ def validate_names(frame: Any, extra: tuple | list = ()) -> None: if len(set(names)) != len(names): raise ValueError("Duplicate Spark column names.") combined = list(dict.fromkeys([*frame.columns, *extra])) - if frame.sparkSession.conf.get("spark.sql.caseSensitive") != "true": + if not _case_sensitive(frame): combined = [name.lower() for name in combined] if len(set(combined)) != len(combined): raise ValueError("Fitted columns collide under Spark column name resolution.") diff --git a/skyulf-core/tests/integrations/test_delta_admission.py b/skyulf-core/tests/integrations/test_delta_admission.py new file mode 100644 index 000000000..d6a6769c0 --- /dev/null +++ b/skyulf-core/tests/integrations/test_delta_admission.py @@ -0,0 +1,245 @@ +"""Real Delta control-table admission across independent Spark sessions.""" + +import importlib +import importlib.util +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier, Event +from uuid import uuid4 + +import pytest + +from skyulf.integrations.databricks.admission import BatchConflictError + + +def _provider(spark, table): + """Load the optional provider without importing Spark in the base test lane.""" + module = importlib.import_module("skyulf.integrations.databricks.delta_admission") + return module.DeltaTableAdmission(spark, table) + + +@pytest.fixture +def control(delta_spark): + """Provision one immutable target binding, as an operator must before use.""" + table = "default.admission_" + uuid4().hex + target = str(uuid4()) + delta_spark.createDataFrame([(target, None)], "target_id string, owner string").write.format( + "delta" + ).saveAsTable(table) + try: + yield delta_spark, table, target + finally: + delta_spark.sql(f"DROP TABLE IF EXISTS {table}").collect() + + +def test_provider_is_available(): + """Distributed batch callers need a concrete provider they can import.""" + assert importlib.util.find_spec("skyulf.integrations.databricks.delta_admission") is not None + + +def test_held_claim_rejects_second_session_then_releases(control): + """A shared table serializes publishers even with separate Spark sessions.""" + spark, table, target = control + first = _provider(spark, table) + second = _provider(spark.newSession(), table) + with first.hold(target): + token = spark.table(table).first().owner + assert token + with pytest.raises(BatchConflictError), second.hold(target): + pytest.fail("A second publisher entered the held critical section.") + assert spark.table(table).first().owner == token + assert spark.table(table).first().owner is None + with second.hold(target): + assert spark.table(table).first().owner != token + assert first.local_only is False + + +def test_body_failure_releases_claim(control): + """A failed publication must permit a deliberate subsequent retry.""" + spark, table, target = control + with ( + pytest.raises(RuntimeError, match="publication failed"), + _provider(spark, table).hold(target), + ): + raise RuntimeError("publication failed") + assert spark.table(table).first().owner is None + + +@pytest.mark.parametrize("malformation", ["empty", "duplicate", "wrong_target", "wrong_schema"]) +def test_malformed_control_is_rejected_without_writing(control, malformation): + """Malformed authority state must not be repaired or claimed implicitly.""" + spark, table, target = control + if malformation == "empty": + spark.sql(f"DELETE FROM {table}").collect() + elif malformation == "duplicate": + spark.sql(f"INSERT INTO {table} SELECT * FROM {table}").collect() + elif malformation == "wrong_target": + target = str(uuid4()) + else: + spark.sql(f"ALTER TABLE {table} ADD COLUMN unexpected STRING").collect() + before = spark.table(table).collect() + version = spark.sql(f"DESCRIBE HISTORY {table}").first().version + with pytest.raises(ValueError), _provider(spark, table).hold(target): + pytest.fail("Malformed admission entered the critical section.") + assert spark.table(table).collect() == before + assert spark.sql(f"DESCRIBE HISTORY {table}").first().version == version + + +def test_release_never_clears_another_owner(control): + """Even an unauthorized owner change cannot make cleanup clear someone else.""" + spark, table, target = control + with pytest.raises(BatchConflictError), _provider(spark, table).hold(target): + spark.sql(f"UPDATE {table} SET owner = 'other-owner'").collect() + assert spark.table(table).first().owner == "other-owner" + + +def test_release_predicate_preserves_owner_changed_after_read(control, monkeypatch): + """Cleanup's UPDATE must check ownership even after its read saw the old token.""" + spark, table, target = control + provider = _provider(spark, table) + update = provider._update + calls = 0 + + def change_owner_before_release(statement, target_id, token): + """Inject a real Delta change between the release check and release write.""" + nonlocal calls + calls += 1 + if calls == 2: + spark.sql(f"UPDATE {table} SET owner = 'racing-owner'").collect() + return update(statement, target_id, token) + + monkeypatch.setattr(provider, "_update", change_owner_before_release) + with provider.hold(target): + assert spark.table(table).first().owner + assert spark.table(table).first().owner == "racing-owner" + + +def test_existing_owner_has_no_expiry(control): + """Orphaned ownership requires manual recovery rather than automatic takeover.""" + spark, table, target = control + spark.sql(f"UPDATE {table} SET owner = 'orphaned-owner'").collect() + with pytest.raises(BatchConflictError), _provider(spark, table).hold(target): + pytest.fail("An orphaned claim was stolen.") + assert spark.table(table).first().owner == "orphaned-owner" + + +def test_lost_acquisition_acknowledgement_retains_claim(control, monkeypatch): + """An uncertain committed claim must block publication and require manual recovery.""" + spark, table, target = control + provider = _provider(spark, table) + update = provider._update + + def lose_acknowledgement(statement, target_id, token): + """Commit the real Delta UPDATE before simulating a transport failure.""" + update(statement, target_id, token) + raise RuntimeError("acquisition acknowledgement lost") + + monkeypatch.setattr(provider, "_update", lose_acknowledgement) + entered = False + with ( + pytest.raises(RuntimeError, match="acquisition acknowledgement lost"), + provider.hold(target), + ): + entered = True + assert entered is False + owner = spark.table(table).first().owner + assert owner is not None + with pytest.raises(BatchConflictError), _provider(spark.newSession(), table).hold(target): + pytest.fail("An uncertain committed claim admitted another publisher.") + assert spark.table(table).first().owner == owner + + +def test_cached_free_row_cannot_admit_a_second_owner(control): + """Cached availability must not bypass committed ownership from another session.""" + spark, table, target = control + other = spark.newSession() + other.sql(f"CACHE TABLE {table}").collect() + assert other.table(table).first().owner is None + try: + with ( + _provider(spark, table).hold(target), + pytest.raises(BatchConflictError), + _provider(other, table).hold(target), + ): + pytest.fail("Cached free state admitted a second owner.") + finally: + other.sql(f"UNCACHE TABLE {table}").collect() + assert spark.table(table).first().owner is None + + +def test_concurrent_requests_have_exactly_one_owner(control, monkeypatch): + """Two real Spark requests may race, but only one may enter the critical section.""" + spark, table, target = control + providers = [_provider(spark.newSession(), table) for _ in range(2)] + free_reads = Barrier(2) + loser_finished = Event() + + def synchronize_first_read(provider): + """Force both contenders to observe availability before either can UPDATE.""" + state = provider._state + first_read = True + + def read_state(target_id): + """Read actual Delta state and synchronize only the pre-acquisition read.""" + nonlocal first_read + owner = state(target_id) + if first_read: + first_read = False + assert owner is None + free_reads.wait(timeout=60) + return owner + + monkeypatch.setattr(provider, "_state", read_state) + + for provider in providers: + synchronize_first_read(provider) + + def contend(provider): + """Keep a winning claim until its racing peer has rejected admission.""" + try: + with provider.hold(target): + assert loser_finished.wait(timeout=120), "Both publishers entered or peer hung." + return "owned" + except BatchConflictError: + loser_finished.set() + return "rejected" + + with ThreadPoolExecutor(max_workers=2) as executor: + results = list(executor.map(contend, providers)) + assert sorted(results) == ["owned", "rejected"] + assert spark.table(table).first().owner is None + + +def test_replaced_control_table_is_rejected(control): + """A long-lived provider must never silently bind a new control-table identity.""" + spark, table, target = control + provider = _provider(spark, table) + spark.sql(f"DROP TABLE {table}").collect() + spark.createDataFrame([(target, None)], "target_id string, owner string").write.format( + "delta" + ).saveAsTable(table) + with pytest.raises(BatchConflictError), provider.hold(target): + pytest.fail("Replaced control authority admitted an existing provider.") + assert spark.table(table).first().owner is None + + +def test_missing_control_table_is_not_created(delta_spark): + """Admission must never manufacture an authority when provisioning is missing.""" + analysis_error = importlib.import_module("pyspark.errors").AnalysisException + table = "default.missing_admission_" + uuid4().hex + with pytest.raises(analysis_error): + _provider(delta_spark, table) + assert not delta_spark.catalog.tableExists(table) + + +def test_non_delta_control_table_is_rejected(delta_spark): + """A superficially correct Parquet row cannot provide transactional admission.""" + table = "default.parquet_admission_" + uuid4().hex + delta_spark.createDataFrame( + [(str(uuid4()), None)], "target_id string, owner string" + ).write.format("parquet").saveAsTable(table) + try: + with pytest.raises(ValueError, match="Delta"): + _provider(delta_spark, table) + assert delta_spark.table(table).first().owner is None + finally: + delta_spark.sql(f"DROP TABLE {table}").collect() diff --git a/skyulf-core/tests/integrations/test_delta_publish.py b/skyulf-core/tests/integrations/test_delta_publish.py index 8f9886626..5c4698bbd 100644 --- a/skyulf-core/tests/integrations/test_delta_publish.py +++ b/skyulf-core/tests/integrations/test_delta_publish.py @@ -101,6 +101,37 @@ def test_retry_preserves_other_periods_and_predictions(harness, mode): assert first.manifest["model_digest"] == h.bundle.semantic_digest +def test_delta_admission_publishes_and_replays_with_released_owner(harness): + """Public batch publication and replay release shared admission and preserve prior rows.""" + from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + + h = harness + control = "default.batch_admission_" + uuid4().hex + target_id = h.spark.sql(f"DESCRIBE DETAIL {h.target}").first()["id"] + prior = h.spark.table(h.target).first() + h.spark.createDataFrame([(target_id, None)], "target_id string, owner string").write.format( + "delta" + ).saveAsTable(control) + try: + h.lock = DeltaTableAdmission(h.spark, control) + first = _run(h) + assert h.spark.table(control).first().owner is None + rows = h.spark.table(h.target).orderBy("id").collect() + assert [row.id for row in rows] == [1, 2, 9] + assert [row.prediction for row in rows] == pytest.approx([2.0, 4.0, 99.0]) + assert rows[-1] == prior + second = _run(h) + assert h.spark.table(control).first().owner is None + assert h.spark.table(h.target).orderBy("id").collect() == rows + assert first.input_count == first.output_count == 2 + assert first.commit_version == second.commit_version == 1 + assert first.replayed is False + assert second.replayed is True + assert second.manifest == first.manifest + finally: + h.spark.sql(f"DROP TABLE IF EXISTS {control}").collect() + + def test_stale_writer_and_reused_run_identity_fail(harness): """Stale expectations and changed requests cannot silently replace a committed month.""" from skyulf.integrations.databricks.delta import BatchConflictError diff --git a/skyulf-core/tests/spark/test_serverless_identifiers.py b/skyulf-core/tests/spark/test_serverless_identifiers.py new file mode 100644 index 000000000..2bab707e5 --- /dev/null +++ b/skyulf-core/tests/spark/test_serverless_identifiers.py @@ -0,0 +1,71 @@ +"""Identifier safety when serverless compute hides Spark configuration.""" + +from types import SimpleNamespace + +import pytest + +from skyulf.core.execution import ExecutionOptions, FrameSpec +from skyulf.inference import build_bundle, predict_spark +from skyulf.preprocessing._spark import _resolved_names + + +class UnavailableConfiguration(Exception): + """Mirror the structured condition returned by Databricks Spark Connect.""" + + def getCondition(self): + """Identify unavailable configuration without parsing error messages.""" + return "CONFIG_NOT_AVAILABLE.WITHOUT_SUGGESTION" + + +@pytest.mark.parametrize("error", [UnavailableConfiguration(), PermissionError("denied")]) +def test_unavailable_config_uses_conservative_identifier_rules(error): + """Hidden configuration must retain collision detection without hiding access failures.""" + + def get(key): + """Reproduce the live failure at the RuntimeConfig boundary.""" + assert key == "spark.sql.caseSensitive" + raise error + + frame = SimpleNamespace( + columns=["Feature", "feature"], sparkSession=SimpleNamespace(conf=SimpleNamespace(get=get)) + ) + if isinstance(error, UnavailableConfiguration): + assert _resolved_names(frame) == ["feature", "feature"] + else: + with pytest.raises(PermissionError, match="denied"): + _resolved_names(frame) + + +@pytest.mark.parametrize("mode", ["native_features", "python_pipeline"]) +def test_inference_with_hidden_identifier_config( + spark, fitted_regression_pipeline, monkeypatch, mode +): + """Both inference paths retain keyed predictions and reject ambiguous input names.""" + bundle = build_bundle(fitted_regression_pipeline, input_stage="raw", feature_order=("x", "z")) + original = type(spark.conf).get + + def hidden(self, key, *args, **kwargs): + """Hide only the setting rejected by real Databricks serverless.""" + if key == "spark.sql.caseSensitive": + raise UnavailableConfiguration() + return original(self, key, *args, **kwargs) + + monkeypatch.setattr(type(spark.conf), "get", hidden) + frame = spark.createDataFrame([(7, 150.0, 9.0)], "id long, x double, z double") + rows = predict_spark( + frame, + bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark"), + mode=mode, + ).collect() + assert rows[0].id == 7 and rows[0].prediction == pytest.approx(280.0) + ambiguous = frame.selectExpr("id", "x", "z", "x AS X") + with pytest.raises(ValueError, match="Duplicate Spark column"): + predict_spark( + ambiguous, + bundle, + frame_spec=FrameSpec(row_keys=("id",)), + options=ExecutionOptions("spark"), + mode=mode, + ) From 63dd3e218181e2a6c6732dd1dcf44f8529136a5b Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Tue, 22 Sep 2026 21:44:27 +0300 Subject: [PATCH 29/85] fix(core): validate serverless Delta publication and permissions Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 13 +- docs/user_guide/databricks_batch.md | 54 ++++- docs/user_guide/inference_flow.md | 6 +- docs/user_guide/mlflow_registry.md | 9 +- docs/user_guide/spark.md | 23 +- .../03-mlflow-batch-delivery-plan.md | 64 +++--- initiatives/spark_and_mlflow/HANDOFF.md | 67 +++--- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 38 ++-- .../spark_and_mlflow/PLATFORM_VALIDATION.md | 167 ++++++++++++-- .../2026-09-22-sm16-live-evidence.json | 190 ++++++++++++++++ .../examples/databricks_delta_smoke.py | 206 ++++++++++++++++++ .../skyulf/integrations/databricks/batch.py | 18 +- .../databricks/delta_admission.py | 14 +- .../integrations/test_delta_admission.py | 65 ++++++ .../tests/integrations/test_delta_publish.py | 83 +++++++ .../integrations/test_platform_delta_smoke.py | 85 ++++++++ 16 files changed, 982 insertions(+), 120 deletions(-) create mode 100644 initiatives/spark_and_mlflow/reports/2026-09-22-sm16-live-evidence.json create mode 100644 skyulf-core/examples/databricks_delta_smoke.py create mode 100644 skyulf-core/tests/integrations/test_platform_delta_smoke.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index f7fa20d06..c27b336d9 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -15,13 +15,22 @@ execution, MLflow registry and Databricks delivery remain under development. propagating unrelated errors. The failure was reproduced in a live job; the correction passed both inference modes in a real serverless Spark Connect 4.2.0 job using a Polars-trained model loaded from Unity Catalog. +- Delta batch/admission tolerates the explicit serverless restrictions on + `REFRESH TABLE` and prediction caching. Identity/ownership reads and + transactional checks remain active; uncached execution stays distributed. + Other runtime failures propagate, and classic Spark still refreshes/caches. ### Added - Shared Delta-table publish admission with conditional ownership updates, non-expiring claims and owner-only release. Real Delta tests cover independent - sessions, concurrent claims and malformed authorities; live Databricks - compatibility remains under validation. + sessions, concurrent claims and malformed authorities. Live serverless + Spark Connect 4.2.0 validation covers monthly replacement/replay, exclusive + admission across jobs and restricted-principal target-write denial. +- Databricks monthly Delta smoke example, tested with a pinned UC regression + bundle, preserved prior periods, empty replacement and durable replay receipts. + The SM-16 evidence records worker package hashes, alias pinning and bounded + synthetic scale observations for the selected runtime. - Spark/MLflow initiative: architecture, implementation plans, validation gates and an ordered [task queue](../initiatives/spark_and_mlflow/OPEN_QUEUE.md). Historical readiness reports are grouped with the initiative. diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md index fe34db24c..486910db4 100644 --- a/docs/user_guide/databricks_batch.md +++ b/docs/user_guide/databricks_batch.md @@ -5,10 +5,14 @@ and atomically replaces the requested period in a precreated Delta table. It reuses both [Spark inference modes](inference_flow.md), without refitting feature engineering or the model. Scheduling remains the caller's responsibility. -The current validation covers **local Spark 4.0.3 with Delta Lake 4.0.0 on Linux**. -Live Databricks, Unity Catalog, distributed publish admission and wheel delivery -remain the SM-16 platform gate. Installing this adapter does not certify those -platforms. Tracking and registry remain optional and independent of the engine. +Validation covers **local Spark 4.0.3 with Delta Lake 4.0.0 on Linux** and a live +Databricks serverless Spark Connect 4.2.0 regression probe using Unity Catalog +tables. The live probe verified monthly replacement, replay, empty protection, +prior-period preservation and worker wheel contents. Separate live jobs verified +exclusive admission and a restricted principal's target-write denial, with +unchanged data/version and released ownership afterward. This is a bounded +regression workflow, not certification of every runtime or production workload. +Tracking and registry remain optional and independent of the engine. This runner currently requires Spark. Delta itself can also be written from pandas/Polars through [Arrow and delta-rs](https://delta-io.github.io/delta-rs/usage/writing/); a local-engine Skyulf Delta sink @@ -16,6 +20,14 @@ with the same period/retry guarantees is planned separately as SM-15L. Choosing Delta as the output format should not force the inference engine to be Spark. Unity Catalog access and supported Delta features need validation for each writer. +The runner caches predictions when the runtime supports `persist()`. If +Databricks serverless rejects that operation with its specific structured +restriction, validation and publication use the distributed frame without a +cache, and no `unpersist()` call is made. Separate actions can recompute +predictions from the pinned source and frozen bundle; this trades repeated work +for compatibility and never collects the dataset into driver memory. Other +cache failures propagate before publication. + ```mermaid flowchart LR A["Delta source: fixed version"] --> B["Select UTC period [start, end)"] @@ -112,7 +124,8 @@ on distributed Spark masters, including `local-cluster`. `DeltaTableAdmission` coordinates participating publishers through one shared Delta control table. Real local Delta tests cover independent Spark sessions and -simultaneous claims; live Databricks validation is still pending. Operators must +simultaneous claims. A live serverless test also rejected a second job while the +first held ownership, then allowed the first job to commit. Operators must provision the authority once, before starting publishers: ```python @@ -143,6 +156,18 @@ target binding fixed. External control-row edits, DDL and writers bypassing this protocol are outside the guarantee. Grant operators provisioning rights and publishers only the required read/update access under your platform's policy. +In Unity Catalog, the scoring identity needs `USE CATALOG` and `USE SCHEMA`, +`SELECT` on the source, and `SELECT`/`MODIFY` on the target and control tables. +Loading a registered model additionally needs its own model access, including +`EXECUTE`; table access does not grant model access. Provisioning new tables is +an operator step, so the scoring identity does not need schema-wide creation +rights for an existing source, target and authority. + +Admission does not bypass target permissions. A caller may acquire the control +row and still be denied `MODIFY` on the prediction table. The sink preserves the +underlying runtime error as the cause of `DeltaPublishError`, and the admission +context releases its claim when that write fails normally. + Ownership never expires. A driver crash or an uncertain acquisition can leave a claim behind: inspect the job and prove that the original driver can no longer publish before an operator clears it. Never clear a live owner's claim to unblock @@ -150,8 +175,13 @@ another job. The sink has no fencing-token mechanism, so time-based expiry would allow an old publisher to write after a new publisher acquired ownership. The provider uses Spark SQL parameter markers (Spark 3.4+) without a SparkContext -or data caching requirement. That API choice is not proof of compatibility with -every Databricks compute type; the platform gate records tested environments. +or data caching requirement. Classic Spark explicitly refreshes the control +table before identity reads. When serverless rejects `REFRESH TABLE` with its +specific unsupported-operation condition, the provider proceeds with fresh +Delta identity/ownership reads; user-managed cache APIs are unavailable there. +Conditional updates and unique-token verification still control ownership. +Other errors propagate. The platform gate records tested environments rather +than assuming all compute types support the same APIs. ## Time and reproducibility @@ -214,6 +244,16 @@ the same provenance guarantees as `run_batch`. ## Local verification +The repository's `skyulf-core/examples/databricks_delta_smoke.py` accepts an +existing Spark session, a pinned raw `y=2*x` regression bundle and an existing +test namespace. Its `run_smoke(...)` creates and prints three unique Delta table +names, verifies monthly publication/replay and explicit empty replacement, and +retains the tables for inspection. Use only a test namespace where you are +authorized to create and modify tables. The returned report includes table IDs, +versions and receipts and deliberately keeps `platform_gate_complete=False`. +Unexpected runtime failures propagate; the probe does not change runtime settings +or replace admission with a no-op provider. + Use Linux (or WSL) with Python 3.12 and Java 17. Windows Spark inference alone does not establish that Hadoop's filesystem support can write Delta locally. Keep this test environment separate from Databricks Runtime's bundled packages. diff --git a/docs/user_guide/inference_flow.md b/docs/user_guide/inference_flow.md index c0b49d87b..b3cf58b05 100644 --- a/docs/user_guide/inference_flow.md +++ b/docs/user_guide/inference_flow.md @@ -203,8 +203,10 @@ backend artifact format is a separate delivery. Local/Spark describes where and how computation runs. Monthly batch scheduling, HTTP endpoints and SQL access describe how it is invoked; they are separate from -the training or FE algorithm. MLflow/Unity Catalog packaging and registry support, -real Databricks validation, endpoints and templates remain later stages. +the training or FE algorithm. MLflow packaging and registry loading are available; +both Spark modes have passed a real Databricks serverless regression probe using +a Polars-trained model from Unity Catalog. The monthly Delta runner has separate +publication checks. Endpoints and reusable templates remain later stages. For runnable code, see the [Spark batch inference example](inference_bundles.md#native-spark-fe-and-worker-model-inference). The SVG diagrams on this page display without Mermaid support; each has an diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 41eadd1c5..086791aa8 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -61,9 +61,12 @@ validation data, not a second feature-engineering implementation. For Unity Catalog, pass a three-part model name (`catalog.schema.model`) and a `databricks-uc` registry URI. Tracking and registry URIs remain separate. The -local tests cover this configuration validation and separate local stores; a -live Databricks/Unity Catalog connection is deliberately reserved for the SM-16 -platform gate. +local tests cover configuration validation and separate stores. A live +Databricks serverless Spark Connect 4.2.0 test registered and loaded a +Polars-trained regression bundle, then verified both Spark inference modes. +A separate restricted service principal loaded an allowed model and received +`RegistryAccessError` for a model without `EXECUTE` permission. This evidence +does not establish compatibility with every compute type or registry backend. Load the selected artifact with `load_registered_bundle`. It uses the pinned name/version and the package's declared bundle path, rejects paths outside the diff --git a/docs/user_guide/spark.md b/docs/user_guide/spark.md index 4f489f25c..2e066b546 100644 --- a/docs/user_guide/spark.md +++ b/docs/user_guide/spark.md @@ -121,10 +121,15 @@ responsibility. In particular, Spark's [`toPandas`](https://spark.apache.org/docs/4.0.3/api/python/reference/pyspark.sql/api/pyspark.sql.DataFrame.toPandas.html) collects data into driver memory. -Validation currently covers classic PySpark 4.0.3 on the local test runtime. -The adapter uses public dataframe APIs, but Databricks and Spark Connect have -not been integration-tested yet. Engine detection does not authorize a Spark -frame to run through existing local-only FE nodes. +Validation covers classic PySpark 4.0.3 locally and a limited live Databricks +serverless Spark Connect 4.2.0 inference path. The latter loads a Polars-trained +regression bundle from Unity Catalog and applies mean imputation/StandardScaler +in both inference modes. It does not certify every Spark fit operation or compute +type. Engine detection does not authorize local-only FE nodes on Spark input. + +Serverless hides `spark.sql.caseSensitive`. Skyulf handles that specific +unavailable-configuration condition with conservative case-insensitive collision +checks; unrelated connection and permission failures still propagate. ## Execution contracts @@ -546,10 +551,12 @@ explains how existing pipeline pickle and backend joblib artifacts relate to the new bundle. Saving fitted FE with a model already existed; distributed execution requires explicit support for the transformations in that artifact. -Current distributed model support is regression with native mean/constant -imputation and StandardScaler, including an empty FE chain. Local training can -use pandas or Polars. Classification, MLflow packaging and Databricks runtime -validation have separate later gates. +Distributed inference supports raw regression and classification in both modes, +with the documented portable FE restrictions. Local training can use pandas or +Polars. MLflow packaging and registry loading are available. Live Databricks +serverless regression parity, monthly Delta publication, writer coordination +and restricted-principal write denial have passed the selected SM-16 workflow. +This does not extend cloud validation to every node or classification path. ## Capability declarations diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index ebdfe26ab..7246b4a8b 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -191,44 +191,38 @@ The fixture performs real Delta I/O; permission denial at the admission boundary is a fault-injection test, not evidence of live UC permissions. Exact versions, commands and results are recorded in [OPEN_QUEUE.md](OPEN_QUEUE.md). -## SM-16 — Gerçek Databricks doğrulaması - -**Bağımlılık:** SM-15. **Oluştur:** `skyulf-core/examples/databricks_batch_smoke.py`, -`initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md` (uygulama sırasında). -**Üretir:** Bir wheel ile gerçek FE → registry load → Spark inference → test Delta table. - -- [ ] Implement and verify shared publish admission for the selected runtime. - SM-15's local file locks are rejected on distributed masters. The provider - must hold exclusive ownership through commit and receipt verification; - expiring leases require a new sink fencing design before they can be used. - Include actual UC write-permission and concurrent-publisher evidence. -- [ ] Kullanılan DBR/Python/Spark/MLflow/Arrow, compute türü, izinli catalog/schema - ve test resource isimlerini kaydet. Workspace bilgisi yoksa yalnız bu görev WAIT - olur; local testler Databricks geçti sayılmaz. -- [ ] Wheel'i build et; temiz job ortamında kur. DBR'ın Spark'ını körlemesine - pip extra ile değiştirme. OSS Spark, DBR ve Connect ayrı dependency profilleri. -- [ ] Native FE ve Python pipeline yollarını aynı küçük gold dataset ile - karşılaştır; büyük sentetik dataset'te bellek/runtime ölç. UC alias pinning - ve monthly retry testini test catalog'unda çalıştır. -- [ ] İlk doğrulama job/script ile; DAB template üretme. Serverless/Connect ancak - ayrıca test edilirse supported ilan edilir; classic başarılarını genelleme. - -```python -def test_platform_evidence_has_concrete_versions(platform_evidence): - """A successful job without runtime and model identity is not reproducible.""" - assert platform_evidence["model_version"] - assert platform_evidence["wheel_version"] - assert platform_evidence["input_snapshot"] - assert platform_evidence["job_run_id"] - assert platform_evidence["prediction_parity_passed"] is True -``` - -Bu kontrol gerçek job çıktısına uygulanır; elle doldurulmuş dict platform testi değildir. -**Kabul:** G4 platform kapısı: run URL/id, sürümler, parity ve tekrar yazma kanıtı. +## SM-16 - Real Databricks validation + +**Dependency:** SM-15. **Status:** DONE on 2026-09-22 for the selected serverless +Spark Connect workflow. Evidence: [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md) +and its linked machine-readable live report. + +- [x] Implement shared, non-expiring Delta publish admission. Verify ownership + through commit and receipt validation, actual target-write denial and two-job + contention. The initial contender probe failed only on its permission-code + assertion; its preceding contention checks and the final successful restricted + probe jointly establish the result. Preserve that failed-run record. +- [x] Record workspace/profile, test namespace/resources, serverless environment, + Python/Spark/MLflow/Arrow versions and concrete run IDs/URLs. +- [x] Install the built wheel in clean jobs without replacing Databricks Spark. + Check all 225 installed worker package files against the r3 content digest; + verify current source files also match the tested wheel. +- [x] Compare native FE and Python-pipeline predictions with independent gold + values. Measure 10k/50k synthetic runtime and scoped memory observations. + Notebook/client Python lifetime RSS is not cluster or inference-worker peak. +- [x] Verify UC version pinning after alias movement, monthly replacement/replay, + empty protection and preservation of other periods using actual transactions. +- [x] Use one-time CLI jobs and scripts. No DAB template or root databricks.yml. + +**Acceptance:** G4 passed for serverless Connect 4.2.0 / Python 3.12.3 / +MLflow 3.16.1, client environment 4.10. The aggregate evidence is generated from +actual job outputs after checking success states, expected results, matching +model/table/trial identities and the wheel checksum. This is not a production +benchmark or blanket certification of all engines, node families or runtimes. ## SM-15L — Local-engine Delta publication -**Dependency:** SM-16. **Status:** WAIT; clarified by the user on 2026-09-22. +**Dependency:** SM-16. **Status:** READY; SM-16 completed on 2026-09-22. The SM-15 delivery covers only the Spark runner. A Delta destination must not imply Spark inference; support for pandas/Polars publication needs its own sink. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 73057c801..1ee12e7f9 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,15 +1,15 @@ # Session handoff - 2026-09-22 -SM-00 through SM-15 are complete. SM-16 is ACTIVE; live Databricks registry/Spark -parity passed, with Delta/concurrency/permissions/scale gates still outstanding. +SM-00 through SM-16 are complete for their documented scopes. The selected +Databricks serverless regression workflow passed. SM-15L is READY and next. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-15 are complete; SM-16 local preparation is in progress. +- SM-00 through SM-16 are complete; local pandas/Polars Delta writing is next. - The registry-bundle loader and first registry-to-Spark probe are implemented. - Local validation passed 29 combined tests; the complete platform gate remains - open. A 0.9.0 wheel was built, with its checksum recorded in the platform file. + Local validation passed 29 combined tests; the selected live platform gate is + now complete. Tested 0.9.0 wheel hashes are recorded in the platform file. - See [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). The user authorized the supplied workspace and `skyulf` profile; OAuth authentication is verified. No classic clusters exist. The user explicitly approved the isolated resources @@ -19,13 +19,29 @@ Target release: 0.9.0. Branch: `090`. `447606109645160` completed SUCCESS. The Polars-trained registered bundle produced the expected gold predictions in both Spark modes on serverless Spark Connect 4.2.0 / Python 3.12.3 / MLflow 3.16.1. -- Shared `DeltaTableAdmission` is implemented. The final 18-test real Delta gate - covers forced acquisition races, lost acknowledgements and public batch replay. - Live validation is pending. +- Shared `DeltaTableAdmission` is implemented. Its local real Delta gate covers + forced acquisition races, lost acknowledgements and public batch replay. + Live monthly admission and independent-job contention passed. +- Checkpoint `311547fc` contains that code and the serverless identifier fix. + Restricted service-principal run `2921374308246` passed model allow/deny, + worker imports and 10k/50k synthetic parity. A subsequent Delta/alias run + completed worker-content and alias prechecks, then failed on serverless + `REFRESH TABLE`. Narrow refresh/cache fixes passed a combined 48-test Delta + gate; live retry `783094949884769` passed monthly/alias/worker-content checks. + Winner `973709879452231` committed after contender `404334394214907` verified + held-owner rejection. The contender then failed a test-only assertion about + the permission error code; final restricted run `977447944071613` passed the + denial, unchanged data/version and released ownership checks. That failed run + remains documented, not relabeled. The aggregate report was generated from + actual results and checked against the r3 wheel; all 225 current package files + match that wheel. See the platform evidence file for retained resources. - Local-engine pandas/Polars Delta writing is tracked as SM-15L. The current - Spark writer does not implement it; templates remain SM-20. + Spark writer does not implement it; templates remain SM-20. Start with explicit + local source/target and memory/provenance contracts. A delta-rs filesystem test + must not be presented as UC managed-table writer support; see the current + platform document's external-client constraints. - SM-15 baseline: `4a613cb5`. Its implementation and verification are in the - delivery commit containing this handoff. No live Databricks validation yet. + delivery commit containing the original SM-15 handoff. Live evidence is SM-16. - SM-13 starts from `67315253`; its implementation, guide and evidence are in the delivery commit containing this handoff. - Previous guide/queue commit: `80dc9ee9` (SM-11 closure and SM-12 handoff). @@ -49,9 +65,9 @@ Databricks training job: pandas/Polars FE + sklearn model -> Write predictions to a Delta table, for example monthly ``` -This is the intended deployment scenario, not a claim that the complete -Databricks integration has already been validated. Scheduling, Delta delivery, -MLflow/Unity Catalog, endpoints and templates retain their later queue stages. +SM-16 validated this regression workflow on the selected serverless environment. +It does not certify arbitrary FE nodes, classification or every runtime. +Scheduling configuration, endpoints and reusable templates remain later scope. Keep new documentation and diagram labels in English. ## Current execution boundaries @@ -88,7 +104,7 @@ The strict documentation build, four rendered diagrams and commit hooks passed. A built 0.9.0 wheel imported the worker inference module in a separate process. Synthetic local measurements recorded 10k/2 partitions at 3.929s and 50k/8 partitions at 8.089s with driver peak RSS 246.2/246.8 MB. These are local -evidence only; Databricks worker-wheel deployment remains a later gate. SM-12 +evidence only; the later SM-16 worker-wheel evidence is recorded above. SM-12 also added optional MLflow tracking: the base environment keeps MLflow absent, while an isolated MLflow 3.16.1 environment passed all 8 tracking tests for explicit client-bound lifecycle, concurrency, caller-run preservation, config @@ -102,22 +118,21 @@ the wheel. Base bundle/schema/integration tests passed 80 with 7 optional skips. MLflow aligns named columns and safely casts compatible inputs before bundle prediction; direct `predict_local` remains strict. Unsupported bundle integer dtypes fail at packaging. Producer uv files and temporary paths are excluded. -Registry-to-G2 evidence is carried into SM-14; live UC/Databricks, scheduled -batch delivery, endpoints and templates remain later gates. +Registry-to-G2 evidence continued through SM-14 and the completed SM-16 live +gate. Scheduling configuration, endpoints and templates remain later work. SM-14 added explicit MLflow registry publication and resolution. The adapter publishes only `runs:/...` artifacts, leaves alias promotion explicit, resolves an alias once to a concrete `models:/name/version` URI, and returns the packaged signature and bundle digest. MLflow 3.16.1 local validation passed 10 tests, including separate tracking/registry stores, missing/access/dependency failures, -alias movement and Unity Catalog name validation. Live UC and Databricks -validation remain SM-16; the G2 Spark runner consumes this concrete artifact in -that later platform gate. +alias movement and Unity Catalog name validation. SM-16 subsequently validated +the live UC-to-Spark workflow using the concrete registered bundle. Pre-existing `.tmp-*` directories remain outside this change. Preserve them; do not stage or delete them as part of the next task. -## SM-15 delivery and next platform boundary +## SM-15 delivery and completed platform boundary The monthly runner now reads a pinned Delta snapshot, checks its availability at `as_of`, runs either Spark inference mode and atomically replaces one period @@ -133,19 +148,19 @@ schema, code example, diagram, retry policy and limits. `LocalTableLock` uses cross-process OS locks and requires a common directory on one host. Both public entry points reject it on distributed Spark masters. -SM-16 must implement or validate distributed publish admission; the provider -protocol is not proof that Databricks has a coordinator. Expiring leases cannot +SM-16 added and validated shared Delta-table admission. Expiring leases cannot protect this sink because it has no fencing-token mechanism. Every publisher -must use the same authority. Test actual Delta/UC permissions in that lane. +must use the same authority. Actual Delta/UC permission evidence is recorded +in the completed platform report. Keep the current source snapshot and original spec available for retries. A receipt returns the old committed version even after a newer recomputation, without writing again. New computation needs a new run ID and reviewed target version. History and transaction retention must cover the allowed retry window. -The first SM-16 registry-to-Spark smoke and platform evidence file are prepared; -see that file for the current wheel checksum, approved namespace and live run. -Inspect the submitted job result and finish the remaining platform gates. Databricks CLI +SM-16 is complete; see its evidence file for wheel checksums, approved namespace, +retained resources and finished runs. Start SM-15L without repeating these cloud +tests unless a new change requires them. Databricks CLI 1.17.0 is installed but absent from the current shell PATH; use its existing WinGet executable or a refreshed shell. The user confirmed `databricks.yml` is not needed in this repository; it is absent. DAB/templates and endpoints remain diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 7de3c25a0..0326959f9 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,9 +1,9 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-22. **SM-00–SM-15 complete; SM-16 ACTIVE. Target: 0.9.0.** +Updated: 2026-09-22. **SM-00–SM-16 complete; SM-15L READY. Target: 0.9.0.** Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. -Session resumed on 2026-09-22: read [HANDOFF.md](HANDOFF.md) before starting SM-16. +Read [HANDOFF.md](HANDOFF.md) before starting SM-15L. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -27,8 +27,8 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-13 | MLflow model packaging | SM-12 | DONE | Temiz ortamda pyfunc yükleme ve parity | | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | -| SM-16 | Gerçek Databricks kapısı | SM-15 | ACTIVE | Live UC/Spark parity passed: `447606109645160`; remaining platform gates open | -| SM-15L | Local pandas/Polars Delta sink | SM-16 | WAIT | Same period/retry guarantees; real local writer and UC access tests | +| SM-16 | Gerçek Databricks kapısı | SM-15 | DONE | Selected serverless workflow passed; live evidence below | +| SM-15L | Local pandas/Polars Delta sink | SM-16 | READY | Next: same period/retry guarantees; local writer and UC access tests | | SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | | SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | Parked | SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | Parked @@ -36,7 +36,7 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. ## Detay planlar -- Active SM-16 preparation and remaining gates: [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). +- Completed SM-16 evidence and scope: [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). - SM-15 currently provides the Spark writer only. The user's local-engine Delta requirement is tracked separately as SM-15L and must be satisfied before SM-20 offers that template combination. Template work remains last. @@ -54,7 +54,7 @@ gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. -## SM-16 — 2026-09-22 local preparation, still ACTIVE +## SM-16 — 2026-09-22 local and live validation, DONE - Baseline `d43e74ca`. Added a trusted pinned registry-bundle loader and a templates-free `databricks_batch_smoke.py` probe with pandas/Polars training, @@ -64,13 +64,25 @@ olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. Ruff/format, repository Ty and strict MkDocs passed. Wheel built locally; checksum, exact commands and remaining gates are in [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). -- Databricks plugin installed; CLI **1.17.0** verified. No profile was selected, - no authentication performed and no workspace resources created. The user - will provide the test namespace and compute. `databricks.yml` is absent as - requested; DAB/template generation remains later work. -- SM-16 is **not DONE**: live UC/job evidence, clean worker wheel deployment, - distributed admission, Delta platform retries/permissions and scale are open. - SM-15L separately tracks the newly clarified local-engine Delta sink requirement. +- Databricks CLI **1.17.0**, profile `skyulf`, approved isolated schema + `workspace.skyulf_sm16_20260922`. Live regression parity passed both Spark + modes in run `447606109645160`; restricted-principal model allow/deny and + 10k/50k synthetic parity passed in run `2921374308246`. +- Checkpoint `311547fc` adds serverless identifier handling and shared Delta + admission. Local gates passed 75 inference tests and 18 admission/batch tests. + The reusable monthly Delta probe passed 5 real Delta tests; live Delta/alias + run `810044894558535` reached an unsupported `REFRESH TABLE` command. + Narrow refresh/cache compatibility fixes passed 48 real Delta tests; corrected + run `783094949884769` passed monthly replacement/replay, alias pinning and + full worker package-content checks. `databricks.yml` remains absent. +- SM-16 is **DONE** for the selected serverless workflow: winner job + `973709879452231` committed only after the contender verified held-owner + rejection. Contender `404334394214907` then failed a test-only permission-code + assertion; final restricted job `977447944071613` passed actual MODIFY denial, + unchanged data/version and owner release. The failed run remains documented. +- SM-15L is **READY** and next: local pandas/Polars Delta sink with explicit + storage/provenance limits and separately validated UC access. No implementation + of that local sink is included in SM-16. ## SM-15 — 2026-09-22 validation record diff --git a/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md b/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md index 921f51aa7..1dd9985c8 100644 --- a/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md +++ b/initiatives/spark_and_mlflow/PLATFORM_VALIDATION.md @@ -1,8 +1,16 @@ # SM-16 platform validation -Status: **ACTIVE — live registry/Spark parity passed; remaining platform gates open**. +Status: **DONE — selected serverless Connect workflow validated on 2026-09-22**. Baseline: `d43e74ca`, branch `090`, target release `0.9.0`. +The [machine-readable evidence](reports/2026-09-22-sm16-live-evidence.json) was +generated after asserting the actual live results, matching model/table/trial +identities and the r3 wheel checksum. It combines five successful reports and +the explicitly retained contender assertion failure. Individual stage reports +keep `platform_gate_complete: false`; the aggregate records completion of G4. +This certifies the selected regression workflow, not every FE node, cloud +runtime, classification path or production workload. SM-15L remains separate. + ## Local preparation evidence — 2026-09-22 - Added `load_registered_bundle` with local registry tests: concrete version @@ -22,8 +30,8 @@ Baseline: `d43e74ca`, branch `090`, target release `0.9.0`. artifact root was moved under its temporary directory before the final gate. - Wheel built locally: `.cache/sm16-dist/skyulf_core-0.9.0-py3-none-any.whl`. SHA-256: `ede03a571bf3de480e1acca8ddd9c5179efd832906c410f4a0a98f50709b4779`. - The wheel was uploaded to the approved workspace test folder. Installation and - worker execution remain pending the live job. Rebuild after code changes. + This was the first uploaded wheel; the corrected r2/r3 hashes and successful + driver/worker checks are recorded below. Rebuild after code changes. Exact local commands: @@ -129,11 +137,121 @@ the isolated test folder. It has no admin role, data-modification grant or created token/secret. The requesting account retains its existing manager role and gained the user role on this test principal so it can submit `run_as` jobs. -Run `2921374308246` was submitted with this `run_as` identity and a 900-second -timeout. It checks allowed model loading, denied access to the first test model, -worker package provenance and 10k/50k synthetic prediction aggregates. It does -not write tables. Its result is pending; submitting a job is not permission-test -evidence. Prepared notebook/request are under `.cache/sm16-live-permissions*`. +Run `2921374308246`, task `479913572085165`, completed **SUCCESS** with this +`run_as` identity. Allowed model loading passed and the first test model returned +`RegistryAccessError`. No token/secret was created and no data table was written. +Two worker probes imported non-editable `skyulf-core 0.9.0` from ephemeral +`site-packages`; package-content digests are checked in the next stage. + +| Rows / requested partitions | Mode | Action time | Maximum absolute error | +| --- | --- | --- | --- | +| 10,000 / 2 | `native_features` | 9.91s | 8.89e-16 | +| 10,000 / 2 | `python_pipeline` | 2.07s | 8.89e-16 | +| 50,000 / 8 | `native_features` | 20.37s | 8.89e-16 | +| 50,000 / 8 | `python_pipeline` | 2.33s | 8.89e-16 | + +Each aggregate checked row count, distinct key count and the independent `2*x` +oracle. These sequential synthetic runs include different validation work and +warm-up effects; they are not a controlled engine benchmark or capacity claim. +Notebook/Connect client Python process-lifetime peak RSS was 2,276,596 KiB +for all four observations. This is not Spark JVM or total cluster memory. +The separate worker import probes recorded 536,040 and 534,688 KiB peak RSS; +those are not peak measurements of the inference task itself. Raw evidence and +the prepared notebook/request are under `.cache/sm16-live-permissions*`. + +### Monthly Delta and alias stage + +The reusable `examples/databricks_delta_smoke.py` passed **5 real Delta tests** +in 62.76s, plus Ruff/format/Ty and independent review. It retains three unique +test-owned tables and exercises real public batch publication, replay, +stale-version rejection, empty protection and explicit empty replacement. +Parent run `810044894558535`, task `499533558954860`, used the same `r2` wheel +and **FAILED** at the admission provider's `REFRESH TABLE` call with structured +`NOT_SUPPORTED_WITH_SERVERLESS`. It created the seeded test tables +`workspace.skyulf_sm16_20260922.skyulf_delta_smoke_837cbd4e7c274c0f905f84adce1d8c89_{source,target,control}`; +no batch publication began. These resources are retained. + +Before that failure, worker package assertions and the alias test completed. +The worker check compared all 225 installed Skyulf package files with the +wheel's package-content digest +`f887a4251f03fddb478b0d263afcd8328d9f7f81398e7da857c00d694a8cf97b`. +The test created alias `sm16_validation`, pinned version 1, registered a +numerically different `3*x` model version and moved the alias. The pinned bundle +still predicted 4 for x=2 while the alias-selected bundle predicted 6. The failure +trace reached the subsequent Delta stage; the notebook's final JSON was not +produced. The successful r3 retry below repeated the content and pinned-load +assertions without moving the alias again. + +The admission correction preserves refresh on classic Spark and catches only +the structured serverless restriction. It still reads identity and ownership; +exclusivity comes from the conditional Delta UPDATE and a fresh UUID token. +Other failures propagate. The official serverless limitations also prohibit +DataFrame `persist`/`unpersist`. The batch runner now catches only the same +structured serverless restriction from `persist`, preserves the distributed +frame, and calls `unpersist` only after successful caching. Other cache errors +propagate. Validation/publication can recompute uncached predictions. + +The combined real Delta gate passed **48 tests** in 173.18s: 24 batch tests, +19 admission tests and 5 probe tests. It covers both inference modes without +caching, unrelated-error propagation, classic cache cleanup, fresh ownership +reads with refresh rejected, and actual monthly transactions. Independent review +found no blocker. The base integration lane passed 41 with 53 optional skips. + +Retry parent run `783094949884769` completed **SUCCESS** using +`.cache/sm16-dist-r3/skyulf_core-0.9.0-py3-none-any.whl`: + +- Wheel SHA-256: `e2ce61eb3f11f25dd334934b9b45832cc3901ceba2aa04a5a28bb091232a29c5`. +- Package-content digest (225 files): `2d5da10303be00bd58c2cb5f6f2e468ad54bfd683181c5b511f09fa2aedd78f0`. + +Task run `26007003170545` returned all eight monthly checks as true: publication, +replay, stale-version rejection, empty rejection, explicit empty replacement, +empty replay, ownership release and preservation of the prior period. Initial +publication and replay used source snapshot 0 and returned commit 1; empty +replacement and its replay used source snapshot 1 and returned commit 2. +The target ended at version 2 with only the prior-period row. + +Retained tables share prefix +`workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_`: + +| Suffix | Delta table ID | Version after monthly probe | Rows | +| --- | --- | --- | --- | +| `source` | `36b4f01d-3378-48e9-a93f-c593b634acef` | 1 | 1 | +| `target` | `f16a3d46-8a00-4c55-9ac8-8f7690b17647` | 2 | 1 | +| `control` | `fe57f94d-a91a-44c1-a294-d0caaee19f7f` | 10 | 1 | + +The report confirms reloading pinned version 1 after alias `sm16_validation` +moved to version 2, with distinct digests and the expected 4 versus 6 predictions. +Two worker partitions each checked all 225 installed package files against the +r3 package-content digest. The full result is saved locally in +`.cache/sm16-live-delta-output-r3.json`. + +Independent contention jobs used the same r3 wheel: winner +`973709879452231` and restricted-principal contender `404334394214907`. +They share trial `3d74ef662d5047dfb90a13ec42dc5eaa` and the retained tables above. +The restricted principal has SELECT on source/target and SELECT/MODIFY on the +control table. The winner completed **SUCCESS**, committing version 3 and +releasing ownership. The contender passed the held-owner conflict, unchanged +owner/version-2 assertions and acknowledgement before the winner could commit. +It then acquired admission and reached an actual target write denial. + +The contender run is **FAILED**, because its test accepted only condition names +containing `PERMISSION` or `PRIVILEGE`. Databricks returned `UNAUTHORIZED_ACCESS`; +the chained error explicitly states `PERMISSION_DENIED` and missing `MODIFY` on +the exact target. This is a probe assertion mismatch, not a successful job or a +product-code defect. Its final preservation assertions were not executed. +The restricted-only follow-up run `977447944071613`, task `396353814917782`, +completed **SUCCESS**. It verified the winner's rows/metadata, target version 3 +and released ownership before and after another denied write, accepting only +the observed exact condition and message. Data and version remained unchanged. +The paired-run contention assertions and this final permission probe jointly +close admission and write-denial gates; the initial failed run remains failed. + +Live records: [winner](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/970586457713217/run/973709879452231), +[contender with assertion mismatch](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/602255242801236/run/404334394214907), +[final write-denial probe](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/555471604714601/run/977447944071613). +The signal table is +`workspace.skyulf_sm16_20260922.skyulf_contention_3d74ef662d5047dfb90a13ec42dc5eaa`. +All test resources and the restricted identity are retained for inspection. References: [Serverless restrictions](https://docs.databricks.com/aws/en/compute/serverless/limitations), [Databricks identifier rules](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-identifiers). @@ -153,8 +271,8 @@ shared Delta admission. Predictions, prior-period rows, the original receipt and owner release after both calls were verified. Base regression passed **80 tests**, with **48 optional-runtime skips** and one known Windows physical core detection warning. Ruff/format/Ty, strict MkDocs and independent review -passed. Live serverless/UC admission, -competing jobs and permission enforcement remain pending. See the +passed. The later live monthly run verified serverless/UC admission; +independent contention and permission runs are recorded above. See the [batch guide](../../docs/user_guide/databricks_batch.md) for provisioning and the explicit cooperative-writer and manual-recovery boundaries. @@ -204,18 +322,18 @@ contain pickle. Digests detect mismatched artifacts; they do not authenticate an untrusted producer. Downloads use explicit stores and the pinned version, including when a previously resolved alias has moved. -## Full platform gate still required +## Completed platform gate and evidence boundaries | Gate | Required evidence | Current state | | --- | --- | --- | | Selected environment | Profile, workspace, compute ID/type, DBR/Python/Spark/MLflow/Arrow | `skyulf`; serverless Connect; successful runtime recorded above | -| Package delivery | Exact wheel/checksum, installed distribution on clean driver/workers | Non-editable driver + worker prediction passed; per-worker provenance pending | -| Real UC round-trip | Concrete model version, alias pinning and trusted bundle download | Register/download/local checks reached; alias gate pending | +| Package delivery | Exact wheel/checksum, installed distribution on clean driver/workers | Non-editable driver and workers passed; 225-file content checks passed in r3 | +| Real UC round-trip | Concrete model version, alias pinning and trusted bundle download | Register/download passed; pinned version 1 survives alias movement to version 2 | | Spark parity | Gold data, both FE modes, key-based predictions, job run ID/URL | Passed in live corrected run `447606109645160` | -| Monthly publication | Real test Delta tables, snapshots, commits, replay, other periods preserved | SM-15 local evidence only | -| Distributed admission | Shared authority, ownership through commit, competing-job result | Implemented; real local Delta tests passed; live gate pending | -| UC permissions | Actual denied and allowed access in the approved namespace | Pending | -| Scale | Synthetic distributed dataset, runtime and driver/worker memory evidence | Pending | +| Monthly publication | Real test Delta tables, snapshots, commits, replay, other periods preserved | Passed in live run `783094949884769`; source versions 0/1, target commits 1/2 | +| Distributed admission | Shared authority, ownership through commit, competing-job result | Winner committed version 3 only after contender verified held-owner rejection; released afterward | +| UC permissions | Actual denied and allowed access in the approved namespace | Model allow/deny passed; target MODIFY denied with unchanged version/data and released admission in final probe | +| Scale | Synthetic distributed dataset, runtime and scoped memory observations | 10k/50k parity/timing + client Python lifetime peak and separate worker import RSS recorded; not inference-worker or cluster peak | Do not use `LocalTableLock` on a distributed Databricks driver. Limiting one job's concurrent runs does not coordinate other jobs or external writers. @@ -231,8 +349,8 @@ template is optional. Even Python-defined bundle resources use a root `databricks.yml` entry point. A model artifact does not automatically generate the code, compute selection, permissions and job definition needed for a bundle. -For SM-16, prepare the script/wheel and use a reviewed job request after the -user selects the platform. Reusable templates remain SM-20. A future generated +SM-16 used script/wheel uploads and reviewed one-time job requests against the +user-selected workspace. Reusable templates remain SM-20. A future generated project can contain its own `databricks.yml`; the Skyulf library repository does not need one for these tests. @@ -256,4 +374,13 @@ Track **SM-15L** before template support advertises local-engine Delta output: Catalog managed table can be written through that path. - Validate UC access separately; fail unsupported combinations explicitly. -Reference: [delta-rs writing](https://delta-io.github.io/delta-rs/usage/writing/). +As of 2026-09-22, Databricks documents external managed-table writes through +Unity REST as preview functionality requiring catalog commits and a supported +client. Its supported-client list does not establish delta-rs support. Therefore +a local filesystem delta-rs test cannot close the UC writer requirement. Evaluate +an explicit pandas/Polars inference plus Spark catalog-I/O path separately from +the optional standalone delta-rs sink; keep local data collection bounded and +visible in that API. This is a follow-up design constraint, not implemented support. + +References: [delta-rs transactions](https://delta-io.github.io/delta-rs/api/transaction/), +[Databricks external Delta access](https://docs.databricks.com/aws/en/external-access/unity-rest). diff --git a/initiatives/spark_and_mlflow/reports/2026-09-22-sm16-live-evidence.json b/initiatives/spark_and_mlflow/reports/2026-09-22-sm16-live-evidence.json new file mode 100644 index 000000000..9693efb16 --- /dev/null +++ b/initiatives/spark_and_mlflow/reports/2026-09-22-sm16-live-evidence.json @@ -0,0 +1,190 @@ +{ + "validated_on": "2026-09-22", + "platform_gate_complete": true, + "scope": "Selected serverless Connect regression workflow; bounded synthetic scale smoke.", + "runtime": { + "python": "3.12.3", + "spark": "4.2.0", + "mlflow": "3.16.1", + "pyarrow": "25.0.1", + "pandas": "2.2.3", + "polars": "1.44.2", + "scikit_learn": "1.6.1", + "databricks_runtime": "client.4.10" + }, + "wheel_version": "0.9.0", + "r3_wheel_sha256": "e2ce61eb3f11f25dd334934b9b45832cc3901ceba2aa04a5a28bb091232a29c5", + "model_name": "workspace.skyulf_sm16_20260922.probe_3e8e88a3d2f2435a9c2b7b280a184bc2", + "model_version": "1", + "model_digest": "66890475ca608271a6115ed2505890740bd6669fd9301711f9032390b4ea8084", + "prediction_parity_passed": true, + "input_snapshots": { + "initial_and_replay": 0, + "empty_and_replay": 1, + "contention": 0 + }, + "job_run_ids": { + "registry": 447606109645160, + "permissions_and_scale": 2921374308246, + "monthly": 783094949884769, + "winner": 973709879452231, + "contender_failed_assertion": 404334394214907, + "write_denial": 977447944071613 + }, + "contention_evidence": "Winner SUCCESS after waiting for contender REJECTED acknowledgement. Contender FAILED only in subsequent write-denial error-code assertion; its prior conflict/owner/version checks passed. Final restricted-only run verifies actual denial and unchanged data/version/released owner.", + "monthly_report": { + "stage": "delta_publication", + "platform_gate_complete": false, + "checks": { + "publication": true, + "replay": true, + "stale_rejected": true, + "empty_rejected": true, + "empty_replacement": true, + "empty_replay": true, + "ownership_released": true, + "prior_period_preserved": true + }, + "model_name": "workspace.skyulf_sm16_20260922.probe_3e8e88a3d2f2435a9c2b7b280a184bc2", + "model_version": "1", + "model_digest": "66890475ca608271a6115ed2505890740bd6669fd9301711f9032390b4ea8084", + "code_version": "0.9.0", + "tables": { + "source": { + "name": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_source", + "id": "36b4f01d-3378-48e9-a93f-c593b634acef", + "version": 1, + "count": 1 + }, + "target": { + "name": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_target", + "id": "f16a3d46-8a00-4c55-9ac8-8f7690b17647", + "version": 2, + "count": 1 + }, + "control": { + "name": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_control", + "id": "fe57f94d-a91a-44c1-a294-d0caaee19f7f", + "version": 10, + "count": 1 + } + }, + "receipts": { + "first": { + "commit_version": 1, + "input_count": 2, + "output_count": 2, + "replayed": false + }, + "replay": { + "commit_version": 1, + "input_count": 2, + "output_count": 2, + "replayed": true + }, + "empty": { + "commit_version": 2, + "input_count": 0, + "output_count": 0, + "replayed": false + }, + "empty_replay": { + "commit_version": 2, + "input_count": 0, + "output_count": 0, + "replayed": true + } + }, + "alias_report": { + "pinned_version": "1", + "alias_version": "2", + "alias": "sm16_validation", + "checks": { + "reload_after_prior_alias_movement": true + }, + "movement_run": 810044894558535 + }, + "worker_report": [ + { + "rows": 8, + "files": 225, + "package_digest": "2d5da10303be00bd58c2cb5f6f2e468ad54bfd683181c5b511f09fa2aedd78f0" + }, + { + "rows": 8, + "files": 225, + "package_digest": "2d5da10303be00bd58c2cb5f6f2e468ad54bfd683181c5b511f09fa2aedd78f0" + } + ] + }, + "winner_report": { + "role": "winner", + "commit_version": 3, + "ownership_released": true, + "run_id": "sm16-3d74ef662d5047dfb90a13ec42dc5eaa-winner", + "trial": "3d74ef662d5047dfb90a13ec42dc5eaa", + "source": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_source", + "target": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_target", + "control": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_control", + "signal": "workspace.skyulf_sm16_20260922.skyulf_contention_3d74ef662d5047dfb90a13ec42dc5eaa", + "platform_gate_complete": false + }, + "loser_report": { + "stage": "restricted_delta_write_denial", + "principal": "9559edaa-81e3-434b-a679-35703510c134", + "trial": "3d74ef662d5047dfb90a13ec42dc5eaa", + "target_write_denied": true, + "denied_condition": "UNAUTHORIZED_ACCESS", + "target_version_before": 3, + "target_version_after": 3, + "target_data_unchanged": true, + "ownership_released": true, + "original_winner_rows_verified": true, + "source": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_source", + "target": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_target", + "control": "workspace.skyulf_sm16_20260922.skyulf_delta_smoke_4bbeac1816a04bbe854c85903256c41d_control", + "signal": "workspace.skyulf_sm16_20260922.skyulf_contention_3d74ef662d5047dfb90a13ec42dc5eaa", + "platform_gate_complete": false + }, + "registry_denial_type": "RegistryAccessError", + "scale_observations": [ + { + "rows": 10000, + "requested_partitions": 2, + "mode": "native_features", + "elapsed_seconds": 9.908594848000007, + "max_error": 8.881784197001252e-16, + "driver_process_peak_rss_kib": 2276596 + }, + { + "rows": 10000, + "requested_partitions": 2, + "mode": "python_pipeline", + "elapsed_seconds": 2.073023195000019, + "max_error": 8.881784197001252e-16, + "driver_process_peak_rss_kib": 2276596 + }, + { + "rows": 50000, + "requested_partitions": 8, + "mode": "native_features", + "elapsed_seconds": 20.367470204999904, + "max_error": 8.881784197001252e-16, + "driver_process_peak_rss_kib": 2276596 + }, + { + "rows": 50000, + "requested_partitions": 8, + "mode": "python_pipeline", + "elapsed_seconds": 2.3294997059999787, + "max_error": 8.881784197001252e-16, + "driver_process_peak_rss_kib": 2276596 + } + ], + "memory_scope": "driver_process_peak_rss_kib is notebook/Connect client Python lifetime peak; not Spark JVM or cluster memory. Worker import RSS was a separate probe, not inference memory.", + "limitations": [ + "No production performance claim.", + "No classification or Spark-fit cloud certification.", + "Admission covers cooperating writers using the same fixed control authority." + ] +} diff --git a/skyulf-core/examples/databricks_delta_smoke.py b/skyulf-core/examples/databricks_delta_smoke.py new file mode 100644 index 000000000..a09af3bfa --- /dev/null +++ b/skyulf-core/examples/databricks_delta_smoke.py @@ -0,0 +1,206 @@ +"""Exercise retained, test-owned Delta tables through the public batch runner. + +The caller supplies a pinned raw regression bundle with the known y=2*x oracle, +its concrete registry identity, and an existing schema or catalog.schema. This +probe creates three unique tables and retains them even on failure. It neither +creates schemas nor grants permissions. Runtime failures propagate unchanged; +passing this probe does not complete the full Databricks platform gate. +""" + +import json +import re +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from importlib.metadata import version +from typing import Any +from uuid import uuid4 + +import numpy as np + +from skyulf.core.execution import ExecutionOptions +from skyulf.inference.bundle import InferenceBundle +from skyulf.integrations.databricks.admission import BatchConflictError +from skyulf.integrations.databricks.batch import BatchResult, BatchSpec, run_batch +from skyulf.integrations.databricks.delta import table_identity +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + + +def _receipt(result: BatchResult) -> dict[str, Any]: + """Keep the verified commit and row counts without embedding runtime objects.""" + return { + "commit_version": result.commit_version, + "input_count": result.input_count, + "output_count": result.output_count, + "replayed": result.replayed, + } + + +def run_smoke( + spark: Any, + *, + namespace: str, + bundle: InferenceBundle, + model_name: str, + model_version: str, +) -> dict[str, Any]: + """Verify publication, retries, stale requests and explicit empty replacement. + + Supply a raw bundle whose only input feature is ``x`` and whose regression + prediction is ``2*x``. Mean imputation and scaling are supported. Table names + are printed before creation so a failed live run remains inspectable. Cleanup + belongs to the caller and must use only the three names owned by this run. + """ + if type(namespace) is not str or not re.fullmatch( + r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?", namespace + ): + raise ValueError("namespace must be a simple schema or catalog.schema.") + identity = uuid4().hex + names = { + role: f"{namespace}.skyulf_delta_smoke_{identity}_{role}" + for role in ("source", "target", "control") + } + spec = BatchSpec( + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + as_of=datetime.now(UTC) + timedelta(minutes=10), + row_keys=("id",), + output_table=names["target"], + model_name=model_name, + model_version=model_version, + source_version=0, + code_version=version("skyulf-core"), + run_id=f"smoke-{identity}", + model_digest=bundle.semantic_digest, + expected_target_version=0, + ) + print("Test-owned Delta tables (retained for inspection): " + json.dumps(names), flush=True) + february = (3, datetime(2026, 2, 1, tzinfo=UTC), 3.0) + spark.createDataFrame( + [ + (1, datetime(2026, 1, 1, tzinfo=UTC), 1.0), + (2, datetime(2026, 1, 31, tzinfo=UTC), 2.0), + february, + ], + "id long, event_time timestamp, x double", + ).write.format("delta").saveAsTable(names["source"]) + spark.createDataFrame( + [(9, datetime(2025, 12, 1, tzinfo=UTC), 99.0, "prior", model_name, model_version)], + "id long, event_time timestamp, prediction double, __skyulf_run_id string, " + "__skyulf_model_name string, __skyulf_model_version string", + ).write.format("delta").saveAsTable(names["target"]) + prior = spark.table(names["target"]).first() + spark.createDataFrame( + [(table_identity(spark, names["target"]), None)], "target_id string, owner string" + ).write.format("delta").saveAsTable(names["control"]) + admission = DeltaTableAdmission(spark, names["control"]) + + def execute(request: BatchSpec) -> BatchResult: + """Use the public batch API and verify ownership release after each success.""" + result = run_batch( + spark, + request, + source=names["source"], + bundle=bundle, + options=ExecutionOptions("spark"), + admission=admission, + ) + if spark.table(names["control"]).first().owner is not None: + raise AssertionError("Successful batch retained admission ownership.") + return result + + first = execute(spec) + rows = spark.table(names["target"]).orderBy("id").limit(4).collect() + if [row.id for row in rows] != [1, 2, 9] or rows[-1] != prior: + raise AssertionError("Publication changed row membership or the prior period.") + np.testing.assert_allclose([row.prediction for row in rows], [2.0, 4.0, 99.0], atol=1e-10) + replay = execute(spec) + if ( + first.replayed + or not replay.replayed + or first.input_count != 2 + or first.output_count != 2 + or first.commit_version != replay.commit_version + or first.manifest != replay.manifest + or spark.table(names["target"]).orderBy("id").limit(4).collect() != rows + ): + raise AssertionError("Replay changed the original commit receipt or predictions.") + try: + execute(replace(spec, run_id=spec.run_id + "-stale")) + except BatchConflictError as exc: + if "Target version changed" not in str(exc): + raise + else: + raise AssertionError("A stale expected target version was admitted.") + if spark.table(names["control"]).first().owner is not None: + raise AssertionError("Stale-request rejection retained admission ownership.") + spark.createDataFrame([february], "id long, event_time timestamp, x double").write.format( + "delta" + ).mode("overwrite").saveAsTable(names["source"]) + empty_spec = replace( + spec, + run_id=spec.run_id + "-empty", + source_version=1, + expected_target_version=first.commit_version, + as_of=datetime.now(UTC) + timedelta(minutes=10), + ) + try: + execute(empty_spec) + except ValueError as exc: + if "allow_empty" not in str(exc): + raise + else: + raise AssertionError("Empty replacement did not require explicit consent.") + if spark.table(names["target"]).orderBy("id").limit(4).collect() != rows: + raise AssertionError("A rejected request changed target predictions.") + empty = execute(replace(empty_spec, allow_empty=True)) + empty_replay = execute(replace(empty_spec, allow_empty=True)) + if ( + empty.replayed + or not empty_replay.replayed + or empty.commit_version != empty_replay.commit_version + or empty.commit_version != first.commit_version + 1 + or empty.manifest != empty_replay.manifest + or empty.input_count != 0 + or empty.output_count != 0 + or spark.table(names["target"]).limit(2).collect() != [prior] + ): + raise AssertionError("Explicit empty replacement or its replay changed the prior period.") + return { + "stage": "delta_publication", + "platform_gate_complete": False, + "checks": dict.fromkeys( + ( + "publication", + "replay", + "stale_rejected", + "empty_rejected", + "empty_replacement", + "empty_replay", + "ownership_released", + "prior_period_preserved", + ), + True, + ), + "model_name": model_name, + "model_version": model_version, + "model_digest": bundle.semantic_digest, + "code_version": spec.code_version, + "tables": { + role: { + "name": name, + "id": table_identity(spark, name), + "version": int(spark.sql(f"DESCRIBE HISTORY {name}").first().version), + "count": spark.table(name).count(), + } + for role, name in names.items() + }, + "receipts": { + key: _receipt(result) + for key, result in ( + ("first", first), + ("replay", replay), + ("empty", empty), + ("empty_replay", empty_replay), + ) + }, + } diff --git a/skyulf-core/skyulf/integrations/databricks/batch.py b/skyulf-core/skyulf/integrations/databricks/batch.py index 7c1b4bb5f..f4786ebcf 100644 --- a/skyulf-core/skyulf/integrations/databricks/batch.py +++ b/skyulf-core/skyulf/integrations/databricks/batch.py @@ -33,6 +33,8 @@ def run_batch( correctness of upstream feature joins. The caller binds a concrete registry version to ``model_digest`` when constructing the spec. Both existing Spark inference modes are supported. Tables and Spark sessions remain caller-owned. + Output stays distributed when serverless rejects persistence; classic Spark + caches it through receipt validation and then releases the cached frame. """ if not isinstance(options, ExecutionOptions) or options.engine != "spark": raise ValueError("run_batch requires ExecutionOptions(engine='spark').") @@ -97,7 +99,18 @@ def run_batch( target = spark.table(spec.output_table) if {f.name: f.dataType for f in output.schema} != {f.name: f.dataType for f in target.schema}: raise ValueError("Output schema must match the precreated Delta target exactly.") - output = output.select(*target.columns).persist() + output = output.select(*target.columns) + persisted = False + try: + output = output.persist() + except Exception as exc: # noqa: BLE001 - Spark Connect wraps structured runtime errors + condition = getattr(exc, "getCondition", None) + if not callable(condition): + condition = getattr(exc, "getErrorClass", None) + if not callable(condition) or condition() != "NOT_SUPPORTED_WITH_SERVERLESS": + raise + else: + persisted = True try: output_count = output.count() if input_count != output_count: @@ -117,7 +130,8 @@ def run_batch( replayed, ) finally: - output.unpersist() + if persisted: + output.unpersist() def _manifest( diff --git a/skyulf-core/skyulf/integrations/databricks/delta_admission.py b/skyulf-core/skyulf/integrations/databricks/delta_admission.py index c5802d838..139dd0479 100644 --- a/skyulf-core/skyulf/integrations/databricks/delta_admission.py +++ b/skyulf-core/skyulf/integrations/databricks/delta_admission.py @@ -36,8 +36,18 @@ def __init__(self, spark: Any, control_table: str) -> None: self._control_id = self._identity() def _identity(self) -> str: - """Invalidate cached metadata and read the authority's current Delta ID.""" - self._spark.sql(f"REFRESH TABLE {self._quoted_table}").collect() + """Refresh where supported, then read the authority's current Delta ID. + + Serverless disallows both explicit refresh and user-managed Spark caches. + There we issue fresh Delta reads without a refresh command. The authority + must retain its fixed name/identity; external DDL remains unsupported. + """ + try: + self._spark.sql(f"REFRESH TABLE {self._quoted_table}").collect() + except Exception as exc: # noqa: BLE001 - classic and Connect expose different classes + condition = getattr(exc, "getCondition", None) or getattr(exc, "getErrorClass", None) + if not callable(condition) or condition() != "NOT_SUPPORTED_WITH_SERVERLESS": + raise return table_identity(self._spark, self._table) def _state(self, target_id: str) -> str | None: diff --git a/skyulf-core/tests/integrations/test_delta_admission.py b/skyulf-core/tests/integrations/test_delta_admission.py index d6a6769c0..610d6e193 100644 --- a/skyulf-core/tests/integrations/test_delta_admission.py +++ b/skyulf-core/tests/integrations/test_delta_admission.py @@ -11,6 +11,49 @@ from skyulf.integrations.databricks.admission import BatchConflictError +class ServerlessRefreshError(Exception): + """Represent the structured error observed from serverless REFRESH TABLE.""" + + def getCondition(self): + """Expose the public Spark error condition without parsing its message.""" + return "NOT_SUPPORTED_WITH_SERVERLESS" + + +def test_serverless_refresh_restriction_preserves_identity_read(monkeypatch): + """Serverless must still read the Delta identity when explicit refresh is unavailable.""" + from types import SimpleNamespace + + module = importlib.import_module("skyulf.integrations.databricks.delta_admission") + reads = [] + + def sql(statement): + """Reproduce the exact live failure before DESCRIBE DETAIL can execute.""" + assert statement == "REFRESH TABLE `default`.`authority`" + raise ServerlessRefreshError() + + def identity(spark, table): + """Record the identity read that must follow a rejected cache operation.""" + reads.append(table) + return "immutable-control-id" + + monkeypatch.setattr(module, "table_identity", identity) + provider = module.DeltaTableAdmission(SimpleNamespace(sql=sql), "default.authority") + assert provider._control_id == "immutable-control-id" + assert reads == ["default.authority"] + + +def test_refresh_permission_failure_is_not_suppressed(): + """A missing privilege must never be treated as an unsupported cache operation.""" + from types import SimpleNamespace + + def sql(statement): + """Refuse access before any ownership operation can begin.""" + raise PermissionError("refresh access denied") + + with pytest.raises(PermissionError, match="refresh access denied"): + _provider(SimpleNamespace(sql=sql), "default.authority") + + def _provider(spark, table): """Load the optional provider without importing Spark in the base test lane.""" module = importlib.import_module("skyulf.integrations.databricks.delta_admission") @@ -53,6 +96,28 @@ def test_held_claim_rejects_second_session_then_releases(control): assert first.local_only is False +def test_serverless_refresh_restriction_preserves_committed_ownership(control, monkeypatch): + """Fresh Delta reads must see another owner's claim even without REFRESH TABLE.""" + spark, table, target = control + original = type(spark).sql + + def restricted(self, statement, *args, **kwargs): + """Reject only the cache command that real serverless compute rejects.""" + if statement.startswith("REFRESH TABLE "): + raise ServerlessRefreshError() + return original(self, statement, *args, **kwargs) + + monkeypatch.setattr(type(spark), "sql", restricted) + first = _provider(spark, table) + second = _provider(spark.newSession(), table) + with first.hold(target): + owner = spark.table(table).first().owner + with pytest.raises(BatchConflictError), second.hold(target): + pytest.fail("A second publisher ignored committed ownership.") + assert spark.table(table).first().owner == owner + assert spark.table(table).first().owner is None + + def test_body_failure_releases_claim(control): """A failed publication must permit a deliberate subsequent retry.""" spark, table, target = control diff --git a/skyulf-core/tests/integrations/test_delta_publish.py b/skyulf-core/tests/integrations/test_delta_publish.py index 5c4698bbd..630d7d68a 100644 --- a/skyulf-core/tests/integrations/test_delta_publish.py +++ b/skyulf-core/tests/integrations/test_delta_publish.py @@ -289,3 +289,86 @@ def hold(self, table_id): admission=DeniedAdmission(), ) assert h.spark.sql(f"DESCRIBE HISTORY {h.target}").first().version == 0 + + +@pytest.mark.parametrize( + "mode,condition_api", + [("native_features", "getCondition"), ("python_pipeline", "getErrorClass")], +) +def test_serverless_cache_rejection_publishes_and_replays( + harness, monkeypatch, mode, condition_api +): + """Only structured serverless cache rejection may use distributed uncached publication.""" + h = harness + error = RuntimeError("cache unsupported") + monkeypatch.setattr( + error, condition_api, lambda: "NOT_SUPPORTED_WITH_SERVERLESS", raising=False + ) + + def reject_persist(frame, *args, **kwargs): + """Represent the rejected cache API while keeping every Spark/Delta action real.""" + raise error + + def reject_unpersist(frame, *args, **kwargs): + """Unpersist is also unsupported and must not follow a failed persist.""" + raise AssertionError("Unpersist called after rejected persistence.") + + frame_type = type(h.spark.table(h.source)) + monkeypatch.setattr(frame_type, "persist", reject_persist) + monkeypatch.setattr(frame_type, "unpersist", reject_unpersist) + spec = replace(h.spec, mode=mode) + first, replay = _run(h, spec), _run(h, spec) + rows = h.spark.table(h.target).orderBy("id").collect() + assert [row.id for row in rows] == [1, 2, 9] + assert [row.prediction for row in rows] == pytest.approx([2.0, 4.0, 99.0]) + assert rows[-1]["__skyulf_run_id"] == "prior" + assert first.input_count == first.output_count == 2 + assert first.commit_version == replay.commit_version == 1 + assert first.replayed is False + assert replay.replayed is True + assert first.manifest == replay.manifest + + +@pytest.mark.parametrize("structured", [False, True]) +def test_other_cache_errors_propagate_before_target_mutation(harness, monkeypatch, structured): + """Neither message text nor unrelated structured failures may bypass cache errors.""" + h = harness + error = RuntimeError("NOT_SUPPORTED_WITH_SERVERLESS") + if structured: + monkeypatch.setattr(error, "getCondition", lambda: "PERMISSION_DENIED", raising=False) + + def reject_persist(frame, *args, **kwargs): + """Fail only at the real prediction frame's optional cache boundary.""" + raise error + + monkeypatch.setattr(type(h.spark.table(h.source)), "persist", reject_persist) + before = h.spark.table(h.target).collect() + with pytest.raises(RuntimeError) as caught: + _run(h) + assert caught.value is error + assert h.spark.table(h.target).collect() == before + assert h.spark.sql(f"DESCRIBE HISTORY {h.target}").first().version == 0 + + +def test_classic_cache_is_released_after_success_and_conflict(harness, monkeypatch): + """Classic runtimes retain caching but release real persisted frames on every exit.""" + from skyulf.integrations.databricks.admission import BatchConflictError + + h = harness + frame_type = type(h.spark.table(h.source)) + persist = frame_type.persist + persisted = [] + + def retain_persisted_frame(frame, *args, **kwargs): + """Observe actual cache state without replacing Spark's persistence behavior.""" + result = persist(frame, *args, **kwargs) + assert result.storageLevel.useMemory + persisted.append(result) + return result + + monkeypatch.setattr(frame_type, "persist", retain_persisted_frame) + _run(h) + with pytest.raises(BatchConflictError): + _run(h, replace(h.spec, run_id="stale-cached-run")) + assert len(persisted) == 2 + assert all(not frame.storageLevel.useMemory for frame in persisted) diff --git a/skyulf-core/tests/integrations/test_platform_delta_smoke.py b/skyulf-core/tests/integrations/test_platform_delta_smoke.py new file mode 100644 index 000000000..a8004d233 --- /dev/null +++ b/skyulf-core/tests/integrations/test_platform_delta_smoke.py @@ -0,0 +1,85 @@ +"""Exercise the reusable Delta publication probe against real local transactions.""" + +import runpy +from pathlib import Path +from uuid import uuid4 + +import pytest + + +def test_delta_smoke_records_commits_and_retains_only_its_tables(delta_spark, monkeypatch): + """A known regression bundle must publish, replay and explicitly clear January safely.""" + examples = Path(__file__).parents[2] / "examples" + probe = examples / "databricks_delta_smoke.py" + assert probe.is_file(), "The reusable Delta smoke example is missing." + run_smoke = runpy.run_path(str(probe))["run_smoke"] + identity = uuid4() + monkeypatch.setitem(run_smoke.__globals__, "uuid4", lambda: identity) + owned = [ + f"default.skyulf_delta_smoke_{identity.hex}_{role}" + for role in ("source", "target", "control") + ] + build_bundle = runpy.run_path(str(examples / "databricks_batch_smoke.py"))["build_gold_bundle"] + bundle, _ = build_bundle("pandas") + try: + report = run_smoke( + delta_spark, + namespace="default", + bundle=bundle, + model_name="smoke_regression", + model_version="1", + ) + assert report["stage"] == "delta_publication" + assert report["platform_gate_complete"] is False + assert report["checks"] == { + "publication": True, + "replay": True, + "stale_rejected": True, + "empty_rejected": True, + "empty_replacement": True, + "empty_replay": True, + "ownership_released": True, + "prior_period_preserved": True, + } + assert report["model_digest"] == bundle.semantic_digest + assert report["model_name"] == "smoke_regression" + assert report["model_version"] == "1" + assert report["receipts"] == { + "first": {"commit_version": 1, "input_count": 2, "output_count": 2, "replayed": False}, + "replay": {"commit_version": 1, "input_count": 2, "output_count": 2, "replayed": True}, + "empty": {"commit_version": 2, "input_count": 0, "output_count": 0, "replayed": False}, + "empty_replay": { + "commit_version": 2, + "input_count": 0, + "output_count": 0, + "replayed": True, + }, + } + tables = report["tables"] + assert set(tables) == {"source", "target", "control"} + assert tables["source"]["version"] == 1 + assert tables["target"]["version"] == 2 + for entry in tables.values(): + assert delta_spark.catalog.tableExists(entry["name"]) + assert entry["count"] == 1 + assert delta_spark.sql(f"DESCRIBE DETAIL {entry['name']}").first()["id"] == entry["id"] + target_row = delta_spark.table(tables["target"]["name"]).first() + assert (target_row.id, target_row.prediction) == (9, 99.0) + control_row = delta_spark.table(tables["control"]["name"]).first() + assert control_row.target_id == tables["target"]["id"] + assert control_row.owner is None + finally: + for table in owned: + delta_spark.sql(f"DROP TABLE IF EXISTS {table}").collect() + + +@pytest.mark.parametrize("namespace", ["a.b.c", "default; DROP TABLE x", "", "a..b"]) +def test_delta_smoke_rejects_invalid_namespace_before_io(namespace): + """Invalid catalog qualification must fail before any Spark table operation.""" + probe = Path(__file__).parents[2] / "examples" / "databricks_delta_smoke.py" + assert probe.is_file(), "The reusable Delta smoke example is missing." + run_smoke = runpy.run_path(str(probe))["run_smoke"] + with pytest.raises(ValueError, match="namespace"): + run_smoke( + None, namespace=namespace, bundle=None, model_name="regression", model_version="1" + ) From bd8689bb498f6bf9991aebd698cfeae30b7e31cf Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 09:15:33 +0300 Subject: [PATCH 30/85] docs: plan local-first Databricks Bundle rollout Signed-off-by: flyingriverhorse --- .../03-mlflow-batch-delivery-plan.md | 236 +++++-- .../04-databricks-integration-plan.md | 391 +++++++++++ .../spark_and_mlflow/05-sm20-bundle-plan.md | 159 +++++ initiatives/spark_and_mlflow/HANDOFF.md | 57 +- initiatives/spark_and_mlflow/NODE_SUPPORT.md | 149 +++++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 627 +++--------------- .../OPEN_QUEUE_tamamlanmakaydi.md | 492 ++++++++++++++ initiatives/spark_and_mlflow/README.md | 110 ++- .../diagrams/local-engine-bundle.svg | 1 + .../2026-09-22-spark-databricks-gap-review.md | 168 +++++ 10 files changed, 1748 insertions(+), 642 deletions(-) create mode 100644 initiatives/spark_and_mlflow/04-databricks-integration-plan.md create mode 100644 initiatives/spark_and_mlflow/05-sm20-bundle-plan.md create mode 100644 initiatives/spark_and_mlflow/NODE_SUPPORT.md create mode 100644 initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md create mode 100644 initiatives/spark_and_mlflow/diagrams/local-engine-bundle.svg create mode 100644 initiatives/spark_and_mlflow/reports/2026-09-22-spark-databricks-gap-review.md diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index 7246b4a8b..3870668b7 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -2,12 +2,14 @@ > **For agentic workers:** Use `executing-plans`. Read > [ARCHITECTURE.md](ARCHITECTURE.md) and [OPEN_QUEUE.md](OPEN_QUEUE.md). -> SM-18–SM-20 start only after the core and platform gates. +> The first local Bundle is SM-20a; Spark enhancement follows it. -**Goal:** Opsiyonel tracking/registry, aylık tablo çıktısı ve son aşamada ürünleştirme. +**Goal:** Optional tracking/registry, local monthly UC output and a first local Bundle; +Spark becomes a later Bundle option. **Architecture:** Core sözleşmeleri platform I/O'dan ayrılır. MLflow pyfunc, SM-08 bundle'ını yükler; Databricks runner aynı inference girişini kullanır. -**Tech Stack:** MLflow, Unity Catalog, Spark/Delta, Databricks Jobs; en son DAB. +**Tech Stack:** MLflow, Unity Catalog, pandas/Polars, Databricks Jobs/Bundle; +Spark/Delta adapters extend the Bundle later. **Spec:** [ARCHITECTURE.md](ARCHITECTURE.md). ## Global constraints @@ -222,62 +224,78 @@ benchmark or blanket certification of all engines, node families or runtimes. ## SM-15L — Local-engine Delta publication -**Dependency:** SM-16. **Status:** READY; SM-16 completed on 2026-09-22. +**Dependency:** SM-24a. **Status:** WAIT; reopened by the later local-first Bundle request. The SM-15 delivery covers only the Spark runner. A Delta destination must not imply Spark inference; support for pandas/Polars publication needs its own sink. - [ ] Design explicit local source/target references and snapshot provenance; do not pass filesystem paths into the Spark-only table-name contract. -- [ ] Implement an optional Arrow/delta-rs writer for supported local data sizes. - No implicit collection of distributed Spark data into pandas/Polars. -- [ ] Match period, UTC/schema, empty-result, receipt, retry and admission - guarantees using actual Delta transactions, including stale concurrent runs. -- [ ] Validate storage access, table protocol features and UC compatibility for - each supported target type. Direct path writes do not establish UC table access. -- [ ] Expose the supported engine/sink combinations before SM-20 offers them. +- [ ] Prefer a bounded local-predictions -> Spark DataFrame bridge for UC Delta + publication. Use explicit output schema and preserve pandas/Polars prediction + values, row keys, labels and nulls. SQL Connector is an alternative, not required. +- [ ] Reuse guarded `publish_replace_period` logic where valid, but separate + the local publication request from `BatchSpec`'s Spark inference modes. +- [ ] Match period, UTC/schema, empty-result, receipt, retry and concurrency + guarantees with real UC transactions, including stale concurrent runs. +- [ ] Validate selected compute, storage, table protocol and permissions. + A direct delta-rs path write does not establish UC managed-table access. +- [ ] Expose only tested engine/sink combinations before SM-20a generates them. This is planned work, not an available `run_batch(engine="polars")` feature. -## SM-17 — Kalan node aileleri ve context desteği - -**Bağımlılık:** SM-16. **Kaynak:** rapordaki aile matrisi; -`skyulf/preprocessing/{encoding,feature_selection,vectorization,transformations}` -ve diğer ailelerin mevcut modülleri; capability tablosu. -**Oluştur:** `NODE_SUPPORT.md`, `tests/spark/test_node_support_matrix.py`; -her kabul edilen aile için `tests/spark/test__parity.py`. - -- [ ] İlk genişletme: column/cast/date/arithmetic, minmax/maxabs ve selection apply. - Fit local-only olsa da seçilmiş kolonları Spark apply destekleyebilir. -- [ ] İkinci genişletme: median/quantile ve kategorik encode. Exact/approximate - algoritma ayrı config; category order, unseen/null, büyük state tablo lookup - ve hash algoritması korunmadan native etiketi verme. -- [ ] Üçüncü: group fitted lookup, rolling/lag ve custom FE. Group/order/tie-break, - history cutoff, geçmiş veri erişimi ve partition boundary testleri zorunlu. -- [ ] Dördüncü: OOF target/WOE. Her fold'da train-only fit ve out-of-fold train - representation testleri. Dataset split/hash kuralı engine değişince değişmesin. -- [ ] SMOTE, yüksek boyutlu vectorizer/embedding, SHAP/CV/tuning ve native model - training için native/explicit bounded local/unsupported kararlarını kaydet. - Bağımsız algoritma portları aile bazlı ayrı testli alt görevler olur; SM-17 - bütün node'ların desteklendiği iddiasıyla kapatılamaz. - -```python -def test_declared_support_has_evidence(support_matrix): - """An advertised engine-operation pair must point to a passing parity case.""" - for entry in support_matrix: - if entry["status"] == "supported": - assert entry["fit_test"] or entry["operation"] == "apply" - assert entry["apply_test"] or entry["operation"] == "fit" - assert entry["runtime_evidence"] -``` - -`support_matrix` fixture registry/capability anahtarlarını NODE_SUPPORT ile -eşleştirir; eski tarihli test yolu tek başına evidence değildir. Her alt aile -uygulanmadan exact dosya/test/API dilimine ayrılır; unsupported aileler kullanıcıya -açıkça gösterilir. İlk release için tüm ailelerin native olması şart değildir. -**Kabul:** G5: ilan edilen support matrix gerçek testlerle tutarlı, diğerleri açık ret. +## SM-17 - Complete existing Spark node and model coverage + +**Dependency:** SM-20a. **Status:** LATER, after the first local Bundle. +The scope below is retained for Spark enhancement. Current local integration +work uses fitted pandas/Polars packages; see [the current plan](04-databricks-integration-plan.md). +The user's 2026-09-22 direction supersedes the earlier limited-family acceptance: +cover existing nodes and model paths, track every remaining gap, and do not close +SM-17 merely because unsupported combinations are listed. + +Starting artifacts: +- [NODE_SUPPORT.md](NODE_SUPPORT.md): 100 literal source registrations, including + aliases and optional model dependencies; all assigned to an owning task. +- [Gap review](reports/2026-09-22-spark-databricks-gap-review.md): source findings, + template-service comparison, training/inference distinctions and runtime constraints. +- [OPEN_QUEUE.md](OPEN_QUEUE.md): ordered SM-17-00 through SM-17k deliverables. + +- [ ] SM-17-00: expand every registration to per-configuration fit/apply/codec, + row/context and model-output contracts, with an inventory coverage guard. +- [ ] SM-17a-f: implement the complete FE/data families in the queue, retaining + existing pandas/Polars behavior. Test exact versus approximate statistics, + category order, missing/unseen values, sparse/vector output, partition boundaries, + row membership, deterministic split and train-only/OOF state as applicable. +- [ ] SM-17g: extend explicit model serialization/prediction adapters to existing + model families. The current sklearn-only, single-output, probability-capable + regression/classification bundle is not a general model support guarantee. +- [ ] SM-17h: introduce explicit Spark-native distributed estimator training and + transform, artifact/version metadata and MLflow persistence. Preserve the local + estimator path; never silently substitute an algorithm or collect all training data. +- [ ] SM-17i: evaluation, CV/tuning, thresholds and explainability/SHAP for the + declared model backends. Distinguish parallel trials from one estimator learning + on distributed data; define explicit bounded/local or native explanation paths + and fail clearly when unavailable. No implicit full-data collection for SHAP. +- [ ] SM-17j: config-driven SDK entry point and runtime preflight, with independent + platform, FE/model engine, sink and optional tracking/registry selections. +- [ ] SM-17k: real per-family tests, artifact round trips, full pipeline gates and + selected Databricks evidence. Supported rows require actual matching evidence. + +Each implementation slice must identify exact APIs/files and tests before coding. +Native models may require a new artifact kind; maintain old bundle compatibility. +A Spark ML model and similarly named sklearn estimator are not automatically +numerically equivalent. Every source model ID needs an explicit disposition. +If equivalent native execution is infeasible, explain the limitation and keep +that work open for an explicit backend decision or user-approved deferral. + +**Acceptance:** G5 closes when the requested tracked coverage is implemented and +verified, or any remaining exclusions have been explicitly agreed with the user. +A rejection is the correct current runtime behavior for missing capabilities, +but does not by itself satisfy the requested feature-completion task. ## SM-18 — Backend/Canvas ve custom feature kullanımı +**Status: PARKED by the user on 2026-09-22. Do not implement until resumed.** + **Bağımlılık:** SM-17. **Mevcut:** `backend/ml_pipeline/_execution/engine/{__init__,_feature_eng,_artifacts,_node_runners}.py`, `backend/deployment/service.py`, @@ -306,7 +324,9 @@ ve `npm run build` kanıtı kayıtlı. ## SM-19 — En son inference erişim biçimleri -**Bağımlılık:** SM-18. **Oluştur:** +**Status: LATER - optional after the first local Bundle.** + +**Bağımlılık:** SM-25 and the current compatible pyfunc contract; no SM-18 dependency. **Oluştur:** `skyulf-core/examples/serving_prediction.py`, `skyulf-core/examples/sql_batch_prediction.sql` (repo köküne göre). **Mevcut:** `backend/deployment/service.py`, bundle/MLflow model adapter'ları. @@ -326,22 +346,126 @@ ve `npm run build` kanıtı kayıtlı. ## SM-20 — Template ve Databricks Bundle -**Bağımlılık:** SM-19. **Oluştur:** repo kökünde `templates/databricks/` ve +**Status: WAIT - SM-20a builds the local Bundle before Spark; SM-20b adds Spark later.** + +**Dependencies:** SM-20a needs SM-26, SM-25, SM-24a and verified SM-15L. +SM-20b needs selected validated Spark adapters; SM-19 only if endpoints are selected. +See [the dedicated SM-20 plan](05-sm20-bundle-plan.md) for generated resources +and the two-month UC source/output-table rehearsal. +**Planned files:** `templates/databricks/` and `tests/templates/test_databricks_template.py`; template dosyaları `databricks.yml`, `resources/batch_job.yml`, `README.md`, `src/run_batch.py`. -- [ ] Sorular: platform, FE engine, tracking, registry, batch/HTTP/SQL; birbirinden - bağımsız ve capability validation ile. Local + MLflow/UC geçerli; Databricks + - pandas/Polars küçük veri yolu geçerli. Unsupported kombinasyon açıklanır. +- [ ] Ask for platform, FE engine, artifact store and output only when the + combination has passed preflight. The first Databricks Bundle pins an + MLflow/UC model version; a tracking-off or registry-off Bundle needs its own + tested durable artifact handoff before it is offered. - [ ] Generated run_batch yalnız test edilmiş runner'ı çağırır; FE config ve custom feature module açık düzenleme noktalarıdır. İş mantığı kopyalanmaz. - [ ] Aylık schedule timezone, period/as_of parametreleri ve dev hedefi üret; secret value üretme. Schedule ile backfill data period'ünü karıştırma. -- [ ] İki fixture üret: local+Polars+tracking off ve Databricks+Spark+MLflow/UC. - Config syntax, import smoke ve bundle validate çalıştır; kullanıcıya ait ortamda - deploy/run ayrıca gerçek smoke ve yetkilendirme sınırıyla yapılır. +- [ ] İlk iki fixture: Databricks+pandas+MLflow/UC ve + Databricks+Polars+MLflow/UC; ayrıca tracking-off yerel kullanım testi. + Generated config/import ve bundle validate sonrasında ilk local Bundle için + gerçek deploy/run, UC table parity ve replay kanıtı topla. +- [ ] SM-20b'de yalnız doğrulanmış Spark kombinasyonunu ikinci seçenek olarak + ekle; local engine seçeneği korunur ve ayrı Spark bundle run testi yapılır. **Örnek assertion:** Generate → config load → runner preflight; engine seçimi manifestte korunur, endpoint seçilmediyse endpoint resource üretilmez. **Kabul:** G8: template çalışan core/runner'ları paketler; endpoint/batch seçimi isteğe bağlı; gerçek deployment kanıtı config validation'dan ayrı yazılır. + +## Selected Databricks follow-ups discovered during the reference review + +The user has selected these integrations for task definition before implementation. +Their current dependencies, sequence, proposed code areas and acceptance checks +are in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). +SM-26 local pipeline packaging is READY; SM-25, SM-24a, SM-15L and SM-20a +follow. SM-24b is optional later. SM-18 and SM-19c remain PARKED. Spark SM-17/SM-24c/SM-20b +follow the first working local Bundle. This planning update starts no deployment. + +### SM-19a/b/c/d - Endpoint detail + +- [ ] SM-19a: live HTTP endpoint create/update/readiness and inference parity using + a pinned compatible model package; dependency build, request schema, ACL and + timeout/error tests. No implicit SparkSession inside serving. +- [ ] SM-19b: SQL ai_query against the same existing endpoint; named feature struct, + return schema, CAN QUERY, row-level failures and capacity/rate handling. Preserve + model/version identity; SQL invocation is not a separate estimator backend. +- [ ] SM-19c (PARKED): optional streaming with explicit checkpoint, history/state and model + update contracts. Serverless continuous-trigger support must be checked separately. +- [ ] SM-19d: endpoint operations: scaling/cold start, A/B routing, rollback, + bounded retry/backoff, inference logging and real HTTP/SQL/load tests. + +### SM-21 - Feature tables and optional online lookup + +- [ ] Optional Databricks Feature Engineering adapter, separate from core FE nodes. +- [ ] Explicit primary/timestamp keys, point-in-time joins and training-set lineage. +- [ ] Packaged lookup metadata and batch score semantics, with same-model parity. +- [ ] Optional online publication/freshness and identity-only serving inputs; + absence/staleness behavior, privileges and offline/online parity tests. + +### SM-22 - Validation and controlled promotion + +- [ ] Candidate/champion evaluation reports using existing Skyulf metrics and + model output contracts; configured minimum quality and regression thresholds. +- [ ] Explicit version-pinned promotion, rollback and audit metadata. Evaluating + a model must not implicitly move production aliases or create a first champion. +- [ ] Reproducible validation dataset/split identity and promotion permission tests. +- [ ] Keep monthly retraining orchestration separate (SM-28): labels, temporal + cutoff, candidate training and validation precede any explicit promotion; + scoring resolves and pins the selected version once per run. + +### SM-23 - Monitoring and inference observability + +- [ ] Reuse current Skyulf quality/drift logic; optional Databricks monitoring + adapters and inference-table integration rather than duplicated metrics. +- [ ] Delayed labels, classification/regression output schemas, model version, + aggregation windows, freshness and observability coverage. +- [ ] Payload retention/redaction and monitoring/refresh permissions are explicit. + +### SM-24 - Job operation helpers + +- [ ] Validated period/backfill parameters, timezone, source snapshot, stable run + identity and resource scope, independent of a generated DAB project. +- [ ] Bounded timeout/retry policies, publication receipts, orphan-claim recovery + instructions and structured logs; no automatic takeover of a live owner. +- [ ] Optional job schedule/notification configuration and test/prod separation. +- [ ] Evaluate append/MERGE or other sink policies only as explicit separately + tested extensions; current replace-period guarantees do not transfer implicitly. + +### SM-25 - Supported-workflow SDK configuration and preflight + +**Dependency:** SM-26. **Status:** WAIT; follows the local artifact contract. +See [the detailed integration plan](04-databricks-integration-plan.md). +This extracts only the usability subset for current compatible bundles from +parked SM-17j; it does not implement broader native node/model coverage. + +- [ ] Independent runtime/engine/sink/tracking/registry configuration without secrets. +- [ ] Resolve bundle metadata and pinned model identity once; retain explicit + source snapshot, period, target version and retry identity. +- [ ] Preflight unsupported FE/model/runtime combinations before submission. +- [ ] Short pandas/Polars training -> local Databricks batch examples first; + Spark batch examples follow SM-20a. +- [ ] No remote mutations during validation; optional integration dependencies. + +### SM-26 - Local pandas/Polars pipeline MLflow packaging + +**Dependency:** SM-16 and existing standalone local persistence. **Status:** READY. +First in the revised local-first integration lane; see +[04-databricks-integration-plan.md](04-databricks-integration-plan.md) for code +areas, artifact boundaries and acceptance criteria. + +- [ ] SM-26a: audit local fitted pipeline/engine/model semantics and define a + versioned local artifact contract distinct from the portable Spark bundle. +- [ ] SM-26b: MLflow pyfunc package/load with no refit, explicit engine/input + conversion, signatures, original feature order and required dependencies. +- [ ] SM-26c: original/save/load/clean-environment parity for pandas and Polars, + including FE beyond the current portable subset; per-model eligibility evidence. +- [ ] Classify local whole-frame, row-local serving and distributed eligibility + independently; unsupported serving/Spark behavior remains an explicit rejection. + +Native Spark expansion follows the first local Bundle in SM-17; backend legacy +artifact bridging remains parked SM-18. Local UC Delta publication is SM-15L +on the critical path to SM-20a. diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md new file mode 100644 index 000000000..917052c66 --- /dev/null +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -0,0 +1,391 @@ +# Local-first Databricks integration and Bundle plan + +Updated: 2026-09-22. Planning only; no implementation or new cloud execution. +Baseline: `63dd3e21` and the completed, scoped SM-16 evidence. + +## Current direction + +The first deliverable is a small-data Databricks Bundle using pandas or Polars +for fitted FE and a Python model. Local means one Python process, which may run +inside a Databricks job; it does not mean the user's laptop. A bounded Spark +bridge may handle UC table I/O after local prediction; native Spark FE/model +execution remains a later task. Build and validate that project before extending +its prediction jobs with Spark. The latest direction reopens +SM-15L as a prerequisite for monthly UC table output in the first Bundle. +SM-18 Backend/Canvas work and continuous streaming remain parked. Full SM-17 +node/model expansion waits until the first local Bundle works. + +Latest refinement: **SM-26 comes first**, making broader existing fitted local +pandas/Polars pipelines usable through MLflow without waiting for native Spark +node ports. This is planned packaging work, not existing support. + +The first scenario is pandas/Polars FE and Python-model training, followed by +local Python batch prediction in a Databricks job and monthly publication to a +UC Delta table. Existing Spark support is limited: +native portable FE covers mean/constant SimpleImputer, StandardScaler and an +empty chain; model bundles support the documented sklearn regression/classification +contract. The worker Python-pipeline mode is also capability-gated, not a generic +fallback for arbitrary local FE. SM-26 expands local-package coverage through +explicit per-pipeline/model tests; it does not expand Spark compatibility. External +model libraries, clustering and custom behavior need their own local coverage +checks. Backend legacy artifact bridging remains parked in SM-18. + +Native Spark FE/model expansion stays in SM-17, after the local Bundle. The +first Bundle may reuse Spark solely to read/write UC tables, with local data +size limits and explicit schema conversion. Existing Spark inference remains +outside its first variant. Each integration gate uses a compatible fixture and rejects +unsupported configurations before submission. Existing local tests cover pandas +and Polars training; live SM-16 used a Polars-trained regression model. New local +UC publication and Bundle claims need their own cloud evidence. + +## Boundaries and reuse + +- Reuse existing `predict_local` and MLflow tracking/model/registry adapters for + the first Bundle. Evaluate a bounded local-result -> Spark DataFrame bridge + to reuse guarded Delta publication, with a distinct local batch contract. + Later Spark inference variants reuse `predict_spark` and `run_batch`. +- Keep platform, FE engine, model execution, sink and optional tracking/registry + independent. Local execution can run inside a Databricks job. +- No implicit Spark-to-pandas collection, node substitution, refitting or alias + promotion. Known artifact schema/order/digests should be derived once. +- Keep `as_of`, period, source snapshot, target version and logical retry identity + explicit. The local publication path needs its own verified retry/transaction + guard before the template advertises monthly UC output. +- Config parsing and validation have no remote mutation. Resource provisioning, + submission, endpoint updates, promotions and cleanup are explicit operations. +- Databricks optional dependencies belong in integration modules, not core nodes. +- No new Skyulf repository root `databricks.yml`; the generated Bundle project + has its own required root `databricks.yml`. Templates call tested services + rather than copy their business logic. +- The reference is a design input, not a certified dependency or code copied into + Skyulf. See the [source comparison](reports/2026-09-22-spark-databricks-gap-review.md). + +## Recommended sequence + +| Order | Task | Depends on | State | +| --- | --- | --- | --- | +| 1 | SM-26: local pipeline MLflow packaging | SM-16; existing local persistence | READY | +| 2 | SM-25: local-first SDK configuration and preflight | SM-26 | WAIT | +| 3 | SM-24a: local training and bounded batch prediction | SM-25 | WAIT | +| 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | WAIT | +| 5 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; verified SM-15L | WAIT | +| After first Bundle | SM-27: bounded full-history rescore and selectable Bundle mode | SM-20a; SM-15L | LATER | +| After first Bundle | SM-22 then SM-28: validation/promotion and optional monthly retraining | SM-20a; SM-22 for SM-28 | LATER | +| Later | SM-24b, SM-19, SM-21, SM-23: optional Jobs API, serving, feature lookup and monitoring | Relevant local adapters | LATER | +| After local Bundle | SM-24c and SM-17: Spark workflow then broader Spark coverage | SM-20a | LATER | +| After selected Spark gates | SM-20b: add tested Spark option to the Bundle | SM-24c; relevant SM-17 slices | LATER | + +The first Bundle needs a working, bounded local input and a verified monthly +UC output; it does not need model promotion, online lookup, HTTP, SQL, A/B, +Canvas, or Spark FE/model execution. Spark may handle UC table I/O only. +The local-first follow-ups add full-history rescore and optional monthly +retraining before broad Spark inference expansion. + +## SM-26 - Broader local pipeline MLflow packaging + +Proposed areas: standalone pipeline persistence/prediction contracts, +`skyulf-core/skyulf/integrations/mlflow/`, integration tests and the MLflow guide. +Reuse existing fitted pipeline behavior; do not implement another FE engine. + +- [ ] SM-26a: audit existing standalone save/load/predict semantics, fitted FE, + local engine selection, schema/order, labels/probabilities/thresholds and model + dependencies. Define a versioned local artifact contract distinct from the + existing portable bundle; retain backward compatibility and trusted loading. +- [ ] SM-26b: package and restore the fitted local pipeline through MLflow pyfunc. + Preserve learned state without refit. An MLflow pandas input boundary must not + silently switch an engine-sensitive Polars pipeline; any conversion is explicit + and preserves dtypes, nulls, column order and output semantics. +- [ ] Include the required code/dependencies and a signature/input example. + Use the current registry/version-pinning services; do not promote aliases. +- [ ] SM-26c: prove original -> saved -> clean-environment MLflow predictions for + pandas and Polars. Include representative FE beyond mean imputation/scaling, + such as encoding/binning, and explicitly track each advertised model family. +- [ ] Separate whole-frame local prediction eligibility, row-local HTTP eligibility + and Spark-worker/native eligibility. Context-dependent or row-changing FE does + not become safe for requests or partitions merely because it can be serialized. +- [ ] Keep Python local batch prediction available without a Delta writer. No + implicit Spark collection, new native Spark ports or backend artifact bridge. + +Acceptance: new local-package paths reproduce the original fitted pipeline under +the declared contract, preserve the existing portable bundle, and reject unsupported +serving/Spark combinations explicitly. Local numerical/schema parity and dependency +isolation precede live endpoint claims. SM-17 and SM-18 retain their later scope; +SM-15L follows the local workflow. + +## SM-25 - SDK configuration and preflight + +Reference: `common/config_service.py.tmpl`, model factory and inference service. +Proposed implementation area: `skyulf-core/skyulf/integrations/databricks/`; +config/preflight/workflow modules, integration tests and an English SDK guide. +Names below describe responsibilities; settle public signatures in the task design. + +- [ ] Define immutable configuration for runtime, input source, FE/model execution, + optional stores and output sink without embedding credentials. +- [ ] Reuse bundle metadata to resolve feature order, model digest and output schema; + resolve an alias once to a pinned version. Preserve explicit caller-owned inputs. +- [ ] Provide a preflight result with node/config/model/runtime incompatibilities + and actionable fixes. Distinguish local checks from optional read-only remote checks. +- [ ] Document a short pandas/Polars fit -> local batch workflow that can run + on Databricks job compute, plus an advanced custom-code entry point. Keep + source size limits explicit and do not generate a project to use the SDK. +- [ ] Select among verified local-package and portable-bundle contracts explicitly. + Keep wider native engine/model choices in parked SM-17j; packaging a local + pipeline is not a shortcut to claim broader Spark support. + +Acceptance: valid local fixtures reach the selected local package and predictor; +unsupported FE/model/sink combinations fail before submission; config loading +performs no remote mutation; defaults never invent snapshot/period or promotion +decisions. Spark preflight expands only with later tested Spark options. + +## SM-24a - Reusable training and batch workflows + +Reference: inference/data/config services; reuse Skyulf's fitted local pipeline. +Proposed files: a workflow module in the Databricks integration, a thin executable +example, integration tests and `docs/user_guide/databricks_batch.md` updates. + +- [ ] Compose existing local pandas/Polars SkyulfPipeline fit, SM-26 local + package export and optional tracking/registration as a thin training entry + point. Accept explicit training/split inputs and a bounded local source. +- [ ] Read a named UC table or other declared source through an explicit bounded + local adapter. Filter the requested month at the pinned source version + before collecting locally; enforce row/byte ceilings. A full two-month + table download or an implicit unbounded Spark collect is not acceptable. +- [ ] Expose pure Python batch prediction for verified SM-26 local packages; + preserve required whole-frame context and input order. This task returns + predictions; SM-15L handles publication. +- [ ] Compose pinned registry load, package preflight and local prediction. +- [ ] Return structured diagnostics with source, period, model and code identity; + do not claim the Spark runner's durable publication receipt. +- [ ] Accept explicit period/backfill parameters and business timezone; retries + reuse the same request rather than refreshing the target version silently. +- [ ] Keep table/control provisioning an explicit setup step, separate from scoring. + +Acceptance: pandas/Polars training and local batch prediction preserve the +declared engine and clean-environment model parity, including tracking-off +behavior. Bounded reads fail before exhausting process memory. Registration +never promotes an alias implicitly; no table-write success is claimed here. + +## SM-15L - Local monthly UC Delta publication + +The earlier one-day deferral is superseded by the local-first Bundle request. +Proposed area: a local prediction -> UC output adapter and integration tests. +Prefer an explicit local-result -> Spark DataFrame bridge followed by guarded +Delta period replacement, subject to live validation. Databricks documents +[`spark.createDataFrame` from local data on serverless](https://docs.databricks.com/aws/en/compute/serverless/limitations) +and [atomic selective overwrite](https://docs.databricks.com/aws/en/delta/selective-overwrite). +The [Python SQL Connector](https://docs.databricks.com/aws/en/dev-tools/python-sql-connector) +remains an alternative when a Spark bridge is unavailable; it is not required. + +- [ ] Choose and test a bounded UC source reader. After local pandas/Polars + prediction, convert only the final result to a Spark DataFrame using an + explicit target schema. Retain named columns, dtypes, nulls, row keys, + labels and model-version metadata; avoid silent Polars-to-pandas semantics. +- [ ] Publish exactly one requested period using a safe, verified transaction + design. Test replay, empty period, stale model/source, concurrent writers, + permission denial and failed staging; reject unsupported overwrite policies. + A new month adds its predictions while prior-month rows and run metadata stay + unchanged. Only an explicit backfill may rescore an earlier month. +- [ ] Reuse the existing guarded `publish_replace_period` where its contract + applies. Its current `BatchSpec` includes Spark inference modes, so define + a truthful local publication request or extract shared publication fields; + do not label local prediction as `native_features` or `python_pipeline`. +- [ ] Require explicit `as_of`, source snapshot/version, period, target identity, + logical run identity and maximum local row/byte limits. Table setup and + cleanup are explicit, and credentials use supported providers. State the + selected Spark compute or SQL warehouse requirement in config and preflight. +- [ ] Record a durable publication receipt and compare rows by key after commit. + A filesystem delta-rs test alone does not prove UC managed-table behavior. + +Acceptance: pandas and Polars local predictions reach the monthly UC target +with tested replay/concurrency semantics on the chosen Databricks runtime. +Spark performs only bounded source/result I/O in this first path; it does not +apply FE or run the model. The output equals local gold predictions by row key, +and a second monthly run does not recompute the first month. +The first Bundle cannot advertise a monthly UC output until this gate passes. + +## SM-24b - Optional Databricks Jobs API operations + +Reference: developer resource scope and cleanup patterns. The first Bundle +already defines/deploys/runs jobs; add this optional SDK adapter only if a +non-Bundle caller needs dynamic submit/status/cancel operations. + +- [ ] Build reviewable pandas/Polars training and local batch job requests from + validated config and installed wheel/version, without requiring Spark execution. +- [ ] Separate request construction from submit/status/cancel operations; use existing + platform credential providers and keep tokens out of config/logs. +- [ ] Set bounded timeouts/retries, resource scope, run identity and optional schedule + parameters. Never equate a scheduler retry with permission to overwrite new data. +- [ ] Record deployment/run receipts and owned-resource inventories; document orphan + claim recovery and explicit cleanup without touching unrelated resources. + +Acceptance: request generation is offline; scoped live tests validate submitted +parameters, runtime dependencies and identity. No notifications are sent by +merely configuring them. This task is not a gate for SM-20a. + +## Optional local/platform additions after the first Bundle + +SM-22, SM-19, SM-21 and SM-23 can extend a generated project after SM-20a. +They are not prerequisites for the first local training and monthly batch +Bundle. Endpoint and `ai_query` work do not require Spark; feature-table +adapters must declare any Spark dependency rather than pulling it into the +first local path. The tasks below remain open with their own acceptance gates. + +## SM-22a/b - Validation and promotion + +Reference: `src/validation/services/model_validation.py.tmpl` and registry service. +Proposed area: platform-neutral validation reporting plus optional registry operations; +reuse Skyulf evaluation and explicit MLflow clients rather than duplicate metric code. + +- [ ] SM-22a: evaluate pinned candidate/champion versions on the same documented + dataset/split, with configured thresholds and original label/probability semantics. +- [ ] Produce a comparison report with model/data/code identities and reasons; + evaluation alone must not mutate aliases or endpoints. +- [ ] SM-22b: separate explicit promotion/rollback operations, recording prior and + requested versions. Detect conflicting state instead of overwriting silently. +- [ ] Test first-model behavior without automatic first-champion promotion. + +Acceptance: deterministic report fixture, real registry alias/version tests, +permission failures and rollback identity checks. SM-17i's broader native-model +evaluation remains parked and does not block current compatible bundles. + +## SM-27 - Full-history local rescore and selectable Bundle mode + +Keep `period_update` as the first Bundle's default: score only the requested +closed month and replace that period idempotently. Add an explicit +`full_rebuild` choice after SM-20a; it reads one pinned, bounded source snapshot +and scores the requested historical scope with one pinned model version. Publish +to a new prediction generation or table, validate counts, keys, parity and +provenance, then activate it explicitly. Preserve the previous generation for +rollback and keep original decision-time forecasts auditable. An ordinary +monthly run must never trigger a full rescore because an alias moved. + +- [ ] Define generation identity, source/model/version receipt, active-view + cutover and rollback; reject unbounded reads and overlapping writes. +- [ ] Require point-in-time feature/label semantics for historical forecasts; + a current-state rescore must be labeled as such, not presented as an old + decision-time prediction. +- [ ] Exercise both modes through the generated local-engine Bundle: two monthly + runs leave month one unchanged; an explicit full rebuild creates a complete + second generation; failed validation leaves the first active. + +## SM-28 - Monthly retraining and challenger workflow + +The reference project wires feature engineering, training, validation and +inference jobs, but its sample inference schedule is commented out. Monthly +retraining is therefore an explicit Skyulf follow-up, not inherited behavior. +It is independent of `period_update` and `full_rebuild` scoring choices. + +- [ ] Provide an opt-in monthly schedule with business timezone, label + availability cutoff, pinned training snapshot and reproducible temporal + holdout. Never train on data unavailable at the prediction cutoff. +- [ ] Register a candidate, compare it with a pinned champion on the same + documented evaluation set using SM-22, and record thresholds and slice + failures. Validation must not silently promote or change serving aliases. +- [ ] Require an explicit promotion step with prior-version receipt and rollback; + a failed or unpromoted candidate leaves champion unchanged. A scoring job + resolves its chosen alias once to a concrete version, then pins it for the + whole run. Newly promoted models affect future periods unless SM-27 is + requested separately. +- [ ] Generate and test the optional train/validate/promote/score dependency + chain without conflating scheduler date, training cutoff and scoring period. + +## SM-19a - Live HTTP serving + +Reference: endpoint service and endpoint integration tests. +Proposed area: optional serving adapter, a query example and contract tests. + +- [ ] Create/update an endpoint from an explicit pinned compatible MLflow model; + observe build/readiness with deadlines and retain the last known configuration. +- [ ] Validate request/response schema, labels/probabilities/thresholds and model + dependencies. Serving must not assume an available SparkSession. +- [ ] Test real prediction parity, malformed inputs, query permissions and timeouts. +- [ ] Treat history/window lookups as unsupported until an explicit context design + exists; do not expand the parked node scope through the serving adapter. + +Acceptance: local pyfunc isolation plus an authorized live endpoint probe. The +existing backend HTTP deployment is separate; no SM-18 Canvas bridge is required. + +## SM-19b/d - SQL and serving operations + +- [ ] SM-19b: invoke the existing endpoint through ai_query; named feature struct, + output schema, query permission and row-level error handling with keyed parity. +- [ ] Keep request/model identity traceable; SQL endpoint calls do not inherit the + Delta sink's idempotency automatically. +- [ ] SM-19d: explicit A/B routing, readiness, scaling/cold-start behavior, rollback, + bounded retries, query logs and load tests. No automatic traffic changes. + +Acceptance: HTTP and SQL use the same compatible model contract and gold fixture; +live evidence distinguishes endpoint infrastructure success from prediction parity. +SM-19c continuous streaming remains PARKED and optional. + +## SM-21a/b - Optional feature lookup + +Reference: feature-store service and training-set preparation. + +- [ ] SM-21a: explicit UC feature-table access, primary/timestamp keys, point-in-time + joins, lineage and packaged lookup metadata. Plain-column input stays supported. +- [ ] SM-21b: optional online publication and serving lookup with freshness, + missing-key and permission contracts; no implicit online infrastructure creation. +- [ ] Define how lookup-aware model packaging composes with Skyulf's raw/features + bundle boundary so preprocessing is applied exactly once. + +Acceptance: leakage fixture and offline/online parity; dependency-free behavior +when disabled. Online availability is not a requirement for ordinary Spark batch. + +## SM-23a/b - Monitoring and observability + +Reference: data-quality/monitoring services and endpoint inference logging. + +- [ ] SM-23a: batch run/quality/drift reporting using existing Skyulf metric contracts; + optional Databricks monitor setup and refresh kept separate from prediction. +- [ ] SM-23b: endpoint inference-table integration, delayed labels and version-aware + monitoring; payload retention/redaction and permissions are explicit. +- [ ] Test no-op behavior when disabled, metric/schema agreement and failure handling + so monitoring failures do not masquerade as model training or prediction failures. + +Acceptance: trustworthy data/model/run attribution and scoped platform evidence; +no requirement to move existing core metrics into Databricks-specific code. + +## SM-20a - First local Databricks Bundle and project template + +This is the first deployable milestone after SM-26, SM-25, SM-24a and SM-15L. +Generate a project using tested local services, with a `databricks.yml` in the +generated project root, job resources, thin Python entry points, pinned package +dependencies, dev/prod targets and a short README. Do not add a YAML file to +the Skyulf repository root. The first verified cross-job artifact path uses +MLflow and a pinned UC model version. The user selects pandas or Polars, UC +source/target, schedule and limits; credentials remain in Databricks +authentication or secrets, never generated source. Tracking-off or registry-off +Bundle variants require a separately tested durable artifact handoff. + +- [ ] Generate local training and monthly local batch jobs. Pass data period, + timezone, source snapshot and model version as explicit job parameters. + Serverless Python script/wheel tasks declare their required environment key + and installed package dependencies in the generated job resources. +- [ ] Generate tests for config/imports, `databricks bundle validate`, a + deployment probe, two consecutive local-engine monthly job runs and UC + output parity/replay. +- [ ] Document how to edit custom FE and model code while preserving the + artifact and prediction contract. The generated project calls SDK services; + it does not copy their implementation. +- [ ] Leave endpoint, `ai_query`, online feature lookup, monitoring and Spark + inference jobs absent unless their separate adapters have passed their gates. + +Acceptance: a fresh generated project can be validated, deployed and run on +the chosen Databricks environment; its pandas/Polars model produces the +expected pinned monthly table rows. Generated-file checks alone are not runtime +evidence. A supported no-UC-output variant may be offered separately; it does +not satisfy the monthly table gate. +See [the dedicated SM-20 plan](05-sm20-bundle-plan.md) for the two-month +source/output-table rehearsal and the later Spark inference variant. + +## SM-24c / SM-17 / SM-20b - Spark enhancement after the first Bundle + +Only after SM-20a passes, expose the already implemented compatible Spark +inference and Delta runner through a thin SM-24c workflow. Then resume the +SM-17 inventory and node/model-family gates in independently reviewed slices. +SM-20b adds a Spark execution choice to the generated Bundle only for tested +artifact/runtime combinations. Local training and local batch remain valid +choices; a model saved through SM-26 does not become a Spark artifact by default. +Every Spark variant needs keyed prediction parity, runtime dependency checks, +monthly Delta replay/concurrency evidence and a generated Bundle run probe. diff --git a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md new file mode 100644 index 000000000..c38b951c1 --- /dev/null +++ b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md @@ -0,0 +1,159 @@ +# SM-20: local-first Databricks Bundle, then Spark enhancement + +Updated: 2026-09-22. Planning only; no generated project or Databricks job has +been created by this plan. Current baseline is the scoped SM-16 serverless probe. +The [open queue](OPEN_QUEUE.md) owns status and task order. + +## Outcome and engine boundary + +The first generated project runs fitted feature engineering and model prediction +in pandas or Polars on bounded data inside a Databricks job. Spark may read a +versioned UC source and write the final prediction rows to a UC Delta table; +it does not transform features or score the model in this first variant. +The model is logged through MLflow and loaded from a pinned Unity Catalog +version. The generated project has its own `databricks.yml`; Skyulf's repository +root does not need one. + +```mermaid +flowchart TB + subgraph PROJECT["Local project and deployment"] + direction LR + CONFIG["Skyulf configuration
Databricks runtime, pandas or Polars engine"] --> GENERATE["Generate local-engine Bundle project"] + GENERATE --> FILES["databricks.yml, train and batch jobs,
Python entry points"] + FILES --> DEPLOY["Validate and deploy Bundle"] + end + + subgraph TRAINING["Databricks training job: bounded local engine"] + direction LR + TRAIN_DATA["Pinned training data"] --> TRAIN["Train job"] + TRAIN --> FIT["pandas or Polars: fit FE
and train Python model"] + FIT --> MLFLOW["MLflow run and fitted pipeline artifact"] + MLFLOW --> MODEL["UC registered model: concrete version"] + end + + subgraph INFERENCE["Databricks batch job: bounded local engine"] + direction LR + SCORE_DATA["UC scoring data at pinned snapshot"] --> BATCH["Batch inference job"] + BATCH --> PREDICT["pandas or Polars: apply FE
and predict"] + PREDICT --> ROWS["Prediction rows with source
and model provenance"] + ROWS --> BRIDGE["Spark bridge: UC table I/O
with explicit output schema"] + BRIDGE --> OUTPUT["UC Delta prediction table"] + end + + DEPLOY --> TRAIN + DEPLOY --> BATCH + MODEL --> BATCH +``` + +[Download the rendered SVG](diagrams/local-engine-bundle.svg). The diagram +shows the first local-engine Bundle end to end; the scoring job is independent +of a particular schedule or period-publication policy. + +This separates the prediction engine from table I/O. Databricks documents +[`spark.createDataFrame` from local data on serverless](https://docs.databricks.com/aws/en/compute/serverless/limitations) +and [atomic selective Delta overwrite](https://docs.databricks.com/aws/en/delta/selective-overwrite). +That makes a Spark write bridge feasible, but its schema, conversion and +publication guarantees still need a live Skyulf test. The SQL Connector is an +alternative, not a required part of the first Bundle. + +## SM-20a prerequisites and generated project + +1. SM-26 proves local fitted pipeline save/load/MLflow prediction parity. +2. SM-25 selects pandas or Polars, a pinned model version, bounded source, + output table and publication mode before the job starts. +3. SM-24a exposes a local training and batch prediction entry point. +4. SM-15L proves local prediction -> UC Delta publication, including replay, + stale requests and concurrent writers. The current `run_batch` performs + Spark inference and cannot be called as if it performed local prediction. + Its `publish_replace_period` logic can be reused only with a truthful local + request contract and explicit final-result conversion. + +The custom template should generate a project with these responsibilities: + +```text +templates/databricks/databricks_template_schema.json +templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +templates/databricks/template/{{.project_name}}/resources/train_job.yml.tmpl +templates/databricks/template/{{.project_name}}/resources/batch_job.yml.tmpl +templates/databricks/template/{{.project_name}}/src/train.py.tmpl +templates/databricks/template/{{.project_name}}/src/score_month.py.tmpl +templates/databricks/template/{{.project_name}}/README.md.tmpl +``` + +The generated Python files call Skyulf services; they do not copy FE, model, +MLflow or Delta publication implementations. The first verified cross-job +artifact path uses MLflow and a concrete UC model version. Tracking-off and +registry-off variants need their own durable artifact-handoff test before they +are offered. Configuration includes source/target table names, row keys, +period column, business timezone, maximum local rows/bytes, model version, +compute environment and optional schedule. Credentials are resolved by the +platform, not generated into files. Serverless Python job tasks declare the +required environment and package dependencies. + +## Two-month UC table rehearsal + +Use an isolated test catalog.schema. Provision the input and prediction tables +explicitly; keep training data separate from the scoring rows. Train one fixed +model and pin its UC version for both scoring runs so this test isolates +publication behavior. Let `M1` and `M2` be consecutive business months, and +`S1`/`S2` the source Delta versions after each month's data arrives. Each +scoring job runs after the corresponding month closes. + +| Step | Action | Required observation | +| --- | --- | --- | +| Setup | Put two keyed `M1` rows in the source table; create an empty prediction table | Source version `S1`; output schema and initial target version recorded | +| First monthly run | After `M1` closes, filter and score only `M1` at `S1` with pinned model version and run ID `R1` | Exactly two persisted `M1` predictions; values equal direct pandas/Polars gold results; receipt names `S1`, model and target version | +| Next month's data | Append two keyed `M2` rows to the same source table | New source version `S2`; original `M1` source rows remain | +| Second monthly run | After `M2` closes, filter and score only `M2` at `S2` with run ID `R2` and expected target version from `R1` | Two new `M2` predictions; target now has four rows across two months; both `M1` prediction values and run metadata remain unchanged | +| Replay | Repeat the exact `R2` request | Return the recorded receipt without another target commit or changed rows | +| Stale conflict | Submit a new logical request with the old expected target version | Reject it without changing the prediction table | + +The output is a persisted UC Delta table, but the second job computes only +`M2`; it does not materialize or re-score both months. The period-scoped Delta +write behaves like an append for a new month and replaces only that month on +an explicit rerun. A late-arriving row in `M1` requires a separate `M1` +backfill request; it must not be picked up silently by the `M2` job. Require +unique row keys within each month, stable column order, explicit null/dtype +conversion and a bounded month-filtered local read. Capture source versions +and `as_of` after their commits rather than guessing availability. No +production table is used. + +## Selectable scoring and retraining extensions + +The first Bundle implements `period_update` only. SM-27 later adds an explicit +`full_rebuild` mode to the generated local-engine project. The selection is a +job parameter with preflight, not an automatic reaction to new data or a moved +model alias. + +| Mode | Input and publication | Typical use | +| --- | --- | --- | +| `period_update` (default) | Score one requested month from a pinned source version; idempotently replace that month's output; retain all other periods and their model versions | Monthly forecasts and auditable past decisions | +| `full_rebuild` (explicit) | Score a pinned, bounded historical scope with one model version; publish a new validated prediction generation and explicitly activate it | Recompute a current-state view, corrected data, or a model migration | + +The full rebuild must keep its source snapshot, model version, `as_of`, row +scope, generation ID and activation receipt. Its failure must leave the old +generation active. Historical decision-time predictions remain available; +rescores using later information must be labeled as current-state results. +The rehearsal adds a third run only after SM-27: score `M1` and `M2` at `S2` +into a new generation, compare four rows, activate it, and verify rollback. + +SM-28 separately adds optional monthly retraining after labels are available. +It trains a candidate, uses SM-22 to compare against a pinned champion, and +requires explicit promotion. The scoring job pins the chosen concrete model +version once per run. A new champion does not retroactively alter previous +months; `full_rebuild` remains a separate request. + +## Acceptance and later expansion + +Offline checks cover template generation, imports, config preflight and +`databricks bundle validate`. A separate live check deploys the generated dev +target, runs training and both monthly scoring steps, then compares rows by +key and month, model/version metadata and Delta history. The Bundle is complete only when +the generated project itself passes those checks; an SDK-only smoke is not +sufficient. The first generated project does not need endpoints, `ai_query`, +online feature lookup, monitoring or dynamic Jobs API helpers. + +SM-20b follows the accepted local Bundle. It adds a Spark inference choice +only for artifact, FE, model and runtime combinations verified by SM-24c and +the relevant SM-17 slices. The same two-month rehearsal then runs against +that Spark variant. The pandas/Polars choice remains available. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 1ee12e7f9..79808fdb1 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,12 +1,37 @@ # Session handoff - 2026-09-22 SM-00 through SM-16 are complete for their documented scopes. The selected -Databricks serverless regression workflow passed. SM-15L is READY and next. +Databricks serverless regression workflow passed. Latest user direction: +**Build a small-data pandas/Polars training and local batch path, then its first +working Databricks Bundle. Spark may handle table I/O in that first path; +Spark FE/model execution and its Bundle option follow. +SM-15L is reopened for monthly UC output; SM-18 remains parked. Start with +SM-26 local MLflow packaging, then SM-25. After the first Bundle, SM-27 adds +explicit full-history rescore and SM-22/SM-28 add optional monthly retraining +with controlled candidate/champion promotion.** Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-16 are complete; local pandas/Polars Delta writing is next. +- SM-00 through SM-16 are complete. Start SM-26 from + [04-databricks-integration-plan.md](04-databricks-integration-plan.md). + The first Bundle and its two-month table rehearsal are specified in + [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). + This planning update changed priorities only; no implementation or new cloud + execution. The previous Spark-first direction is superseded. Preserve the later + [NODE_SUPPORT.md](NODE_SUPPORT.md) inventory and + [gap review](reports/2026-09-22-spark-databricks-gap-review.md). + The review enumerated all 100 source registration IDs and added model training, + broader model inference, configuration usability and parked platform follow-ups. + It did not implement those features. Missing node/model coverage must remain + open unless implemented or explicitly deferred by the user. Broad SM-17 + follows the first local Bundle. The current Spark integration uses compatible bundles; + pandas/Polars -> Spark is not support for arbitrary local FE or model artifacts. +- SM-26 explicitly separates broader local pipeline packaging from native Spark + porting. Preserve the fitted local FE/model behavior and test clean-environment + MLflow parity; classify local, row-local serving and distributed eligibility + separately. SM-25, SM-24a, SM-15L and SM-20a follow this artifact + contract. No new support is implemented by this planning update. - The registry-bundle loader and first registry-to-Spark probe are implemented. Local validation passed 29 combined tests; the selected live platform gate is now complete. Tested 0.9.0 wheel hashes are recorded in the platform file. @@ -35,9 +60,13 @@ Target release: 0.9.0. Branch: `090`. remains documented, not relabeled. The aggregate report was generated from actual results and checked against the r3 wheel; all 225 current package files match that wheel. See the platform evidence file for retained resources. -- Local-engine pandas/Polars Delta writing is tracked as SM-15L. The current - Spark writer does not implement it; templates remain SM-20. Start with explicit - local source/target and memory/provenance contracts. A delta-rs filesystem test +- Local-engine pandas/Polars UC Delta writing is tracked as SM-15L after SM-24a. + The current Spark `run_batch` performs inference itself and cannot be used + for local predictions unchanged. Prefer a bounded local-result -> Spark + DataFrame bridge into guarded Delta publication; SQL Connector is optional. + The later local-first Bundle request supersedes the earlier one-day deferral. + Start with explicit local source/target, memory/provenance and transaction + contracts. A delta-rs filesystem test must not be presented as UC managed-table writer support; see the current platform document's external-client constraints. - SM-15 baseline: `4a613cb5`. Its implementation and verification are in the @@ -56,18 +85,20 @@ The runtime environment and the execution engine are independent choices. Local pandas/Polars FE and sklearn training may run inside Databricks; a later Spark inference job may also run inside Databricks. -The user's intended workflow is: +The first deliverable is: ```text Databricks training job: pandas/Polars FE + sklearn model - -> Save fitted FE, model and input contract - -> Databricks scoring job: Spark FE + Python model on workers - -> Write predictions to a Delta table, for example monthly + -> Save fitted FE, model and input contract through MLflow + -> Databricks scoring job: pandas/Polars local batch on bounded data + -> Spark handles final UC Delta table publication only (SM-15L) + -> Generate and run the first local-engine Bundle (SM-20a) ``` -SM-16 validated this regression workflow on the selected serverless environment. -It does not certify arbitrary FE nodes, classification or every runtime. -Scheduling configuration, endpoints and reusable templates remain later scope. +SM-16 validated an earlier compatible Polars-trained -> Spark regression path +on selected serverless compute. It does not validate the new local UC sink or +generated Bundle. Spark becomes a later optional Bundle choice in SM-20b. +Endpoint and online-lookup resources are separate optional work. Keep new documentation and diagram labels in English. ## Current execution boundaries @@ -159,7 +190,7 @@ without writing again. New computation needs a new run ID and reviewed target version. History and transaction retention must cover the allowed retry window. SM-16 is complete; see its evidence file for wheel checksums, approved namespace, -retained resources and finished runs. Start SM-15L without repeating these cloud +retained resources and finished runs. Start SM-26 without repeating these cloud tests unless a new change requires them. Databricks CLI 1.17.0 is installed but absent from the current shell PATH; use its existing WinGet executable or a refreshed shell. The user confirmed `databricks.yml` is diff --git a/initiatives/spark_and_mlflow/NODE_SUPPORT.md b/initiatives/spark_and_mlflow/NODE_SUPPORT.md new file mode 100644 index 000000000..665030d74 --- /dev/null +++ b/initiatives/spark_and_mlflow/NODE_SUPPORT.md @@ -0,0 +1,149 @@ +# Node and model coverage inventory + +Source snapshot: `63dd3e21`, inspected 2026-09-22. **SM-17 follows the first local Bundle:** +this complete source-ID list is its starting inventory, not completed per-option +runtime validation. Changes after this snapshot must update the inventory. +Current work is the [Databricks integration lane](04-databricks-integration-plan.md) +using fitted local packages; the later Spark coverage is not a prerequisite. + +An AST scan of literal `NodeRegistry.register` calls found **100 IDs**: **62 +preprocessing** and **38 modeling**. Aliases and optional-library registrations +are retained deliberately. This is not a count of distinct algorithms or of +nodes available with only base dependencies. + +## Coverage rules + +- Every row needs configuration-level fit, apply, state export/import, inference, + row/schema effects and runtime evidence. A family-level check cannot certify + every option in that family. +- OPEN is planned missing coverage, not accepted permanent exclusion. SM-17 does + not close while requested coverage remains open without an explicit user deferral. +- Only the imputer/scaler declarations listed below currently advertise native + Spark FE. Their already-tested configurations remain supported during expansion. +- Model rows require separate local Python worker compatibility and native Spark + training decisions. Generic sklearn regression/classification support exists, + but this inventory does not certify every model ID or configured variant. +- XGBoost/LightGBM, clustering, custom prediction semantics and classifiers without + probabilities require explicit bundle/output adapters. Composite sklearn paths + require per-configuration auditing; add adapters only where their semantics need one. +- Native model backend changes are explicit choices; no silent replacement of + an existing sklearn estimator by a different Spark estimator. +- Existing local pandas/Polars behavior must retain its regression coverage. + +Detailed work and acceptance: [gap review](reports/2026-09-22-spark-databricks-gap-review.md). + +## Source registrations + +| Registration ID | Source | Owning task | Current Spark/portable coverage | +| --- | --- | --- | --- | +| `adaboost_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L571) | SM-17g/h/i | OPEN: per-model contract audit | +| `calibrated_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L260) | SM-17g/h/i | OPEN: per-model contract audit | +| `decision_tree_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L500) | SM-17g/h/i | OPEN: per-model contract audit | +| `extra_trees_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L664) | SM-17g/h/i | OPEN: per-model contract audit | +| `gaussian_nb` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L857) | SM-17g/h/i | OPEN: per-model contract audit | +| `gradient_boosting_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L536) | SM-17g/h/i | OPEN: per-model contract audit | +| `hist_gradient_boosting_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L705) | SM-17g/h/i | OPEN: per-model contract audit | +| `k_neighbors_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L463) | SM-17g/h/i | OPEN: per-model contract audit | +| `lgbm_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L775) | SM-17g/h/i | OPEN: per-model contract audit | +| `logistic_regression` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L67) | SM-17g/h/i | OPEN: per-model contract audit | +| `random_forest_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L385) | SM-17g/h/i | OPEN: per-model contract audit | +| `sgd_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L890) | SM-17g/h/i | OPEN: per-model contract audit | +| `svc` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L424) | SM-17g/h/i | OPEN: per-model contract audit | +| `xgboost_classifier` | [modeling/classification.py](../../skyulf-core/skyulf/modeling/classification.py#L607) | SM-17g/h/i | OPEN: per-model contract audit | +| `birch` | [modeling/clustering.py](../../skyulf-core/skyulf/modeling/clustering.py#L274) | SM-17g/h/i | OPEN: per-model contract audit | +| `gaussian_mixture` | [modeling/clustering.py](../../skyulf-core/skyulf/modeling/clustering.py#L241) | SM-17g/h/i | OPEN: per-model contract audit | +| `kmeans` | [modeling/clustering.py](../../skyulf-core/skyulf/modeling/clustering.py#L171) | SM-17g/h/i | OPEN: per-model contract audit | +| `minibatch_kmeans` | [modeling/clustering.py](../../skyulf-core/skyulf/modeling/clustering.py#L201) | SM-17g/h/i | OPEN: per-model contract audit | +| `stacking_classifier` | [modeling/ensemble.py](../../skyulf-core/skyulf/modeling/ensemble.py#L570) | SM-17g/h/i | OPEN: per-model contract audit | +| `stacking_regressor` | [modeling/ensemble.py](../../skyulf-core/skyulf/modeling/ensemble.py#L646) | SM-17g/h/i | OPEN: per-model contract audit | +| `voting_classifier` | [modeling/ensemble.py](../../skyulf-core/skyulf/modeling/ensemble.py#L532) | SM-17g/h/i | OPEN: per-model contract audit | +| `voting_regressor` | [modeling/ensemble.py](../../skyulf-core/skyulf/modeling/ensemble.py#L610) | SM-17g/h/i | OPEN: per-model contract audit | +| `bernoulli_nb` | [modeling/naive_bayes.py](../../skyulf-core/skyulf/modeling/naive_bayes.py#L71) | SM-17g/h/i | OPEN: per-model contract audit | +| `multinomial_nb` | [modeling/naive_bayes.py](../../skyulf-core/skyulf/modeling/naive_bayes.py#L33) | SM-17g/h/i | OPEN: per-model contract audit | +| `adaboost_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L384) | SM-17g/h/i | OPEN: per-model contract audit | +| `decision_tree_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L311) | SM-17g/h/i | OPEN: per-model contract audit | +| `elasticnet_regression` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L203) | SM-17g/h/i | OPEN: per-model contract audit | +| `extra_trees_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L420) | SM-17g/h/i | OPEN: per-model contract audit | +| `gradient_boosting_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L349) | SM-17g/h/i | OPEN: per-model contract audit | +| `hist_gradient_boosting_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L462) | SM-17g/h/i | OPEN: per-model contract audit | +| `k_neighbors_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L274) | SM-17g/h/i | OPEN: per-model contract audit | +| `lasso_regression` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L170) | SM-17g/h/i | OPEN: per-model contract audit | +| `lgbm_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L526) | SM-17g/h/i | OPEN: per-model contract audit | +| `linear_regression` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L58) | SM-17g/h/i | OPEN: per-model contract audit | +| `random_forest_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L131) | SM-17g/h/i | OPEN: per-model contract audit | +| `ridge_regression` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L95) | SM-17g/h/i | OPEN: per-model contract audit | +| `svr` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L241) | SM-17g/h/i | OPEN: per-model contract audit | +| `xgboost_regressor` | [modeling/regression.py](../../skyulf-core/skyulf/modeling/regression.py#L609) | SM-17g/h/i | OPEN: per-model contract audit | +| `CustomBinning` | [preprocessing/bucketing.py](../../skyulf-core/skyulf/preprocessing/bucketing.py#L608) | SM-17b | OPEN: Spark implementation | +| `GeneralBinning` | [preprocessing/bucketing.py](../../skyulf-core/skyulf/preprocessing/bucketing.py#L544) | SM-17b | OPEN: Spark implementation | +| `KBinsDiscretizer` | [preprocessing/bucketing.py](../../skyulf-core/skyulf/preprocessing/bucketing.py#L666) | SM-17b | OPEN: Spark implementation | +| `Casting` | [preprocessing/casting.py](../../skyulf-core/skyulf/preprocessing/casting.py#L449) | SM-17a | OPEN: Spark implementation | +| `AliasReplacement` | [preprocessing/cleaning/alias.py](../../skyulf-core/skyulf/preprocessing/cleaning/alias.py#L174) | SM-17a | OPEN: Spark implementation | +| `InvalidValueReplacement` | [preprocessing/cleaning/invalid_value.py](../../skyulf-core/skyulf/preprocessing/cleaning/invalid_value.py#L251) | SM-17a | OPEN: Spark implementation | +| `TextCleaning` | [preprocessing/cleaning/text.py](../../skyulf-core/skyulf/preprocessing/cleaning/text.py#L213) | SM-17a | OPEN: Spark implementation | +| `ValueReplacement` | [preprocessing/cleaning/value_replacement.py](../../skyulf-core/skyulf/preprocessing/cleaning/value_replacement.py#L216) | SM-17a | OPEN: Spark implementation | +| `Deduplicate` | [preprocessing/drop_and_missing/deduplicate.py](../../skyulf-core/skyulf/preprocessing/drop_and_missing/deduplicate.py#L90) | SM-17a | OPEN: Spark implementation | +| `DropMissingColumns` | [preprocessing/drop_and_missing/drop_columns.py](../../skyulf-core/skyulf/preprocessing/drop_and_missing/drop_columns.py#L107) | SM-17a | OPEN: Spark implementation | +| `DropMissingRows` | [preprocessing/drop_and_missing/drop_rows.py](../../skyulf-core/skyulf/preprocessing/drop_and_missing/drop_rows.py#L137) | SM-17a | OPEN: Spark implementation | +| `MissingIndicator` | [preprocessing/drop_and_missing/missing_indicator.py](../../skyulf-core/skyulf/preprocessing/drop_and_missing/missing_indicator.py#L127) | SM-17a | OPEN: Spark implementation | +| `DummyEncoder` | [preprocessing/encoding/dummy.py](../../skyulf-core/skyulf/preprocessing/encoding/dummy.py#L263) | SM-17b | OPEN: Spark implementation | +| `HashEncoder` | [preprocessing/encoding/hash.py](../../skyulf-core/skyulf/preprocessing/encoding/hash.py#L138) | SM-17b | OPEN: Spark implementation | +| `LabelEncoder` | [preprocessing/encoding/label.py](../../skyulf-core/skyulf/preprocessing/encoding/label.py#L310) | SM-17b | OPEN: Spark implementation | +| `OneHotEncoder` | [preprocessing/encoding/one_hot.py](../../skyulf-core/skyulf/preprocessing/encoding/one_hot.py#L230) | SM-17b | OPEN: Spark implementation | +| `OrdinalEncoder` | [preprocessing/encoding/ordinal.py](../../skyulf-core/skyulf/preprocessing/encoding/ordinal.py#L338) | SM-17b | OPEN: Spark implementation | +| `TargetEncoder` | [preprocessing/encoding/target.py](../../skyulf-core/skyulf/preprocessing/encoding/target.py#L326) | SM-17d | OPEN: Spark implementation | +| `WOEEncoder` | [preprocessing/encoding/woe.py](../../skyulf-core/skyulf/preprocessing/encoding/woe.py#L315) | SM-17d | OPEN: Spark implementation | +| `FeatureGeneration` | [preprocessing/feature_generation/generation.py](../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py#L105) | SM-17a | OPEN: Spark implementation | +| `FeatureGenerationNode` | [preprocessing/feature_generation/generation.py](../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py#L107) | SM-17a | OPEN: Spark implementation | +| `FeatureMath` | [preprocessing/feature_generation/generation.py](../../skyulf-core/skyulf/preprocessing/feature_generation/generation.py#L106) | SM-17a | OPEN: Spark implementation | +| `FeatureInteraction` | [preprocessing/feature_generation/interaction.py](../../skyulf-core/skyulf/preprocessing/feature_generation/interaction.py#L162) | SM-17a | OPEN: Spark implementation | +| `PolynomialFeatures` | [preprocessing/feature_generation/polynomial.py](../../skyulf-core/skyulf/preprocessing/feature_generation/polynomial.py#L100) | SM-17a | OPEN: Spark implementation | +| `PolynomialFeaturesNode` | [preprocessing/feature_generation/polynomial.py](../../skyulf-core/skyulf/preprocessing/feature_generation/polynomial.py#L101) | SM-17a | OPEN: Spark implementation | +| `CorrelationThreshold` | [preprocessing/feature_selection/correlation.py](../../skyulf-core/skyulf/preprocessing/feature_selection/correlation.py#L162) | SM-17c | OPEN: Spark implementation | +| `feature_selection` | [preprocessing/feature_selection/facade.py](../../skyulf-core/skyulf/preprocessing/feature_selection/facade.py#L67) | SM-17c | OPEN: Spark implementation | +| `ModelBasedSelection` | [preprocessing/feature_selection/model_based.py](../../skyulf-core/skyulf/preprocessing/feature_selection/model_based.py#L45) | SM-17c | OPEN: Spark implementation | +| `UnivariateSelection` | [preprocessing/feature_selection/univariate.py](../../skyulf-core/skyulf/preprocessing/feature_selection/univariate.py#L46) | SM-17c | OPEN: Spark implementation | +| `VarianceThreshold` | [preprocessing/feature_selection/variance.py](../../skyulf-core/skyulf/preprocessing/feature_selection/variance.py#L33) | SM-17c | OPEN: Spark implementation | +| `GeoDistance` | [preprocessing/geo/distance.py](../../skyulf-core/skyulf/preprocessing/geo/distance.py#L156) | SM-17e | OPEN: Spark implementation | +| `H3Index` | [preprocessing/geo/h3_index.py](../../skyulf-core/skyulf/preprocessing/geo/h3_index.py#L123) | SM-17e | OPEN: Spark implementation | +| `IterativeImputer` | [preprocessing/imputation/iterative.py](../../skyulf-core/skyulf/preprocessing/imputation/iterative.py#L52) | SM-17b | OPEN: Spark implementation | +| `KNNImputer` | [preprocessing/imputation/knn.py](../../skyulf-core/skyulf/preprocessing/imputation/knn.py#L49) | SM-17b | OPEN: Spark implementation | +| `SimpleImputer` | [preprocessing/imputation/simple.py](../../skyulf-core/skyulf/preprocessing/imputation/simple.py#L117) | SM-17b | PARTIAL: native fit/apply mean/constant; other strategies OPEN | +| `DataSnapshot` | [preprocessing/inspection.py](../../skyulf-core/skyulf/preprocessing/inspection.py#L156) | SM-17f | OPEN: Spark implementation | +| `DatasetProfile` | [preprocessing/inspection.py](../../skyulf-core/skyulf/preprocessing/inspection.py#L88) | SM-17f | OPEN: Spark implementation | +| `EllipticEnvelope` | [preprocessing/outliers/elliptic.py](../../skyulf-core/skyulf/preprocessing/outliers/elliptic.py#L124) | SM-17c | OPEN: Spark implementation | +| `IQR` | [preprocessing/outliers/iqr.py](../../skyulf-core/skyulf/preprocessing/outliers/iqr.py#L70) | SM-17c | OPEN: Spark implementation | +| `ManualBounds` | [preprocessing/outliers/manual_bounds.py](../../skyulf-core/skyulf/preprocessing/outliers/manual_bounds.py#L88) | SM-17c | OPEN: Spark implementation | +| `Winsorize` | [preprocessing/outliers/winsorize.py](../../skyulf-core/skyulf/preprocessing/outliers/winsorize.py#L76) | SM-17c | OPEN: Spark implementation | +| `ZScore` | [preprocessing/outliers/zscore.py](../../skyulf-core/skyulf/preprocessing/outliers/zscore.py#L74) | SM-17c | OPEN: Spark implementation | +| `Oversampling` | [preprocessing/resampling.py](../../skyulf-core/skyulf/preprocessing/resampling.py#L270) | SM-17f | OPEN: Spark implementation | +| `Undersampling` | [preprocessing/resampling.py](../../skyulf-core/skyulf/preprocessing/resampling.py#L413) | SM-17f | OPEN: Spark implementation | +| `MaxAbsScaler` | [preprocessing/scaling/maxabs.py](../../skyulf-core/skyulf/preprocessing/scaling/maxabs.py#L67) | SM-17a | OPEN: Spark implementation | +| `MinMaxScaler` | [preprocessing/scaling/minmax.py](../../skyulf-core/skyulf/preprocessing/scaling/minmax.py#L67) | SM-17a | OPEN: Spark implementation | +| `RobustScaler` | [preprocessing/scaling/robust.py](../../skyulf-core/skyulf/preprocessing/scaling/robust.py#L86) | SM-17b | OPEN: Spark implementation | +| `StandardScaler` | [preprocessing/scaling/standard.py](../../skyulf-core/skyulf/preprocessing/scaling/standard.py#L124) | SM-17a | IMPLEMENTED: native fit/apply mean/std flags; retain regression gates | +| `Split` | [preprocessing/split.py](../../skyulf-core/skyulf/preprocessing/split.py#L165) | SM-17f | OPEN: Spark implementation | +| `TrainTestSplitter` | [preprocessing/split.py](../../skyulf-core/skyulf/preprocessing/split.py#L166) | SM-17f | OPEN: Spark implementation | +| `feature_target_split` | [preprocessing/split.py](../../skyulf-core/skyulf/preprocessing/split.py#L553) | SM-17f | OPEN: Spark implementation | +| `DateFeatures` | [preprocessing/time_series/date_features.py](../../skyulf-core/skyulf/preprocessing/time_series/date_features.py#L149) | SM-17a | OPEN: Spark implementation | +| `LagFeatures` | [preprocessing/time_series/lag.py](../../skyulf-core/skyulf/preprocessing/time_series/lag.py#L108) | SM-17d | OPEN: Spark implementation | +| `RollingAggregate` | [preprocessing/time_series/rolling.py](../../skyulf-core/skyulf/preprocessing/time_series/rolling.py#L146) | SM-17d | OPEN: Spark implementation | +| `GeneralTransformation` | [preprocessing/transformations/general.py](../../skyulf-core/skyulf/preprocessing/transformations/general.py#L189) | SM-17c | OPEN: Spark implementation | +| `PowerTransformer` | [preprocessing/transformations/power.py](../../skyulf-core/skyulf/preprocessing/transformations/power.py#L151) | SM-17c | OPEN: Spark implementation | +| `SimpleTransformation` | [preprocessing/transformations/simple.py](../../skyulf-core/skyulf/preprocessing/transformations/simple.py#L64) | SM-17c | OPEN: Spark implementation | +| `count_vectorizer` | [preprocessing/vectorization/count_vectorizer.py](../../skyulf-core/skyulf/preprocessing/vectorization/count_vectorizer.py#L125) | SM-17e | OPEN: Spark implementation | +| `hashing_vectorizer` | [preprocessing/vectorization/hashing_vectorizer.py](../../skyulf-core/skyulf/preprocessing/vectorization/hashing_vectorizer.py#L107) | SM-17e | OPEN: Spark implementation | +| `sentence_embedder` | [preprocessing/vectorization/sentence_embedder.py](../../skyulf-core/skyulf/preprocessing/vectorization/sentence_embedder.py#L206) | SM-17e | OPEN: Spark implementation | +| `tfidf_vectorizer` | [preprocessing/vectorization/tfidf_vectorizer.py](../../skyulf-core/skyulf/preprocessing/vectorization/tfidf_vectorizer.py#L119) | SM-17e | OPEN: Spark implementation | +| `tokenizer` | [preprocessing/vectorization/tokenizer.py](../../skyulf-core/skyulf/preprocessing/vectorization/tokenizer.py#L153) | SM-17e | OPEN: Spark implementation | + +## SM-17-00 remaining acceptance + +- [ ] Expand each registration to its actual configuration options and aliases. +- [ ] Record independent native-fit, native-apply and worker-Python capabilities. +- [ ] Record codec/state, column order, label/probability and row effects. +- [ ] Reconcile optional runtime registrations and fa?ade/dynamic model choices. +- [ ] Add a registry/inventory guard against new untracked nodes. +- [ ] Link each supported combination to tests and selected-runtime evidence. + +The inventory is documentation only. It grants no capabilities and starts no jobs. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 0326959f9..9ed8643c5 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,13 +1,20 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-22. **SM-00–SM-16 complete; SM-15L READY. Target: 0.9.0.** -Bu dosya kısa çalışma sırasıdır; detaylar bağlantılı planlarda. +Updated: 2026-09-22. **SM-00–SM-16 complete; SM-26 next. Target: 0.9.0.** +First deliverable: pandas/Polars training and local batch on Databricks, then a +working local-engine Bundle. Spark expansion follows that Bundle. SM-15L is +reopened for monthly UC output; SM-18 and continuous streaming remain parked. -Read [HANDOFF.md](HANDOFF.md) before starting SM-15L. +Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) +and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-26. +Historical completion evidence is preserved in +[OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). +This planning update has not generated a project or started a job. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. +DEFERRED = user postponed this work; PARKED = do not implement until resumed. | Sıra | Görev | Bağımlılık | Durum | Kısa bitiş ölçütü | | --- | --- | --- | --- | --- | @@ -28,31 +35,110 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | | SM-16 | Gerçek Databricks kapısı | SM-15 | DONE | Selected serverless workflow passed; live evidence below | -| SM-15L | Local pandas/Polars Delta sink | SM-16 | READY | Next: same period/retry guarantees; local writer and UC access tests | -| SM-17 | Kalan node aileleri | SM-16 | WAIT | Aile bazlı port; her kayıt supported/unsupported | -| SM-18 | Backend/Canvas ve custom FE | SM-17 | LATER | Capability UI/API; DAG/artifact uyumu | Parked -| SM-19 | HTTP/SQL erişimi; optional streaming | SM-18 | LATER | Desteklenen erişimlerde batch ile aynı tahmin | Parked -| SM-20 | Template / Databricks Bundle | SM-19 | LATER | Seçilebilir working runner; validate ve smoke | Parked +| SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | WAIT | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | +| SM-17 | Complete existing Spark node/model coverage | SM-20a | LATER | Resume only after the first local Bundle; preserve all inventoried gaps | +| SM-18 | Backend/Canvas and legacy artifact bridge | SM-17 | PARKED | Capability UI/API, DAG contracts and existing deployment compatibility | +| SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | READY | Preserve fitted FE/model/engine semantics beyond the portable Spark subset; clean-environment prediction parity; Spark eligibility separate | +| SM-25 | Local-first config / SDK preflight | SM-26 | WAIT | Choose pandas/Polars, runtime, store and sink; reject incompatible local packages before jobs | +| SM-24a | Local training and bounded batch prediction | SM-25 | WAIT | Reuse fitted pandas/Polars pipeline and pinned MLflow model; no Spark FE/model dependency | +| SM-20a | First local-engine Bundle/template | SM-24a, verified SM-15L | WAIT | Generate, validate, deploy and run pandas/Polars train/monthly batch with pinned MLflow/UC model | +| SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | +| SM-22 | Optional model validation and controlled promotion | SM-20a, current evaluation/registry | LATER | Pinned candidate/champion comparison, explicit version promotion and rollback | +| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | LATER | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | +| SM-28 | Monthly retraining and challenger workflow | SM-20a, SM-22 | LATER | Label-aware schedule, leakage-safe training, candidate/champion report, explicit promotion, and independent pinned scoring job | +| SM-19 | Optional live HTTP / SQL ai_query / endpoint operations | SM-20a, compatible pyfunc package | LATER | Add only after serving parity; streaming remains parked | +| SM-21 | Optional Databricks feature tables / online lookup | SM-20a; SM-19a for online serving | LATER | Point-in-time lookups and optional online freshness; declare any Spark dependency | +| SM-23 | Optional monitoring and inference observability | SM-20a, relevant batch/serving adapter | LATER | Existing Skyulf metrics + optional Databricks monitoring/inference tables | +| SM-24c | Spark batch workflow adapter | SM-20a, existing Spark sink | LATER | Expose tested Spark runner after first local Bundle | +| SM-20b | Spark Bundle enhancement | SM-24c, selected SM-17 slices | LATER | Add tested Spark engine choice while preserving local variant | + +IDs remain stable; suffixes distinguish the first local Bundle from its later +Spark extension. SM-27 and SM-28 add the selectable full-rescore and scheduled +retraining workflows after the first Bundle; neither blocks SM-20a. Endpoint, +feature lookup and monitoring work also remain optional. Prefer completing the +local Bundle extensions before broad Spark expansion. + +## Local-first path to the first Bundle + +These tasks were identified in the reference review; the latest user direction +moves the first local Bundle before Spark and other optional integrations. +Full task scope, proposed code areas, reference sources and acceptance checks are +in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). + +1. **SM-26:** fitted pandas/Polars pipeline -> MLflow package -> same local predictions. +2. **SM-25:** config, pinned local artifact loading, limits and preflight. +3. **SM-24a:** local training and bounded local batch prediction in Databricks. +4. **SM-15L:** convert only final local predictions for guarded Spark Delta publication; each new month adds results while earlier months remain unchanged. +5. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle using the [two-month rehearsal](05-sm20-bundle-plan.md). +6. **After SM-20a:** SM-27 adds explicit `full_rebuild` alongside the default + `period_update`; SM-22 then SM-28 add candidate/champion validation and + optional monthly retraining. These are separate from monthly scoring. +7. **Later:** optional SM-24b/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. + +SM-26 is the explicit packaging task added after the local-first MLflow discussion. +It reuses the fitted local pipeline rather than requiring every FE node to gain a +portable Spark codec first. Each advertised local pipeline/model variant needs +save/load/prediction evidence. This does not make its artifact Spark-compatible. +Backend joblib dictionary bridging stays in parked SM-18. Local prediction +and UC Delta publication remain separate tasks; SM-15L is now on the first +Bundle's critical path, with an explicit small-data memory limit. Spark can +perform UC table I/O here without becoming the FE or model execution engine. + +Pandas/Polars training -> Spark inference is available only for the currently +compatible FE/model bundle contract. Both Spark modes remain capability-gated. +Delaying SM-17 does not enable arbitrary local pipelines or all registered models. +SM-25 extracts the supported-workflow usability subset from later SM-17j; wider +native model/engine coverage waits until the first local Bundle passes. + +## Later SM-17 scope and completion contract + +The user requested coverage of the existing nodes and models, not closure by +listing the rest as unsupported. Missing combinations stay open unless the user +explicitly defers them. This expansion starts after SM-20a; none of its missing +features is marked DONE. No implicit collection or algorithm swap. + +| Task | Status | Deliverable | +| --- | --- | --- | +| SM-17-00 | LATER | Expand the [100-ID inventory](NODE_SUPPORT.md) into per-option fit/apply/state/model/runtime coverage and a registry coverage guard | +| SM-17a | LATER | Column/cast/cleaning/date/math/interaction/polynomial and basic scaler native paths | +| SM-17b | LATER | Remaining imputation, categorical encoders, binning/ranges and robust/quantile state | +| SM-17c | LATER | Feature selection, transforms and outliers; fit/apply distinction and row alignment | +| SM-17d | LATER | Group/window/history and target/WOE OOF semantics; deterministic splits and leakage gates | +| SM-17e | LATER | Text/vectorization/embeddings and geo; sparse/vector contracts and worker dependencies | +| SM-17f | LATER | Split/resampling/inspection; training-only row changes, stable membership and bounded previews | +| SM-17g | LATER | Existing model-family bundle/inference coverage: sklearn variants, XGBoost/LightGBM, ensembles/calibration and clustering | +| SM-17h | LATER | Explicit native Spark model training/transform, artifact kind and MLflow persistence; all existing model IDs retain decisions/tasks | +| SM-17i | LATER | Evaluation/CV/tuning/thresholds and explainability/SHAP contracts; parallel trials versus distributed fit; bounded execution | +| SM-17j | LATER | Easier config/SDK entry point, preflight and independent platform/FE/model/sink/tracking choices; no Canvas or DAB work | +| SM-17k | LATER | Family regression gates and selected Databricks runtime validation; no missing requested coverage silently marked DONE | + +Family tasks depend on SM-17-00 and their relevant preceding contracts. Model +work need not wait for every independent FE family, but no task should claim +support before its artifact, inference and runtime requirements pass. + +Details, reference-repo comparison and parked endpoint tasks: +[Spark/Databricks gap review](reports/2026-09-22-spark-databricks-gap-review.md). ## Detay planlar - Completed SM-16 evidence and scope: [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). -- SM-15 currently provides the Spark writer only. The user's local-engine - Delta requirement is tracked separately as SM-15L and must be satisfied before - SM-20 offers that template combination. Template work remains last. -- The user confirmed the immediate order: finish SM-16, then SM-15L. +- SM-15 currently provides the Spark writer only. SM-15L is now required for + SM-20a's local monthly UC output and must establish its own transaction and + runtime evidence. The first template precedes Spark expansion. +- Latest user direction supersedes the prior Spark-first and template-last order: + deliver a local pandas/Polars Bundle, then expand Spark and add a tested Spark + option. SM-18 and continuous streaming remain parked. - SM-00–SM-07: [Core/Spark](01-core-spark-plan.md) - SM-08–SM-11: [Inference](02-inference-plan.md) - SM-12–SM-20: [MLflow/batch/son teslimatlar](03-mlflow-batch-delivery-plan.md) +- Current integration lane: [Local-first integration](04-databricks-integration-plan.md) + and [SM-20 Bundle rehearsal](05-sm20-bundle-plan.md). - Ortak kurallar: [Mimari](ARCHITECTURE.md), [Doğrulama](VALIDATION.md) -SM-17 başlangıcında 17a column/cast/date, 17b quantile/category, -17c group/window, 17d OOF alt görevlerine ayrılır. Her alt görevin kendi -test/review kapısı vardır. Tüm node'ların native olması zorunlu değildir; -gerçekten desteklenen kapsam ilan edilerek G5 kapatılır. -SM-19 streaming isteğe bağlıdır; HTTP/SQL bittiğinde streaming unsupported -olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. +SM-17 requires the full tracked scope above. Some algorithms may need an explicit +alternative backend rather than an equivalent native Spark implementation; that +decision must not hide missing support. SM-19 streaming remains optional and parked. ## SM-16 — 2026-09-22 local and live validation, DONE @@ -80,9 +166,9 @@ olarak açıkça kaydedilebilir, template'i belirsiz süre bloke etmez. rejection. Contender `404334394214907` then failed a test-only permission-code assertion; final restricted job `977447944071613` passed actual MODIFY denial, unchanged data/version and owner release. The failed run remains documented. -- SM-15L is **READY** and next: local pandas/Polars Delta sink with explicit - storage/provenance limits and separately validated UC access. No implementation - of that local sink is included in SM-16. +- SM-15L was deferred immediately after SM-16; the later local-first Bundle + request reopens it after SM-24a. No implementation of that local sink is + included in SM-16, and real UC access remains an acceptance requirement. ## SM-15 — 2026-09-22 validation record @@ -255,499 +341,6 @@ olarak yazılır; yerel test sonucu gerçek UC/Databricks sonucu yerine geçmez. Önce README, mimari ve bu kuyruğu oku. Güncel git durumunu ve ilgili kaynakları doğrula; kullanıcı değişikliklerini koru. İlk READY görevi ACTIVE yap, kendi -test döngüsüyle tamamla ve kanıtı yaz. Sonraki bağımlılığı aç. Endpoint veya -template'e önden başlama. SM-00 yalnız test/runtime hazırlığıydı; güncel -destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. - -## SM-00 — 2026-09-21 tamamlanma kaydı - -- Başlangıç HEAD: `2397c11648c27645a4ee332412a503c394c1c2f2`; değişiklikler uncommitted. -- Test fixture/smoke, optional extra/requirements, Spark CI lane ve 0.9.0 - Unreleased changelog oluşturuldu. Detaylı ortam ve komutlar [BASELINE.md](BASELINE.md). -- Local baseline: 206 passed, 5 mevcut numeric warning. -- PySpark 4.0.3 + Temurin Java 17.0.20.1 + Python 3.12.10: 2 passed, temiz kapanış. -- Spark olmayan base ortam: 2 skipped; zorunlu Spark modu: beklenen 2 setup error, - exit 1. Eksik dependency başarılı CI gibi raporlanmıyor. -- Ruff check/format ve scoped ty geçti. GitHub Actions ve Databricks çalıştırılmadı. -- Sonraki görev SM-01; bu kanıt native Spark node desteği anlamına gelmez. - -## SM-01 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `105a6fe4`; bu kayıt doğrulanmış SM-01 çalışma ağacına aittir. -- Yeni `core/execution.py`: frozen FrameSpec ve ExecutionOptions, strict - `from_config`, pozitif integer limitleri; engine default'unu değiştirmez. -- Yeni `core/capabilities.py`: immutable operation/engine/config desteği ve - structured UnsupportedExecutionError. NodeRegistry mevcut Calculator sınıfında - declaration tutar; alias aynı sınıfı paylaşır, subclass açıkça yeniden ilan eder. -- Yeni testler `tests/unit/test_execution_contract.py` ve - `tests/unit/test_execution_capabilities.py`; Spark gerektirmeyen kurallar bu - yüzden planlanan spark/ dizini yerine unit/ altındadır. -- İlk 48 test eksik modüllerle fail oldu; uygulama sonrası geçti. Tam core: - `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q - --tb=short --disable-warnings -p no:cacheprovider --basetemp .cache/sm01-core` - → **9850 passed, 84 skipped, 1077 warnings**, 127.52 saniye; 3 snapshot geçti. -- Bağımsız inceleme bloklayan sorun bulmadı. Ek alias/subclass, type-exact - selector, invalid registration ve optional import regresyonlarından sonra: - iki yeni unit dosyası + test_engines_registry.py + test_core_seams.py - → **94 passed**. Bu son eklemeler test kapsamıdır; ürün kodu değişmedi. -- Tam repo ty, scoped Ruff/format ve yeni core modüllerinde CCN<=8 kontrolü geçti. - `mkdocs build --strict` başarılı; docs/user_guide/spark.md kontrat örnekleri - doğrudan çalıştırıldı. Kullanıcı belgeleri uygulamayla birlikte güncellendi. -- Spark engine/node desteği henüz etkin değil. Existing local pipeline preflight'ı - bu yeni API'ye bağlanmadı; SM-03'te yapılacak. Sıradaki görev SM-02. - -## SM-02 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `b9eef16a`; bu kayıt SM-02 çalışma ağacına aittir. -- SparkEngine ve ayrı DistributedDataFrame sözleşmesi eklendi. Gerçek dataframe - tanıma, literal kolon seçimi ve native frame erişimi var; varsayılan local - engine korunur. Eksik Spark dependency/registration local fallback'e gitmez. -- Adapter session oluşturmaz; `len/shape/to_pandas/to_numpy/to_arrow` ve - SklearnBridge üzerinden Spark feature/target dönüşümü açık hata verir. - `from_pandas/create_dataframe` çağırana kendi SparkSession'ını kullanmasını söyler. -- TDD: ilk 12 gerçek Spark testi başarısızdı; adapter sonrası runtime dahil - 14 test geçti. Son iki lazy-operation/namespace testi ve review düzeltmesiyle: - `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, `SKYULF_REQUIRE_SPARK=1`; - `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark - skyulf-core/tests/unit/test_spark_optional_import.py - skyulf-core/tests/unit/test_engines_registry.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm02-spark-reviewed` - → **46 passed**, 11.07 saniye; JVM temiz kapandı. -- PySpark 4.0.3 / Python 3.12.10 / Java 17 profili kullanıldı. Base ortamda - subprocess import engeli PySpark/MLflow yokken core importunu ve local seçimi - doğrular. Aynı test Spark kurulu ortamda da dependency yokluğunu simüle eder. -- Bağımsız review yalnız dependency hata mesajındaki dağıtım adını düzeltti: - `skyulf-core[spark]`. İlk tam core koşusu bu düzeltme sırasında eski toplanmış - test beklentisi/yeni subprocess kaynağı nedeniyle 1 failed verdi; son kaynakla - odaklı test **3 passed**. Son kaynakla tam core tekrarı: - `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q - --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm02-core-reviewed` - → **9875 passed, 84 skipped, 1077 warnings**, 163.31 saniye. -- Ruff check/format ve tam repo ty geçti. Yeni adapter max CCN=3. - `mkdocs build --strict` geçti; Spark rehberindeki runtime/adapter örnekleri - gerçek oturumda çalıştırıldı. Rehber ve 0.9.0 Unreleased changelog güncel. -- Sınır: native FE node, Spark dispatcher veya model inference etkin değil. - Databricks/Connect/uzak CI çalıştırılmadı. Sonraki görev SM-03. - -## SM-03 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `2d8cd8e5`; bu kayıt SM-03 çalışma ağacına aittir. -- FeatureEngineer `frame_spec` / `execution_options` ile Spark'a opt-in olur. - Yeni `_spark.py` native yürütmeyi local profiler'dan ayırır. Dispatcher input - hazırlığı engine-keyed mapping kullanır. `SkyulfSchema` Spark tiplerini okur. -- Key/target tek frame'de kalır; key null/duplicate ve desteklenmeyen dtype/schema - kontrolleri var. Bütün node fit/apply capability'leri action öncesi kontrol - edilir. Her node sonrası protected projection `exceptAll` karşılaştırması - key/label değişimini, row drop/expand'i reddeder. Validation sonucu limit(1)'dir; - full scan/shuffle maliyeti rehberde yazılıdır. Native node desteği ilan edilmez. -- Otomatik feature listesi key/target dışındadır. Literal dot/backtick kolonlar, - case-insensitive ambiguity ve internal aggregate alias collision testlidir. - Local get_data_stats Spark'ı açıkça reddeder; Spark FE metriklerinde row count, - fit_time ve peak_memory unknown (`None`). Driver süre ölçümü ayrı isimlidir. -- Planlanan base.py/data/dataset.py değişikliği gerekmedi: mevcut local profiler'a - girilmeden routing yapılır; tuple/SplitDataset Spark input sınırda reddedilir. - Local frame/tuple/split API'leri korunur; explicit engine seçimi her split'i denetler. -- TDD: ilk Spark contract koşusu **10 failed**; uygulama sonrası **10 passed**. - Ek güvence testlerinde case-insensitive isim hataları yeniden üretildi ve - düzeltildi. Bağımsız review internal alias bulgusunu verdi; son recheck temiz. -- Son Spark + dispatcher/optional import komutu: - `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, `SKYULF_REQUIRE_SPARK=1`; - `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark - skyulf-core/tests/unit/test_spark_optional_import.py - skyulf-core/tests/unit/test_preprocessing_dispatcher.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm03-spark-reviewed` - → **69 passed**, 61.59 saniye; PySpark 4.0.3/Python 3.12.10/Java 17, temiz kapanış. -- İlk full core **9875 passed, 107 skipped, 1077 warnings**, 170.97 saniye. - Ardından explicit local engine/split seçimindeki iki hata testle üretildi; - fix sonrası yeni 9 test + dispatcher/pipeline/base/optional import **124 passed**. - Son full core komutu: - `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q - --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm03-core-final` - → **9884 passed, 107 skipped, 1077 warnings**, 170.30 saniye. -- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Spark rehberindeki - beş Python örneği aynı gerçek session'da çalıştırıldı; beklenen unsupported - capability örneği de doğrulandı. Changelog/rehber birlikte güncellendi. -- Sınır: built-in native node, portable state codec, distributed model inference, - explicit aggregate metrics ve Databricks/Connect testi henüz yok. SM-04 sırada. - -## SM-04 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `44b5241e`; bu kayıt SM-04 çalışma ağacına aittir. -- `core/portable_state.py`: UTF-8 tagged JSON v1 encode/decode; explicit encode - byte bütçesi ve parse öncesi decode limiti (varsayılan 8 MiB). StandardScaler ve - mean/constant SimpleImputer gerçek artifact sözlükleri, boş no-op state dahil. -- Integer/string/bool/null ayrımı, non-finite float ve signed zero, kolon sırası - korunur. Unknown version/node/fields/tags, duplicate JSON/map keys/columns, - inconsistent state, unsupported Python objects ve aşırı nesting reddedilir. - Checksum canonical semantic content üzerinden SHA-256; imza değildir. -- `core/artifacts.py` StandardScaler mean/var alanları mevcut disabled-flag - davranışına uygun `None` kabul edecek şekilde düzeltildi. İlgili scaling testi - mean-enabled koşulda non-null assertion ile gerçek beklentiyi açıkça doğrular. -- `pipeline/seal.py` değişmedi: eski fingerprint ve pickle formatını değiştirmek - gerekmedi. Portable checksum kendi versioned vocabulary'sine sahiptir. - API'de bulunmayan producer/schema bilgisi uydurulmadı; mimari metadata sınırı - güncellendi. Future bundle bu bilgiyi gerçek input/execution bağlamından alacak. -- TDD ilk koşu eksik modül nedeniyle fail; ilk uygulama **44 passed**. UTF-16 - kabulü ve review'un compact Unicode byte-limit bulgusu ayrı red/green testlerle - düzeltildi. Review son recheck'te limit sınırlarını bağımsız doğruladı. -- Odaklı komut: `.venv/Scripts/python.exe -m pytest - skyulf-core/tests/spark/test_portable_state.py - skyulf-core/tests/unit/test_pipeline_seal.py skyulf-core/tests/unit/test_pipeline.py - skyulf-core/tests/unit/test_pipeline_threshold_fingerprint.py - skyulf-core/tests/integration/test_scaling.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm04-reviewed` - → **188 passed**, 5 mevcut numeric warning, 4.69 saniye. Eski save/load testleri - ve fingerprint golden testleri değişmeden geçti. İlk odaklı koşunun Windows - default temp erişim hatası workspace içindeki basetemp ile giderildi. -- Spark profile: `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark/test_portable_state.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm04-spark-codec` - → **61 passed**, 1.22 saniye. Codec JVM kullanmaz; bu sonuç Spark FE kanıtı değildir. -- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests - -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm04-core` - → **9945 passed, 107 skipped, 1077 warnings**, 168.18 saniye. - Ruff/format, tam repo ty ve - `mkdocs build --strict` geçti. Rehberdeki yeni codec örneği base ortamda çalıştı. -- Sınır: ayrı codec API'sidir; FeatureEngineer/model worker için otomatik paketleme - yok. Byte limiti toplam process memory limiti değildir. Native SimpleImputer - SM-05, StandardScaler SM-06; Spark runtime/Databricks bu görevde çalıştırılmadı. - -## SM-05 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `81216e16`; bu kayıt SM-05 çalışma ağacına aittir. -- `imputation/_spark_simple.py`: mean/constant için native fit/apply. Mean, - missing counts ve otomatik seçim istatistikleri aynı aggregate sorgusunda; - driver'a tek istatistik satırı döner. Constant da mevcut artifact missing-count - sözleşmesi için aggregate kullanır. Boş kolon seçimi doğrudan no-op. -- Apply native expressions kullanır; veri action'ı, Python UDF veya pandas - fallback yok. FeatureEngineer'ın key/target doğrulama action'ları devam eder. - Integer constant hassasiyeti korunur; mean double promotion yapabilir. - All-null mean uydurulmaz; numeric/string/bool sabitlerin sınırları rehberde. -- Registry mean/constant için fit/apply capability ve codec v1 bildirir. - Runner node default'larını preflight öncesi normalize eder; açık `columns=[]` - korunur. `state_max_bytes` fit artifact'ında ve transform action'larından önce - uygulanır. Direct apply codec yapısal doğrulamasını wire limiti dayatmadan kullanır. -- pandas/Polars/Spark arasında 18 fit/apply kombinasyonu JSON round-trip ile - doğrulandı. Yeni test dosyasında 36 vaka: train-only öğrenme, null/NaN, - all-null, kolon seçimi, dtype, key/target, lazy plan, state bütçesi ve precision. -- İlk TDD koşusu **19 failed, 8 passed**; native uygulama sonrası **26 passed**, - bir fixture DDL quoting hatası düzeltildi. Bağımsız review üç yakın-binary - değerin yanlış elenmesini ve imported state'in `x`/`X` çakışmasını buldu. - Gerçek runtime tekrarları ve regresyonlarla düzeltildi; review recheck temiz. -- Gerçek Spark komutu: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, - `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py - -q --tb=short -o addopts= -p no:cacheprovider - --basetemp .cache/sm05-spark-full` - → **157 passed, 2 warnings**, 112.97 saniye. PySpark 4.0.3 / Java 17; - Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. -- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests - -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm05-core-full` - → **9945 passed, 143 skipped, 1077 warnings**, 185.45 saniye. - Base ortamda PySpark yok; 36 yeni runtime testi burada skip, üstte gerçek Spark'ta geçti. -- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Spark rehberindeki - session kurulumundan sonraki yedi Python snippet'i aynı gerçek session'da - çalıştırıldı: `.venv-spark/Scripts/python.exe -m pytest - .cache/sm05_docs/test_spark_examples.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm05-doc-examples` - → **1 passed**, 27.12 saniye; mevcut pandas fillna FutureWarning. -- Sınır: median/mode, StandardScaler native apply, distributed model inference, - MLflow ve Databricks/Connect entegrasyon kanıtı henüz yok. Sonraki görev SM-06. - -## SM-06 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `992d13b2`; bu kayıt SM-06 çalışma ağacına aittir. -- `scaling/_spark_standard.py`: native fit/apply, population variance (`ddof=0`), - dört with_mean/with_std kombinasyonu, portable codec v1 capability. Mean/std - seçeneklerine bağlı None alanları mevcut artifact sözlüğüyle uyumlu. -- Fit en fazla iki distributed aggregate sorgusu çalıştırır; her biri tek - O(kolon) istatistik satırı döndürür. İlk sorgu min/max referansları, infinity - ve satır/otomatik seçim kontrolleri; ikinci sorgu referanstan farkların - mean/var_pop/count değerleri. İki flag kapalıysa ikinci sorgu gerekmez. - Sıfırı kapsayan aralık referans 0; diğerlerinde sıfıra yakın uç değer kullanılır. -- Null/NaN fit'te dışlanır. All-missing istatistikler NaN; tek gözlem/sabit - varyans 0 ve scale 1. Near-constant scale için sklearn'in float64 hata sınırı - uygulanır. Seçili infinity/overflow reddedilir; Spark double precision sınırı - ve sayısal tolerance rehberde açık. Decimal/string/nested scaling unsupported. -- Apply native ifadelerle lazy; Python UDF/action/pandas dönüşümü yok. Kolon - adları literal, input kolon sırası korunur; keyed runner key/target'ı doğrular. - Doğrudan apply eksik kolonları local scaler gibi atlar; pipeline mevcut giriş - kolon sözleşmesini korur. Integer/bool seçili kolonlar enabled apply'da double olur. -- `_spark_numeric.py`: imputer ile ortak kolon çözümleme, null/NaN, otomatik - seçim istatistikleri ve case-sensitive isim kontrolü. Mevcut imputer davranışı - regresyon testleriyle korundu; local pandas/Polars uygulaması değiştirilmedi. -- 57 scaler testi: 36 çapraz engine/flag kombinasyonu, held-out veri, column order, - null/NaN, sabit/tek/boş veri, dtype, key/target, lazy plan ve bounded collection. - Normal fixture rtol=1e-10/atol=1e-12; 1e12 offset ve küçük spread fixture'ında - temsil aralığına bağlı rtol=0.002, repartition 1/2/7. -- TDD başlangıcı **33 failed, 16 passed**; ilk scaler+imputer koşusu **85 passed**. - Bağımsız review doğrudan avg'nin büyük sabit kolonda 0 yerine 0.0968 - üretmesini, ardından koşulsuz min-reference'ın mixed-sign küçük katkıyı - kaybetmesini buldu. Her bulgu iki red regresyonla yeniden üretildi; son tam - Spark koşusunda düzeltmeler geçti. Review son recheck'te önemli bulgu kalmadı. -- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, - `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py - -q --tb=short -o addopts= -p no:cacheprovider - --basetemp .cache/sm06-spark-full` - → **214 passed, 2 warnings**, 197.25 saniye. PySpark 4.0.3 / Java 17; - Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. -- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests - -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm06-core-full` - → **9945 passed, 198 skipped, 1077 warnings**, 186.87 saniye. - Bu koşu 55 yeni scaler runtime testini PySpark olmayan base ortamda skip etti; - sonradan eklenen iki mixed-sign testi dahil tüm 57 vaka üstte gerçek Spark'ta geçti. -- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Rehberdeki session - kurulumundan sonraki sekiz Python snippet'i aynı gerçek session'da çalıştı: - `.venv-spark/Scripts/python.exe -m pytest .cache/sm06_docs/test_spark_examples.py - -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm06-doc-examples` - → **1 passed**, 32.00 saniye; mevcut pandas fillna FutureWarning. -- Sınır: FeatureEngineer export_state/from_state, tüm zincirin persistence - kapısı ve örnek script SM-07'de. Distributed model inference, MLflow ve - Databricks/Connect entegrasyon doğrulaması henüz yok. - -## SM-07 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `802f60d3`; bu kayıt SM-07 çalışma ağacına aittir. -- Public `FeatureEngineer.export_state() -> bytes` ve `from_state(...)`: - sıralı step isimleri/config'leri ve mevcut node codec envelope'ları tek - versioned JSON paketinde. İlk destek mean/constant imputer ve StandardScaler. - Öğrenilmiş kolon seçimi explicit hale gelir; auto-selection yeniden çalışmaz. - Session/keys/target runtime'dan yeniden alınır; core dosya I/O yapmaz. -- `core/portable_pipeline.py` toplam wire bütçesini parse öncesinde kontrol eder; - step sırası, config ve nested state checksum kapsamındadır. Bilinmeyen - node/version, custom applier, bozuk veya eksik fit state'i açıkça reddedilir. - `_feature_state.py` yalnız bilinen applier'ları kurar; Spark key/target ile - öğrenilmiş feature çakışmasını execution başlamadan reddeder. -- Node ve pipeline wire JSON compact UTF-8; semantic checksum'ın mevcut ASCII - canonical biçimi değişmedi. Unicode kolonlarda re-encoding kaynaklı yanlış - bütçe aşımı giderildi; escaped surrogate isimler eski codec ile uyumlu. -- Başarılı tuning'in adopted FE state'i export edilebilir. Başarısız local/model - refit export'u kapatır; boş pipeline da buna dahildir. Spark'ın başarısız refit'i - önceki başarılı state'i koruma sözleşmesi değişmedi. Legacy pickle ve pipeline - fingerprint hesapları mevcut regresyonlarla korundu. -- `tests/spark/test_feature_pipeline.py`: gerçek üç fit × üç apply engine, - dosyada JSON round-trip, repartition 1/2/7, ters girdi ve tekrar transform. - Key bazlı sonuçlar aynı; train-only learned state değişmez. 10.000 satırlı - imputer→scaler testinde unbounded collect ve local conversion yasak; yalnız - bounded aggregate/validation satırları driver'a döner. Fixture dosya içindedir. -- Bağımsız review Unicode byte limiti ve tuning fitted-state aktarımını buldu. - Gerçek Spark Unicode testi düzeltmeden önce failed, sonra passed. Tuning/model - × boş/scaler dört regresyonu önce failed, sonra passed; exception sonrası boş - pipeline'ın yanlış export edilmesi de düzeltildi. Son review recheck temiz. -- Dar local state/codec/lifecycle koşusu: **101 passed, 28 warnings**, 1.75 saniye. - Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests - -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm07-base-full` - → **9969 passed, 223 skipped, 1077 warnings**, 192.35 saniye. Base ortamda - PySpark yok; runtime skip'leri gerçek Spark lane'inden ayrı değerlendirilir. -- `skyulf-core/examples/spark_feature_engineering.py --state-path - .cache/sm07-example-features.json` gerçek PySpark 4.0.3/Java 17 ile çalıştı: - **1949 byte**, üç keyed feature beklenen ±sqrt(1.5)/0; dosya save/load ve - JVM kapanışı başarılı. Rehber kullanım, frozen columns ve runtime sınırlarını açıklar. -- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, - `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py - skyulf-core/tests/unit/test_feature_state.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm07-spark-full` - → **261 passed, 2 warnings**, 345.28 saniye. PySpark 4.0.3 / Java 17; - Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. -- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Rehberde session - kurulumundan sonraki dokuz Python snippet'i aynı gerçek session'da çalıştı: - `.venv-spark/Scripts/python.exe -m pytest .cache/sm07_docs/test_spark_examples.py - -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm07-doc-examples` - → **1 passed, 1 warning**, 38.00 saniye; mevcut pandas fillna FutureWarning. -- Sınır: G1 feature engineering içindir; model bundle/inference, MLflow, - Databricks/Connect ve endpoint/template doğrulaması değildir. Sonraki görev SM-08. - -## SM-08 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `7099733c`; bu kayıt SM-08 çalışma ağacına aittir. -- `skyulf/inference/` public API: `build_bundle`, `save_bundle`, `load_bundle`, - `predict_local`, immutable `InferenceBundle`. Metadata ve payload bytes ayrı; - `raw` input'ta FE bir kez uygulanır, `features` doğrudan model tahminidir. - pandas/Polars girdisi; çıktı pandas prediction/probability kolonlarıdır. -- `SkyulfPipeline.fit` metadata-only `_inference_schemas` kaydeder: target hariç - raw input ve gerçek model training feature sırası/dtype'ları. Başarısız refit - temizler; raw frame tutulmaz. NumPy bridge'in kaybettiği kolon adları tahminle - doldurulmaz. Schema capture 31 gerçek frame/tuple/split/wrapper/tuning testiyle - korundu; mevcut pickle ve fingerprint davranışı değişmedi. -- Katı manifest: stage, input/model/output schema, class/probability sırası, - positive label, tuning ve explicit pipeline threshold provenance, sabit - dependency listesi ve digest'ler. pandas/Polars Boolean/bool eşleştirmesi açık. - Eksik/ekstra/tekrarlı/sırası yanlış veya dtype'ı farklı feature'lar reddedilir. -- Kayıt üç sabit isimli dosyadır: manifest.json, features.json, model.pkl. - Var olan hedefe yazılmaz. FE+manifest state bütçesi ile model wire bütçesi ayrı; - protokol-5 PickleBuffer byte sayımı ve explicit FE limitinin tüm çağrılara - aktarımı test edildi. Kaynak pipeline'ın sonraki mutasyonu paketi değiştirmez. -- Semantic digest pickle protokolüne bağlı değildir; ayrıca model/FE wire - checksum kontrolü yapılır. Pickle yalnız güvenilir üreticiden yüklenir. - Python major/minor ve skyulf-core/sklearn/NumPy/SciPy sürümleri yüklemeden - önce doğrulanır. pandas/Polars sürümleri provenance olarak kaydedilir. -- Ruling: local giriş yalnız feature kolonlarını kabul eder; id gibi ekstra - kolonlar otomatik elenmez. SM-09 runner key'leri model girişinden açıkça ayırır. - Fixture seed=17, iki farklı ölçekli x/z kolonu ve held-out satırlar içerir; - test dosyasında tutulur. Bu, plandaki tek x/id örneğine göre kolon sırası - hatasını da yakalar; SM-09 shared fixture'a ihtiyaç duyduğunda taşınabilir. -- Ruling: mevcut `core/serialization.py` provider'ı ve eski backend okuyucu - değiştirilmedi. Standalone adapter `SkyulfPipeline.load` → `build_bundle`; - schema bilgisi olmayan eski pickle yeniden fit gerektirir. Backend dict - doğrudan reddedilir, adapter SM-18'de. İlk FE desteği SM-07'nin node'ları; - split node yerine explicit SplitDataset ile training partitions verilebilir. -- Bağımsız review Polars Boolean alias'ını, 8 MiB üstü FE için custom budget - aktarımını ve büyük estimator protocol-5 PickleBuffer serialization hatasını - yeniden üretti. Red regresyonlardan sonra düzeltildi. Re-review: gerçek - 144 KB KNN bundle ve 8.39 MB FE / 16 MiB bütçe ile pandas+Polars inference geçti; - açık önemli bulgu kalmadı. KNN gibi modeller kendi state'lerinde örnek tutabilir; - schema capture'ın veri tutmaması estimator'ın bu davranışını değiştirmez. -- Dar testler: **76 passed, 2 skipped, 21 warnings**, 4.46 saniye. İki skip - Spark-local giriş reddi vakasıdır; gerçek Spark lane'inde ayrıca çalışır. -- `skyulf-core/examples/inference_bundle.py --bundle-dir .cache/sm08-example-model` - çalıştı: kayıt/yükleme sonrası **[40.0, 20.0]**, raw/features parity ve aynı - semantic digest. Ayrı base-process import kontrolü PySpark/MLflow yüklemedi. -- Yeni `docs/user_guide/inference_bundles.md`, Spark rehberi linki ve nav kaydı. - Rehberin Python örneği gerçek base ortamında **1 passed**, 2.08 saniye; - `mkdocs build --strict` başarılı. Ruff/format ve tam repo ty geçti. -- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests - -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm08-core-full` - → **10045 passed, 225 skipped, 1097 warnings**, 193.33 saniye. Base ortamda - PySpark yok; yeni gerçek Spark input-ret testleri burada iki skip'tir. -- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, - `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py - skyulf-core/tests/unit/test_feature_state.py - skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --tb=short - -o addopts= -p no:cacheprovider --basetemp .cache/sm08-spark-full` - → **339 passed, 2 warnings**, 340.64 saniye. PySpark 4.0.3 / Java 17; - Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. -- Sınır: bu görev local paketleme/inference içindir. Spark worker model runner - SM-09, ikinci Python FE yolu SM-10, dağıtık classification kapısı SM-11'dir. - MLflow, Databricks/Connect, endpoint ve template doğrulaması henüz yok. - -## SM-09 — 2026-09-21 tamamlanma kaydı - -- Başlangıç commit'i `81745a7b`; bu kayıt SM-09 çalışma ağacına aittir. -- `inference/spark.py` ve public `predict_spark`: raw girdiye native FE, - ardından `mapInPandas` iterator'larında Python regression tahmini. Model - iterator başına bir kez yüklenir; yalnız feature'lar ve key'ler worker'a gider. - Ortak model tahmin helper'ı local davranışı tekrar kullanır. Session, frame - veya bağlantı worker closure'a girmez; pandas dönüşümü worker batch'indedir. -- `tests/spark/test_native_features_inference.py`; SM-08'in fitted pipeline ve - raw-frame fixture'ları ortak conftest'e taşındı. pandas/Polars eğitim, bundle - kayıt/yükleme, repartition 1/3, Arrow limit 1/5, eksik değerler, boş veri ve - partition'lar, birleşik key'ler, `2**53` üstü identity, worker projection, - bounded driver validation, iterator model yükleme ve chunk sınırı doğrulandı. -- Ruling: native model schema önce yalnız Spark ifadeleri oluşturularak - incelenir; sonra mevcut FE key/preservation kontrolleri çalışır. Preview veri - action'ı içermez, öğrenilmiş kuralları tekrar fit etmez. Local integer imputer - çıktısı ile Spark double promotion uyuşmazlığı artık action'dan önce hata verir. -- Ruling: nullable integer/boolean model feature schema'ları erken reddedilir; - Arrow null batch dönüşümü hassasiyet kaybetmeden çözülene kadar destek ilan - edilmez. Non-nullable integer model feature ve büyük integer key gerçek action - ile geçti. Key'lerin nullable schema metadata'sı ayrı değer kontrolüyle korunur. - Broader nullable transport SM-11'e kayıtlıdır. -- Ruling: raw model input kolonlarının kendi sırası/dtype'ları korunmalı; - extra kolonlar projection ile elenir. Key'ler integer/string/boolean'dır; - feature/output isimleriyle çakışamaz. Incoming prediction kolonu da reddedilir. - `FrameSpec.target` boş olmalıdır. Raw regression dışındaki stage/task/mode ve - streaming açık ret verir. `python_batch_rows` model çağrısını sınırlar; - Arrow transport konfigürasyonuna veya kullanıcının Spark session'ına yazılmaz. -- TDD red: eksik public API; streaming, native dtype ve nullable transport - girdilerinin doğrulamadan önce Spark action'a ulaşması ayrı ayrı yeniden - üretildi. Dar final test: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, - `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark/test_native_features_inference.py - skyulf-core/tests/spark/test_inference_bundle.py -q -o addopts= - -p no:cacheprovider --basetemp .cache/sm09-runner-final` - → **101 passed**, 110.42 saniye; owned JVM temiz kapandı. -- Bağımsız review iki schema/Arrow bulgusunu doğruladı; düzeltmelerin ve red - regresyonların yeniden incelemesinde açık yüksek/orta bulgu kalmadı. -- Eski backend artifact akışı ayrıca doğrulandı: `.venv/Scripts/python.exe -m - pytest tests/integration/test_bundle_preprocessing_integrity.py - tests/integration/test_full_inference_pipeline.py -q --tb=short -o addopts= - -p no:cacheprovider --basetemp .cache/sm09-legacy` - → **22 passed, 30 warnings**, 7.80 saniye. Backend kaynakları değiştirilmedi; - full FE/model joblib reader korunuyor, yeni bundle adapter'ı SM-18'de. -- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests - -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider - --basetemp .cache/sm09-core-full` - → **10050 passed, 274 skipped, 1097 warnings**, 194.81 saniye. Base ortamda - PySpark yok; gerçek Spark testleri ayrı lane'de doğrulanır. -- Ruff/format ve tam repo ty başarılı. Bundle/Spark rehberleri mevcut artifact - davranışını, yeni runner'ı, dtype ve sürüm sınırlarını açıklıyor. - `mkdocs build --strict` başarılı. -- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, - `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest - skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py - skyulf-core/tests/unit/test_feature_state.py - skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --tb=short - -o addopts= -p no:cacheprovider --basetemp .cache/sm09-spark-full` - → **393 passed, 2 warnings**, 418.45 saniye. PySpark 4.0.3 / Java 17; - JVM temiz kapandı. Warning'ler mevcut Split alias'ına ait. -- Spark runtime: Python 3.12.10, skyulf-core 0.9.0, pandas 2.3.2, - Polars 1.44.2, sklearn 1.9.1, NumPy 1.26.4, SciPy 1.17.1, Arrow 24.0.0. -- Rehberin iki Python bloğu `.venv-spark/Scripts/python.exe - .cache/sm09_docs_example.py` ile aynı ortamda çalıştırıldı: local kayıt/yükleme - ve key'li Spark sonucu **[40.0, 20.0]**, başarılı assert'ler ve temiz JVM kapanışı. -- Sınır: bu G2a / native FE + regression teslimatıdır. SM-10 Python FE worker - modu, SM-11 classification/worker wheel/ölçek kapısıdır. Databricks/Connect, - MLflow/UC, endpoint ve template doğrulaması yoktur. Sıradaki görev SM-10. - -## SM-11 — 2026-09-22 final validation record - -- Starting point: `a930f8a5`; implementation commits: `04dbe303` and - corrective `7cdd622c`. The earlier DONE label was reopened during review and - is now restored only after the corrective evidence below. -- `predict_spark` now accepts raw regression and classification bundles in both - `native_features` and `python_pipeline` modes. The output schema maps - manifest label dtypes to Spark types and keeps probability columns in the - estimator class order. Saved tuning and explicit pipeline threshold rules - reuse the local `_predict_features` contract. -- Added `tests/spark/test_prediction_contract.py` for string binary labels, - integer multiclass labels, probability ordering, saved thresholds, two - partition layouts and two Arrow batch limits. Added - `tests/spark/test_worker_isolation.py` to verify one model load per iterator - and bounded model calls. The former classification rejection regression test - now asserts the supported output contract. -- Added `skyulf-core/examples/spark_batch_inference.py`, which runs the same - classification bundle through both Spark modes. The example sets the current - interpreter as the Python worker on Windows when no worker override exists. -- Corrective focused verification: - `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp - .tmp-sm11-regression skyulf-core/tests/spark/test_native_features_inference.py - skyulf-core/tests/spark/test_python_pipeline_inference.py - skyulf-core/tests/spark/test_prediction_contract.py - skyulf-core/tests/spark/test_worker_isolation.py - skyulf-core/tests/spark/test_inference_bundle.py -q --disable-warnings - --maxfail=1` → **63 passed**. JVM cleanup prints the - existing Windows `ERROR: Access denied` after a successful exit. -- Full Spark gate after the corrective transport guard: - `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp - .tmp-sm11-spark-final skyulf-core/tests/spark - skyulf-core/tests/unit/test_execution_capabilities.py - skyulf-core/tests/unit/test_feature_state.py - skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --disable-warnings - --maxfail=1` → **418 passed, 2 warnings**, 525.50 seconds. The warnings are - existing; Windows prints the cleanup access-denied line after exit 0. -- Both example commands completed with exit code 0 and printed matching - `prediction`, `probability_0` and `probability_1` results. Ruff check and - format passed for all changed Python files. -- Nullable integer/boolean model-feature transport remains rejected because - Arrow can widen values with nulls. Worker wheel isolation, scale/RSS - measurements, MLflow, Databricks, endpoints and templates remain later work. -- Corrective preflight rejects nullable integral/boolean raw inputs in - `python_pipeline` before key validation. Independent estimator class/probability - assertions and a non-default threshold decision assertion are covered. A - wheel subprocess smoke imported `skyulf.inference.spark` from the built 0.9.0 - wheel. Local scale measurements recorded 10k/2 partitions at 3.929s and - 50k/8 partitions at 8.089s with driver peak RSS 246.2/246.8 MB and child - process peak RSS 887.2/922.7 MB. These results are evidence, not a production - performance guarantee. -- Next task: SM-12 optional MLflow tracking, with tracking disabled remaining a - valid local/Spark workflow. +test döngüsüyle tamamla ve kanıtı yaz. Sonraki bağımlılığı aç. İlk local Bundle +kapısından önce Spark veya endpoint işine başlama. SM-00 yalnız test/runtime +hazırlığıydı; güncel destek ve sınırlar tamamlanan görevlerin kayıtlarında belirtilir. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md b/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md new file mode 100644 index 000000000..c0e1f5a9c --- /dev/null +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md @@ -0,0 +1,492 @@ +## SM-00 — 2026-09-21 tamamlanma kaydı + +- Başlangıç HEAD: `2397c11648c27645a4ee332412a503c394c1c2f2`; değişiklikler uncommitted. +- Test fixture/smoke, optional extra/requirements, Spark CI lane ve 0.9.0 + Unreleased changelog oluşturuldu. Detaylı ortam ve komutlar [BASELINE.md](BASELINE.md). +- Local baseline: 206 passed, 5 mevcut numeric warning. +- PySpark 4.0.3 + Temurin Java 17.0.20.1 + Python 3.12.10: 2 passed, temiz kapanış. +- Spark olmayan base ortam: 2 skipped; zorunlu Spark modu: beklenen 2 setup error, + exit 1. Eksik dependency başarılı CI gibi raporlanmıyor. +- Ruff check/format ve scoped ty geçti. GitHub Actions ve Databricks çalıştırılmadı. +- Sonraki görev SM-01; bu kanıt native Spark node desteği anlamına gelmez. + +## SM-01 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `105a6fe4`; bu kayıt doğrulanmış SM-01 çalışma ağacına aittir. +- Yeni `core/execution.py`: frozen FrameSpec ve ExecutionOptions, strict + `from_config`, pozitif integer limitleri; engine default'unu değiştirmez. +- Yeni `core/capabilities.py`: immutable operation/engine/config desteği ve + structured UnsupportedExecutionError. NodeRegistry mevcut Calculator sınıfında + declaration tutar; alias aynı sınıfı paylaşır, subclass açıkça yeniden ilan eder. +- Yeni testler `tests/unit/test_execution_contract.py` ve + `tests/unit/test_execution_capabilities.py`; Spark gerektirmeyen kurallar bu + yüzden planlanan spark/ dizini yerine unit/ altındadır. +- İlk 48 test eksik modüllerle fail oldu; uygulama sonrası geçti. Tam core: + `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q + --tb=short --disable-warnings -p no:cacheprovider --basetemp .cache/sm01-core` + → **9850 passed, 84 skipped, 1077 warnings**, 127.52 saniye; 3 snapshot geçti. +- Bağımsız inceleme bloklayan sorun bulmadı. Ek alias/subclass, type-exact + selector, invalid registration ve optional import regresyonlarından sonra: + iki yeni unit dosyası + test_engines_registry.py + test_core_seams.py + → **94 passed**. Bu son eklemeler test kapsamıdır; ürün kodu değişmedi. +- Tam repo ty, scoped Ruff/format ve yeni core modüllerinde CCN<=8 kontrolü geçti. + `mkdocs build --strict` başarılı; docs/user_guide/spark.md kontrat örnekleri + doğrudan çalıştırıldı. Kullanıcı belgeleri uygulamayla birlikte güncellendi. +- Spark engine/node desteği henüz etkin değil. Existing local pipeline preflight'ı + bu yeni API'ye bağlanmadı; SM-03'te yapılacak. Sıradaki görev SM-02. + +## SM-02 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `b9eef16a`; bu kayıt SM-02 çalışma ağacına aittir. +- SparkEngine ve ayrı DistributedDataFrame sözleşmesi eklendi. Gerçek dataframe + tanıma, literal kolon seçimi ve native frame erişimi var; varsayılan local + engine korunur. Eksik Spark dependency/registration local fallback'e gitmez. +- Adapter session oluşturmaz; `len/shape/to_pandas/to_numpy/to_arrow` ve + SklearnBridge üzerinden Spark feature/target dönüşümü açık hata verir. + `from_pandas/create_dataframe` çağırana kendi SparkSession'ını kullanmasını söyler. +- TDD: ilk 12 gerçek Spark testi başarısızdı; adapter sonrası runtime dahil + 14 test geçti. Son iki lazy-operation/namespace testi ve review düzeltmesiyle: + `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, `SKYULF_REQUIRE_SPARK=1`; + `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark + skyulf-core/tests/unit/test_spark_optional_import.py + skyulf-core/tests/unit/test_engines_registry.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm02-spark-reviewed` + → **46 passed**, 11.07 saniye; JVM temiz kapandı. +- PySpark 4.0.3 / Python 3.12.10 / Java 17 profili kullanıldı. Base ortamda + subprocess import engeli PySpark/MLflow yokken core importunu ve local seçimi + doğrular. Aynı test Spark kurulu ortamda da dependency yokluğunu simüle eder. +- Bağımsız review yalnız dependency hata mesajındaki dağıtım adını düzeltti: + `skyulf-core[spark]`. İlk tam core koşusu bu düzeltme sırasında eski toplanmış + test beklentisi/yeni subprocess kaynağı nedeniyle 1 failed verdi; son kaynakla + odaklı test **3 passed**. Son kaynakla tam core tekrarı: + `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q + --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm02-core-reviewed` + → **9875 passed, 84 skipped, 1077 warnings**, 163.31 saniye. +- Ruff check/format ve tam repo ty geçti. Yeni adapter max CCN=3. + `mkdocs build --strict` geçti; Spark rehberindeki runtime/adapter örnekleri + gerçek oturumda çalıştırıldı. Rehber ve 0.9.0 Unreleased changelog güncel. +- Sınır: native FE node, Spark dispatcher veya model inference etkin değil. + Databricks/Connect/uzak CI çalıştırılmadı. Sonraki görev SM-03. + +## SM-03 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `2d8cd8e5`; bu kayıt SM-03 çalışma ağacına aittir. +- FeatureEngineer `frame_spec` / `execution_options` ile Spark'a opt-in olur. + Yeni `_spark.py` native yürütmeyi local profiler'dan ayırır. Dispatcher input + hazırlığı engine-keyed mapping kullanır. `SkyulfSchema` Spark tiplerini okur. +- Key/target tek frame'de kalır; key null/duplicate ve desteklenmeyen dtype/schema + kontrolleri var. Bütün node fit/apply capability'leri action öncesi kontrol + edilir. Her node sonrası protected projection `exceptAll` karşılaştırması + key/label değişimini, row drop/expand'i reddeder. Validation sonucu limit(1)'dir; + full scan/shuffle maliyeti rehberde yazılıdır. Native node desteği ilan edilmez. +- Otomatik feature listesi key/target dışındadır. Literal dot/backtick kolonlar, + case-insensitive ambiguity ve internal aggregate alias collision testlidir. + Local get_data_stats Spark'ı açıkça reddeder; Spark FE metriklerinde row count, + fit_time ve peak_memory unknown (`None`). Driver süre ölçümü ayrı isimlidir. +- Planlanan base.py/data/dataset.py değişikliği gerekmedi: mevcut local profiler'a + girilmeden routing yapılır; tuple/SplitDataset Spark input sınırda reddedilir. + Local frame/tuple/split API'leri korunur; explicit engine seçimi her split'i denetler. +- TDD: ilk Spark contract koşusu **10 failed**; uygulama sonrası **10 passed**. + Ek güvence testlerinde case-insensitive isim hataları yeniden üretildi ve + düzeltildi. Bağımsız review internal alias bulgusunu verdi; son recheck temiz. +- Son Spark + dispatcher/optional import komutu: + `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, `SKYULF_REQUIRE_SPARK=1`; + `.venv-spark/Scripts/python.exe -m pytest skyulf-core/tests/spark + skyulf-core/tests/unit/test_spark_optional_import.py + skyulf-core/tests/unit/test_preprocessing_dispatcher.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm03-spark-reviewed` + → **69 passed**, 61.59 saniye; PySpark 4.0.3/Python 3.12.10/Java 17, temiz kapanış. +- İlk full core **9875 passed, 107 skipped, 1077 warnings**, 170.97 saniye. + Ardından explicit local engine/split seçimindeki iki hata testle üretildi; + fix sonrası yeni 9 test + dispatcher/pipeline/base/optional import **124 passed**. + Son full core komutu: + `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests -q + --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm03-core-final` + → **9884 passed, 107 skipped, 1077 warnings**, 170.30 saniye. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Spark rehberindeki + beş Python örneği aynı gerçek session'da çalıştırıldı; beklenen unsupported + capability örneği de doğrulandı. Changelog/rehber birlikte güncellendi. +- Sınır: built-in native node, portable state codec, distributed model inference, + explicit aggregate metrics ve Databricks/Connect testi henüz yok. SM-04 sırada. + +## SM-04 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `44b5241e`; bu kayıt SM-04 çalışma ağacına aittir. +- `core/portable_state.py`: UTF-8 tagged JSON v1 encode/decode; explicit encode + byte bütçesi ve parse öncesi decode limiti (varsayılan 8 MiB). StandardScaler ve + mean/constant SimpleImputer gerçek artifact sözlükleri, boş no-op state dahil. +- Integer/string/bool/null ayrımı, non-finite float ve signed zero, kolon sırası + korunur. Unknown version/node/fields/tags, duplicate JSON/map keys/columns, + inconsistent state, unsupported Python objects ve aşırı nesting reddedilir. + Checksum canonical semantic content üzerinden SHA-256; imza değildir. +- `core/artifacts.py` StandardScaler mean/var alanları mevcut disabled-flag + davranışına uygun `None` kabul edecek şekilde düzeltildi. İlgili scaling testi + mean-enabled koşulda non-null assertion ile gerçek beklentiyi açıkça doğrular. +- `pipeline/seal.py` değişmedi: eski fingerprint ve pickle formatını değiştirmek + gerekmedi. Portable checksum kendi versioned vocabulary'sine sahiptir. + API'de bulunmayan producer/schema bilgisi uydurulmadı; mimari metadata sınırı + güncellendi. Future bundle bu bilgiyi gerçek input/execution bağlamından alacak. +- TDD ilk koşu eksik modül nedeniyle fail; ilk uygulama **44 passed**. UTF-16 + kabulü ve review'un compact Unicode byte-limit bulgusu ayrı red/green testlerle + düzeltildi. Review son recheck'te limit sınırlarını bağımsız doğruladı. +- Odaklı komut: `.venv/Scripts/python.exe -m pytest + skyulf-core/tests/spark/test_portable_state.py + skyulf-core/tests/unit/test_pipeline_seal.py skyulf-core/tests/unit/test_pipeline.py + skyulf-core/tests/unit/test_pipeline_threshold_fingerprint.py + skyulf-core/tests/integration/test_scaling.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm04-reviewed` + → **188 passed**, 5 mevcut numeric warning, 4.69 saniye. Eski save/load testleri + ve fingerprint golden testleri değişmeden geçti. İlk odaklı koşunun Windows + default temp erişim hatası workspace içindeki basetemp ile giderildi. +- Spark profile: `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark/test_portable_state.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm04-spark-codec` + → **61 passed**, 1.22 saniye. Codec JVM kullanmaz; bu sonuç Spark FE kanıtı değildir. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm04-core` + → **9945 passed, 107 skipped, 1077 warnings**, 168.18 saniye. + Ruff/format, tam repo ty ve + `mkdocs build --strict` geçti. Rehberdeki yeni codec örneği base ortamda çalıştı. +- Sınır: ayrı codec API'sidir; FeatureEngineer/model worker için otomatik paketleme + yok. Byte limiti toplam process memory limiti değildir. Native SimpleImputer + SM-05, StandardScaler SM-06; Spark runtime/Databricks bu görevde çalıştırılmadı. + +## SM-05 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `81216e16`; bu kayıt SM-05 çalışma ağacına aittir. +- `imputation/_spark_simple.py`: mean/constant için native fit/apply. Mean, + missing counts ve otomatik seçim istatistikleri aynı aggregate sorgusunda; + driver'a tek istatistik satırı döner. Constant da mevcut artifact missing-count + sözleşmesi için aggregate kullanır. Boş kolon seçimi doğrudan no-op. +- Apply native expressions kullanır; veri action'ı, Python UDF veya pandas + fallback yok. FeatureEngineer'ın key/target doğrulama action'ları devam eder. + Integer constant hassasiyeti korunur; mean double promotion yapabilir. + All-null mean uydurulmaz; numeric/string/bool sabitlerin sınırları rehberde. +- Registry mean/constant için fit/apply capability ve codec v1 bildirir. + Runner node default'larını preflight öncesi normalize eder; açık `columns=[]` + korunur. `state_max_bytes` fit artifact'ında ve transform action'larından önce + uygulanır. Direct apply codec yapısal doğrulamasını wire limiti dayatmadan kullanır. +- pandas/Polars/Spark arasında 18 fit/apply kombinasyonu JSON round-trip ile + doğrulandı. Yeni test dosyasında 36 vaka: train-only öğrenme, null/NaN, + all-null, kolon seçimi, dtype, key/target, lazy plan, state bütçesi ve precision. +- İlk TDD koşusu **19 failed, 8 passed**; native uygulama sonrası **26 passed**, + bir fixture DDL quoting hatası düzeltildi. Bağımsız review üç yakın-binary + değerin yanlış elenmesini ve imported state'in `x`/`X` çakışmasını buldu. + Gerçek runtime tekrarları ve regresyonlarla düzeltildi; review recheck temiz. +- Gerçek Spark komutu: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + -q --tb=short -o addopts= -p no:cacheprovider + --basetemp .cache/sm05-spark-full` + → **157 passed, 2 warnings**, 112.97 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm05-core-full` + → **9945 passed, 143 skipped, 1077 warnings**, 185.45 saniye. + Base ortamda PySpark yok; 36 yeni runtime testi burada skip, üstte gerçek Spark'ta geçti. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Spark rehberindeki + session kurulumundan sonraki yedi Python snippet'i aynı gerçek session'da + çalıştırıldı: `.venv-spark/Scripts/python.exe -m pytest + .cache/sm05_docs/test_spark_examples.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm05-doc-examples` + → **1 passed**, 27.12 saniye; mevcut pandas fillna FutureWarning. +- Sınır: median/mode, StandardScaler native apply, distributed model inference, + MLflow ve Databricks/Connect entegrasyon kanıtı henüz yok. Sonraki görev SM-06. + +## SM-06 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `992d13b2`; bu kayıt SM-06 çalışma ağacına aittir. +- `scaling/_spark_standard.py`: native fit/apply, population variance (`ddof=0`), + dört with_mean/with_std kombinasyonu, portable codec v1 capability. Mean/std + seçeneklerine bağlı None alanları mevcut artifact sözlüğüyle uyumlu. +- Fit en fazla iki distributed aggregate sorgusu çalıştırır; her biri tek + O(kolon) istatistik satırı döndürür. İlk sorgu min/max referansları, infinity + ve satır/otomatik seçim kontrolleri; ikinci sorgu referanstan farkların + mean/var_pop/count değerleri. İki flag kapalıysa ikinci sorgu gerekmez. + Sıfırı kapsayan aralık referans 0; diğerlerinde sıfıra yakın uç değer kullanılır. +- Null/NaN fit'te dışlanır. All-missing istatistikler NaN; tek gözlem/sabit + varyans 0 ve scale 1. Near-constant scale için sklearn'in float64 hata sınırı + uygulanır. Seçili infinity/overflow reddedilir; Spark double precision sınırı + ve sayısal tolerance rehberde açık. Decimal/string/nested scaling unsupported. +- Apply native ifadelerle lazy; Python UDF/action/pandas dönüşümü yok. Kolon + adları literal, input kolon sırası korunur; keyed runner key/target'ı doğrular. + Doğrudan apply eksik kolonları local scaler gibi atlar; pipeline mevcut giriş + kolon sözleşmesini korur. Integer/bool seçili kolonlar enabled apply'da double olur. +- `_spark_numeric.py`: imputer ile ortak kolon çözümleme, null/NaN, otomatik + seçim istatistikleri ve case-sensitive isim kontrolü. Mevcut imputer davranışı + regresyon testleriyle korundu; local pandas/Polars uygulaması değiştirilmedi. +- 57 scaler testi: 36 çapraz engine/flag kombinasyonu, held-out veri, column order, + null/NaN, sabit/tek/boş veri, dtype, key/target, lazy plan ve bounded collection. + Normal fixture rtol=1e-10/atol=1e-12; 1e12 offset ve küçük spread fixture'ında + temsil aralığına bağlı rtol=0.002, repartition 1/2/7. +- TDD başlangıcı **33 failed, 16 passed**; ilk scaler+imputer koşusu **85 passed**. + Bağımsız review doğrudan avg'nin büyük sabit kolonda 0 yerine 0.0968 + üretmesini, ardından koşulsuz min-reference'ın mixed-sign küçük katkıyı + kaybetmesini buldu. Her bulgu iki red regresyonla yeniden üretildi; son tam + Spark koşusunda düzeltmeler geçti. Review son recheck'te önemli bulgu kalmadı. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + -q --tb=short -o addopts= -p no:cacheprovider + --basetemp .cache/sm06-spark-full` + → **214 passed, 2 warnings**, 197.25 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm06-core-full` + → **9945 passed, 198 skipped, 1077 warnings**, 186.87 saniye. + Bu koşu 55 yeni scaler runtime testini PySpark olmayan base ortamda skip etti; + sonradan eklenen iki mixed-sign testi dahil tüm 57 vaka üstte gerçek Spark'ta geçti. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Rehberdeki session + kurulumundan sonraki sekiz Python snippet'i aynı gerçek session'da çalıştı: + `.venv-spark/Scripts/python.exe -m pytest .cache/sm06_docs/test_spark_examples.py + -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm06-doc-examples` + → **1 passed**, 32.00 saniye; mevcut pandas fillna FutureWarning. +- Sınır: FeatureEngineer export_state/from_state, tüm zincirin persistence + kapısı ve örnek script SM-07'de. Distributed model inference, MLflow ve + Databricks/Connect entegrasyon doğrulaması henüz yok. + +## SM-07 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `802f60d3`; bu kayıt SM-07 çalışma ağacına aittir. +- Public `FeatureEngineer.export_state() -> bytes` ve `from_state(...)`: + sıralı step isimleri/config'leri ve mevcut node codec envelope'ları tek + versioned JSON paketinde. İlk destek mean/constant imputer ve StandardScaler. + Öğrenilmiş kolon seçimi explicit hale gelir; auto-selection yeniden çalışmaz. + Session/keys/target runtime'dan yeniden alınır; core dosya I/O yapmaz. +- `core/portable_pipeline.py` toplam wire bütçesini parse öncesinde kontrol eder; + step sırası, config ve nested state checksum kapsamındadır. Bilinmeyen + node/version, custom applier, bozuk veya eksik fit state'i açıkça reddedilir. + `_feature_state.py` yalnız bilinen applier'ları kurar; Spark key/target ile + öğrenilmiş feature çakışmasını execution başlamadan reddeder. +- Node ve pipeline wire JSON compact UTF-8; semantic checksum'ın mevcut ASCII + canonical biçimi değişmedi. Unicode kolonlarda re-encoding kaynaklı yanlış + bütçe aşımı giderildi; escaped surrogate isimler eski codec ile uyumlu. +- Başarılı tuning'in adopted FE state'i export edilebilir. Başarısız local/model + refit export'u kapatır; boş pipeline da buna dahildir. Spark'ın başarısız refit'i + önceki başarılı state'i koruma sözleşmesi değişmedi. Legacy pickle ve pipeline + fingerprint hesapları mevcut regresyonlarla korundu. +- `tests/spark/test_feature_pipeline.py`: gerçek üç fit × üç apply engine, + dosyada JSON round-trip, repartition 1/2/7, ters girdi ve tekrar transform. + Key bazlı sonuçlar aynı; train-only learned state değişmez. 10.000 satırlı + imputer→scaler testinde unbounded collect ve local conversion yasak; yalnız + bounded aggregate/validation satırları driver'a döner. Fixture dosya içindedir. +- Bağımsız review Unicode byte limiti ve tuning fitted-state aktarımını buldu. + Gerçek Spark Unicode testi düzeltmeden önce failed, sonra passed. Tuning/model + × boş/scaler dört regresyonu önce failed, sonra passed; exception sonrası boş + pipeline'ın yanlış export edilmesi de düzeltildi. Son review recheck temiz. +- Dar local state/codec/lifecycle koşusu: **101 passed, 28 warnings**, 1.75 saniye. + Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm07-base-full` + → **9969 passed, 223 skipped, 1077 warnings**, 192.35 saniye. Base ortamda + PySpark yok; runtime skip'leri gerçek Spark lane'inden ayrı değerlendirilir. +- `skyulf-core/examples/spark_feature_engineering.py --state-path + .cache/sm07-example-features.json` gerçek PySpark 4.0.3/Java 17 ile çalıştı: + **1949 byte**, üç keyed feature beklenen ±sqrt(1.5)/0; dosya save/load ve + JVM kapanışı başarılı. Rehber kullanım, frozen columns ve runtime sınırlarını açıklar. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm07-spark-full` + → **261 passed, 2 warnings**, 345.28 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Ruff/format, tam repo ty ve `mkdocs build --strict` geçti. Rehberde session + kurulumundan sonraki dokuz Python snippet'i aynı gerçek session'da çalıştı: + `.venv-spark/Scripts/python.exe -m pytest .cache/sm07_docs/test_spark_examples.py + -q --tb=short -o addopts= -p no:cacheprovider --basetemp .cache/sm07-doc-examples` + → **1 passed, 1 warning**, 38.00 saniye; mevcut pandas fillna FutureWarning. +- Sınır: G1 feature engineering içindir; model bundle/inference, MLflow, + Databricks/Connect ve endpoint/template doğrulaması değildir. Sonraki görev SM-08. + +## SM-08 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `7099733c`; bu kayıt SM-08 çalışma ağacına aittir. +- `skyulf/inference/` public API: `build_bundle`, `save_bundle`, `load_bundle`, + `predict_local`, immutable `InferenceBundle`. Metadata ve payload bytes ayrı; + `raw` input'ta FE bir kez uygulanır, `features` doğrudan model tahminidir. + pandas/Polars girdisi; çıktı pandas prediction/probability kolonlarıdır. +- `SkyulfPipeline.fit` metadata-only `_inference_schemas` kaydeder: target hariç + raw input ve gerçek model training feature sırası/dtype'ları. Başarısız refit + temizler; raw frame tutulmaz. NumPy bridge'in kaybettiği kolon adları tahminle + doldurulmaz. Schema capture 31 gerçek frame/tuple/split/wrapper/tuning testiyle + korundu; mevcut pickle ve fingerprint davranışı değişmedi. +- Katı manifest: stage, input/model/output schema, class/probability sırası, + positive label, tuning ve explicit pipeline threshold provenance, sabit + dependency listesi ve digest'ler. pandas/Polars Boolean/bool eşleştirmesi açık. + Eksik/ekstra/tekrarlı/sırası yanlış veya dtype'ı farklı feature'lar reddedilir. +- Kayıt üç sabit isimli dosyadır: manifest.json, features.json, model.pkl. + Var olan hedefe yazılmaz. FE+manifest state bütçesi ile model wire bütçesi ayrı; + protokol-5 PickleBuffer byte sayımı ve explicit FE limitinin tüm çağrılara + aktarımı test edildi. Kaynak pipeline'ın sonraki mutasyonu paketi değiştirmez. +- Semantic digest pickle protokolüne bağlı değildir; ayrıca model/FE wire + checksum kontrolü yapılır. Pickle yalnız güvenilir üreticiden yüklenir. + Python major/minor ve skyulf-core/sklearn/NumPy/SciPy sürümleri yüklemeden + önce doğrulanır. pandas/Polars sürümleri provenance olarak kaydedilir. +- Ruling: local giriş yalnız feature kolonlarını kabul eder; id gibi ekstra + kolonlar otomatik elenmez. SM-09 runner key'leri model girişinden açıkça ayırır. + Fixture seed=17, iki farklı ölçekli x/z kolonu ve held-out satırlar içerir; + test dosyasında tutulur. Bu, plandaki tek x/id örneğine göre kolon sırası + hatasını da yakalar; SM-09 shared fixture'a ihtiyaç duyduğunda taşınabilir. +- Ruling: mevcut `core/serialization.py` provider'ı ve eski backend okuyucu + değiştirilmedi. Standalone adapter `SkyulfPipeline.load` → `build_bundle`; + schema bilgisi olmayan eski pickle yeniden fit gerektirir. Backend dict + doğrudan reddedilir, adapter SM-18'de. İlk FE desteği SM-07'nin node'ları; + split node yerine explicit SplitDataset ile training partitions verilebilir. +- Bağımsız review Polars Boolean alias'ını, 8 MiB üstü FE için custom budget + aktarımını ve büyük estimator protocol-5 PickleBuffer serialization hatasını + yeniden üretti. Red regresyonlardan sonra düzeltildi. Re-review: gerçek + 144 KB KNN bundle ve 8.39 MB FE / 16 MiB bütçe ile pandas+Polars inference geçti; + açık önemli bulgu kalmadı. KNN gibi modeller kendi state'lerinde örnek tutabilir; + schema capture'ın veri tutmaması estimator'ın bu davranışını değiştirmez. +- Dar testler: **76 passed, 2 skipped, 21 warnings**, 4.46 saniye. İki skip + Spark-local giriş reddi vakasıdır; gerçek Spark lane'inde ayrıca çalışır. +- `skyulf-core/examples/inference_bundle.py --bundle-dir .cache/sm08-example-model` + çalıştı: kayıt/yükleme sonrası **[40.0, 20.0]**, raw/features parity ve aynı + semantic digest. Ayrı base-process import kontrolü PySpark/MLflow yüklemedi. +- Yeni `docs/user_guide/inference_bundles.md`, Spark rehberi linki ve nav kaydı. + Rehberin Python örneği gerçek base ortamında **1 passed**, 2.08 saniye; + `mkdocs build --strict` başarılı. Ruff/format ve tam repo ty geçti. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm08-core-full` + → **10045 passed, 225 skipped, 1097 warnings**, 193.33 saniye. Base ortamda + PySpark yok; yeni gerçek Spark input-ret testleri burada iki skip'tir. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py + skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --tb=short + -o addopts= -p no:cacheprovider --basetemp .cache/sm08-spark-full` + → **339 passed, 2 warnings**, 340.64 saniye. PySpark 4.0.3 / Java 17; + Windows JVM child-process cleanup başarılı. Warning'ler mevcut Split alias'ına ait. +- Sınır: bu görev local paketleme/inference içindir. Spark worker model runner + SM-09, ikinci Python FE yolu SM-10, dağıtık classification kapısı SM-11'dir. + MLflow, Databricks/Connect, endpoint ve template doğrulaması henüz yok. + +## SM-09 — 2026-09-21 tamamlanma kaydı + +- Başlangıç commit'i `81745a7b`; bu kayıt SM-09 çalışma ağacına aittir. +- `inference/spark.py` ve public `predict_spark`: raw girdiye native FE, + ardından `mapInPandas` iterator'larında Python regression tahmini. Model + iterator başına bir kez yüklenir; yalnız feature'lar ve key'ler worker'a gider. + Ortak model tahmin helper'ı local davranışı tekrar kullanır. Session, frame + veya bağlantı worker closure'a girmez; pandas dönüşümü worker batch'indedir. +- `tests/spark/test_native_features_inference.py`; SM-08'in fitted pipeline ve + raw-frame fixture'ları ortak conftest'e taşındı. pandas/Polars eğitim, bundle + kayıt/yükleme, repartition 1/3, Arrow limit 1/5, eksik değerler, boş veri ve + partition'lar, birleşik key'ler, `2**53` üstü identity, worker projection, + bounded driver validation, iterator model yükleme ve chunk sınırı doğrulandı. +- Ruling: native model schema önce yalnız Spark ifadeleri oluşturularak + incelenir; sonra mevcut FE key/preservation kontrolleri çalışır. Preview veri + action'ı içermez, öğrenilmiş kuralları tekrar fit etmez. Local integer imputer + çıktısı ile Spark double promotion uyuşmazlığı artık action'dan önce hata verir. +- Ruling: nullable integer/boolean model feature schema'ları erken reddedilir; + Arrow null batch dönüşümü hassasiyet kaybetmeden çözülene kadar destek ilan + edilmez. Non-nullable integer model feature ve büyük integer key gerçek action + ile geçti. Key'lerin nullable schema metadata'sı ayrı değer kontrolüyle korunur. + Broader nullable transport SM-11'e kayıtlıdır. +- Ruling: raw model input kolonlarının kendi sırası/dtype'ları korunmalı; + extra kolonlar projection ile elenir. Key'ler integer/string/boolean'dır; + feature/output isimleriyle çakışamaz. Incoming prediction kolonu da reddedilir. + `FrameSpec.target` boş olmalıdır. Raw regression dışındaki stage/task/mode ve + streaming açık ret verir. `python_batch_rows` model çağrısını sınırlar; + Arrow transport konfigürasyonuna veya kullanıcının Spark session'ına yazılmaz. +- TDD red: eksik public API; streaming, native dtype ve nullable transport + girdilerinin doğrulamadan önce Spark action'a ulaşması ayrı ayrı yeniden + üretildi. Dar final test: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark/test_native_features_inference.py + skyulf-core/tests/spark/test_inference_bundle.py -q -o addopts= + -p no:cacheprovider --basetemp .cache/sm09-runner-final` + → **101 passed**, 110.42 saniye; owned JVM temiz kapandı. +- Bağımsız review iki schema/Arrow bulgusunu doğruladı; düzeltmelerin ve red + regresyonların yeniden incelemesinde açık yüksek/orta bulgu kalmadı. +- Eski backend artifact akışı ayrıca doğrulandı: `.venv/Scripts/python.exe -m + pytest tests/integration/test_bundle_preprocessing_integrity.py + tests/integration/test_full_inference_pipeline.py -q --tb=short -o addopts= + -p no:cacheprovider --basetemp .cache/sm09-legacy` + → **22 passed, 30 warnings**, 7.80 saniye. Backend kaynakları değiştirilmedi; + full FE/model joblib reader korunuyor, yeni bundle adapter'ı SM-18'de. +- Tam core: `HF_HUB_OFFLINE=1 .venv/Scripts/python.exe -m pytest skyulf-core/tests + -q --tb=short --disable-warnings -o addopts= -p no:cacheprovider + --basetemp .cache/sm09-core-full` + → **10050 passed, 274 skipped, 1097 warnings**, 194.81 saniye. Base ortamda + PySpark yok; gerçek Spark testleri ayrı lane'de doğrulanır. +- Ruff/format ve tam repo ty başarılı. Bundle/Spark rehberleri mevcut artifact + davranışını, yeni runner'ı, dtype ve sürüm sınırlarını açıklıyor. + `mkdocs build --strict` başarılı. +- Tam Spark: `JAVA_HOME=.cache/spark-jdk/jdk-17.0.20.1+1`, + `SKYULF_REQUIRE_SPARK=1`, `.venv-spark/Scripts/python.exe -m pytest + skyulf-core/tests/spark skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py + skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --tb=short + -o addopts= -p no:cacheprovider --basetemp .cache/sm09-spark-full` + → **393 passed, 2 warnings**, 418.45 saniye. PySpark 4.0.3 / Java 17; + JVM temiz kapandı. Warning'ler mevcut Split alias'ına ait. +- Spark runtime: Python 3.12.10, skyulf-core 0.9.0, pandas 2.3.2, + Polars 1.44.2, sklearn 1.9.1, NumPy 1.26.4, SciPy 1.17.1, Arrow 24.0.0. +- Rehberin iki Python bloğu `.venv-spark/Scripts/python.exe + .cache/sm09_docs_example.py` ile aynı ortamda çalıştırıldı: local kayıt/yükleme + ve key'li Spark sonucu **[40.0, 20.0]**, başarılı assert'ler ve temiz JVM kapanışı. +- Sınır: bu G2a / native FE + regression teslimatıdır. SM-10 Python FE worker + modu, SM-11 classification/worker wheel/ölçek kapısıdır. Databricks/Connect, + MLflow/UC, endpoint ve template doğrulaması yoktur. Sıradaki görev SM-10. + +## SM-11 — 2026-09-22 final validation record + +- Starting point: `a930f8a5`; implementation commits: `04dbe303` and + corrective `7cdd622c`. The earlier DONE label was reopened during review and + is now restored only after the corrective evidence below. +- `predict_spark` now accepts raw regression and classification bundles in both + `native_features` and `python_pipeline` modes. The output schema maps + manifest label dtypes to Spark types and keeps probability columns in the + estimator class order. Saved tuning and explicit pipeline threshold rules + reuse the local `_predict_features` contract. +- Added `tests/spark/test_prediction_contract.py` for string binary labels, + integer multiclass labels, probability ordering, saved thresholds, two + partition layouts and two Arrow batch limits. Added + `tests/spark/test_worker_isolation.py` to verify one model load per iterator + and bounded model calls. The former classification rejection regression test + now asserts the supported output contract. +- Added `skyulf-core/examples/spark_batch_inference.py`, which runs the same + classification bundle through both Spark modes. The example sets the current + interpreter as the Python worker on Windows when no worker override exists. +- Corrective focused verification: + `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp + .tmp-sm11-regression skyulf-core/tests/spark/test_native_features_inference.py + skyulf-core/tests/spark/test_python_pipeline_inference.py + skyulf-core/tests/spark/test_prediction_contract.py + skyulf-core/tests/spark/test_worker_isolation.py + skyulf-core/tests/spark/test_inference_bundle.py -q --disable-warnings + --maxfail=1` → **63 passed**. JVM cleanup prints the + existing Windows `ERROR: Access denied` after a successful exit. +- Full Spark gate after the corrective transport guard: + `.venv-spark/Scripts/python.exe -m pytest -o addopts='' --basetemp + .tmp-sm11-spark-final skyulf-core/tests/spark + skyulf-core/tests/unit/test_execution_capabilities.py + skyulf-core/tests/unit/test_feature_state.py + skyulf-core/tests/unit/test_pipeline_inference_schema.py -q --disable-warnings + --maxfail=1` → **418 passed, 2 warnings**, 525.50 seconds. The warnings are + existing; Windows prints the cleanup access-denied line after exit 0. +- Both example commands completed with exit code 0 and printed matching + `prediction`, `probability_0` and `probability_1` results. Ruff check and + format passed for all changed Python files. +- Nullable integer/boolean model-feature transport remains rejected because + Arrow can widen values with nulls. Worker wheel isolation, scale/RSS + measurements, MLflow, Databricks, endpoints and templates remain later work. +- Corrective preflight rejects nullable integral/boolean raw inputs in + `python_pipeline` before key validation. Independent estimator class/probability + assertions and a non-default threshold decision assertion are covered. A + wheel subprocess smoke imported `skyulf.inference.spark` from the built 0.9.0 + wheel. Local scale measurements recorded 10k/2 partitions at 3.929s and + 50k/8 partitions at 8.089s with driver peak RSS 246.2/246.8 MB and child + process peak RSS 887.2/922.7 MB. These results are evidence, not a production + performance guarantee. +- Next task: SM-12 optional MLflow tracking, with tracking disabled remaining a + valid local/Spark workflow. diff --git a/initiatives/spark_and_mlflow/README.md b/initiatives/spark_and_mlflow/README.md index 6c68b7fc8..a9b2bff17 100644 --- a/initiatives/spark_and_mlflow/README.md +++ b/initiatives/spark_and_mlflow/README.md @@ -1,68 +1,66 @@ -# Spark ve MLflow initiative +# Spark and MLflow initiative -Tarih: 2026-09-21. Durum: **SM-00–SM-09 tamamlandı; sıradaki görev SM-10.** -Hedef sürüm [0.9.0 — Unreleased](../../changelog/0.9.x.md). -Geliştirme sürümü 0.9.0; yayın yapılmadı. [Güncel baseline](BASELINE.md). +Updated: 2026-09-22. **SM-00–SM-16 are complete for their documented scopes; +SM-26 is next.** Target: [0.9.0 — Unreleased](../../changelog/0.9.x.md). +The first new deliverable is a pandas/Polars Databricks Bundle for bounded +training and monthly local prediction. Spark can handle UC table I/O, while +Spark FE/model execution becomes a later Bundle option. Read the current +[queue](OPEN_QUEUE.md) for the authoritative status and order. -Amaç: Skyulf Core'un mevcut pandas/Polars davranışını koruyarak gerçek Spark -feature engineering, dağıtık Python inference ve opsiyonel MLflow/Unity Catalog -entegrasyonu sağlamak. Aylık batch teslimatından sonra endpoint'ler, en son -template/Databricks Bundle gelir. +## Reading order -## Okuma ve uygulama sırası +1. [OPEN_QUEUE.md](OPEN_QUEUE.md): current task status and order. +2. [HANDOFF.md](HANDOFF.md): verified baseline and execution boundaries. +3. [04-databricks-integration-plan.md](04-databricks-integration-plan.md): local-first adapters. +4. [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md): separate Bundle plan and two-month UC table rehearsal. +5. [01-core-spark-plan.md](01-core-spark-plan.md), + [02-inference-plan.md](02-inference-plan.md) and + [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md): earlier task detail. +6. [ARCHITECTURE.md](ARCHITECTURE.md) and [VALIDATION.md](VALIDATION.md): contracts and gates. -1. [OPEN_QUEUE.md](OPEN_QUEUE.md): kısa, sıralı görev kuyruğu ve sonraki iş. -2. [ARCHITECTURE.md](ARCHITECTURE.md): kapsam, değişmez kurallar ve dosya sınırları. -3. [01-core-spark-plan.md](01-core-spark-plan.md): SM-00–SM-07, engine ve fit/apply. -4. [02-inference-plan.md](02-inference-plan.md): SM-08–SM-11, iki inference yolu. -5. [03-mlflow-batch-delivery-plan.md](03-mlflow-batch-delivery-plan.md): - SM-12–SM-20, MLflow, registry, batch ve son teslimatlar. -6. [VALIDATION.md](VALIDATION.md): test matrisi, ortamlar ve tamamlanma kanıtı. +Historical research: -Tarihsel araştırma: +- [Readiness review](reports/2026-09-21-spark-databricks-readiness.md) +- [Source, node and test inventory](reports/2026-09-21-spark-core-inventory.md) -- [Hazırlık incelemesi](reports/2026-09-21-spark-databricks-readiness.md) -- [Kaynak/node/test envanteri](reports/2026-09-21-spark-core-inventory.md) +These reports describe their inspected commits, not the current branch. +The original planning HEAD was `2397c11648c27645a4ee332412a503c394c1c2f2`; +branch `090` and local master later advanced past the 0.8.24 merge point +`97536eae20e5422220f9824bc591ceb05576ee50`. That restored the current +Polars/ContextVar engine behavior, so the older pandas-default observation is +historical. SM-00 recorded a 231-test baseline and two Spark smoke tests. +The user guide is [Spark](../../docs/user_guide/spark.md). This initiative +does not change the global default engine. -Bu iki rapor `initiatives/reports/` içinden taşındı. Rapordaki sayılar ve test -sonuçları raporun incelediği commit'e aittir; güncel dalın sonucu değildir. -Plan hazırlanırken HEAD `2397c11648c27645a4ee332412a503c394c1c2f2` idi. -Özellikle güncel `engines/registry.py` pandas varsayılanı ve sınıf değişkeni -kullanıyor; eski rapordaki Polars/ContextVar ifadesi güncel varsayım yapılmamalı. -SM-00 mevcut davranışı yeniden kaydeder. Bu initiative global varsayılan engine'i -değiştirmeyi gerektirmez; ileride wizard önerisi ayrı bir kullanıcı tercihidir. +## Completed foundation and next deliverable -Güncelleme: 090 ve yerel master 0.8.24 merge noktası -`97536eae20e5422220f9824bc591ceb05576ee50` üzerine ilerletildi. Yukarıdaki -pandas-default notu önceki checkout'u anlatır; güncel kaynak Polars/ContextVar -davranışını geri içeriyor. Güncel tekrar: 231 baseline + 2 Spark smoke geçti. -Kullanıcı belgeleri: [Spark rehberi](../../docs/user_guide/spark.md). +The initial SimpleImputer/StandardScaler Spark paths, compatible Python-worker +inference, MLflow packaging/registry and a selected serverless Delta batch path +have documented evidence through SM-16. This does not cover every node or model. +The next deliverable strengthens fitted pandas/Polars packaging and uses it in +a generated local-engine Bundle. Its monthly output is tested across two +consecutive months and source versions with one pinned model version. The +second run scores only the new month. See the separate SM-20 plan. -## İlk teslimat +## Working rules -Kolon seçimi → SimpleImputer(mean/constant) → StandardScaler → kayıt/yükleme → -Spark apply. Sonra aynı feature'larla mevcut bir Python modelinin Spark worker -tahmini. Spark verisini driver'a indirmek hiçbir aşamanın gizli çözümü değildir. -Median/quantile, kategorik state ve zaman pencereleri ilk teslimattan ayrı tutulur. +- The next task is **SM-26**. Complete each queue dependency before its consumer. +- For each task, show a failing test, implement the narrow change and record + the passing gate. New tests have a docstring and a real assertion. +- Recheck source paths before implementation; planned APIs are not current APIs. +- A written file, passing local tests and a successful Databricks run are + separate claims. A DONE task records commands, results, runtime and commit + or working-tree state. +- Commit and push are separate actions. A requested commit needs fresh checks + and DCO sign-off. +- Core/SDK and the local UC output precede SM-20a. Backend/Canvas remains + parked SM-18; endpoints and streaming are not first-Bundle dependencies. -## Çalışma kuralları +## Related initiatives -- Sonraki görev **SM-10**. Bir sonraki satıra geçmeden önce bağımlılıklarını bitir. -- Her görevde test → beklenen başarısızlık → dar uygulama → test/gate kanıtı. -- Yeni testler docstring ve gerçek assertion içerir. Uygulama sırasında kaynak - yollarını yeniden doğrula; planlanan API'ler bugün mevcut API gibi kullanılmaz. -- Dosya yazılmış olması, testlerin geçmesi ve Databricks'te çalışması ayrı durumlar. -- Queue'da DONE için komut, sonuç, runtime ve commit/çalışma ağacı kaydı gerekir. -- Commit/push bu planın otomatik adımı değildir; yalnız kullanıcı istediğinde - güncel kontrollerle DCO commit hazırlanır. -- Önce core/SDK; backend/Canvas değişikliği SM-18. Endpoint SM-19, - template SM-20. Streaming ilk release'in zorunlu koşulu değildir. - -## Diğer initiative'lerle ilişki - -[Önceki MLflow planı](../analysis/skyulf-core-mlflow-integration-plan.md) -tarihsel girdidir. Bu çalışma için sıra ve karar kaynağı burasıdır: global fit -callback veya backend job'a zorunlu bağlı tracking yerine açık run kapsamı; -ilk teslimatta UI yok. Joblib/ONNX, Ray ve deep-learning planları bu çalışmanın -önkoşulu değildir. Paylaşılan artifact/pipeline dosyalarındaki eşzamanlı -değişiklikler her görev başında kontrol edilir. +Earlier MLflow proposals are historical input. This initiative uses explicit +run scopes instead of +global fit callbacks or mandatory backend-job tracking. The first Bundle has +no Canvas work. Joblib/ONNX, Ray and deep-learning initiatives are not its +prerequisites. Check shared artifact and pipeline files for concurrent changes +before each implementation task. diff --git a/initiatives/spark_and_mlflow/diagrams/local-engine-bundle.svg b/initiatives/spark_and_mlflow/diagrams/local-engine-bundle.svg new file mode 100644 index 000000000..c0178b5af --- /dev/null +++ b/initiatives/spark_and_mlflow/diagrams/local-engine-bundle.svg @@ -0,0 +1 @@ +

Databricks batch job: bounded local engine

Databricks training job: bounded local engine

Local project and deployment

Skyulf configuration
Databricks runtime, pandas or Polars engine

Generate local-engine Bundle project

databricks.yml, train and batch jobs,
Python entry points

Validate and deploy Bundle

Pinned training data

Train job

pandas or Polars: fit FE
and train Python model

MLflow run and fitted pipeline artifact

UC registered model: concrete version

UC scoring data at pinned snapshot

Batch inference job

pandas or Polars: apply FE
and predict

Prediction rows with source
and model provenance

Spark bridge: UC table I/O
with explicit output schema

UC Delta prediction table

diff --git a/initiatives/spark_and_mlflow/reports/2026-09-22-spark-databricks-gap-review.md b/initiatives/spark_and_mlflow/reports/2026-09-22-spark-databricks-gap-review.md new file mode 100644 index 000000000..8dc1b6673 --- /dev/null +++ b/initiatives/spark_and_mlflow/reports/2026-09-22-spark-databricks-gap-review.md @@ -0,0 +1,168 @@ +# Spark and Databricks gaps after SM-16 + +Date: 2026-09-22. Inspected baseline: `63dd3e21`, branch `090`. +This is a source review and roadmap update, not new runtime validation. + +**Historical planning snapshot:** the user subsequently parked broad SM-17 and +selected the Databricks integration lane first. The source findings below remain +useful; priority/status statements are superseded by +[04-databricks-integration-plan.md](../04-databricks-integration-plan.md) and the +current queue. No missing node/model support was implemented by changing priority. + +## User decisions + +- Do not start SM-15L today. It is deferred until explicitly resumed. +- Prioritize completion of existing node and model coverage through SM-17. +- Park SM-18 and all later implementation, including endpoints and templates. +- Account for every existing registered node and configuration. Merely documenting + an unsupported operation does not satisfy the requested completion scope. + Keep the owning task open unless implemented or explicitly deferred by the user. +- Do not replace a local algorithm with a different Spark algorithm silently. + Native distributed fit, native apply, worker Python inference and explicit + bounded local execution are distinct contracts. + +## What the repository actually provides + +An AST scan of literal `NodeRegistry.register` calls across `skyulf-core/skyulf` +found **100 source registration IDs: 62 preprocessing and 38 modeling**. This +includes aliases and optional-dependency registrations; it is not 100 independent +algorithms or a claim that every registration loads in the base environment. +The complete ID inventory and task ownership are in [NODE_SUPPORT.md](../NODE_SUPPORT.md). + +Only `SimpleImputer` and `StandardScaler` currently declare Spark fit/apply +capabilities. The imputer declaration covers mean/constant; the scaler covers +its mean/std flag combinations. Native FE and Python-worker FE inference do not +provide an automatic fallback for the other nodes. Their artifact/state and +execution contracts must be implemented and tested explicitly. + +The new bundle's `inference/_model.py::validate_model` requires a standalone +sklearn estimator from a `sklearn.*` module, regression/classification semantics, +single output and classifier `predict_proba`. Custom prediction appliers require +an adapter. Consequently, existing local XGBoost/LightGBM registrations, clustering +and all special/composite model paths must be audited separately; none is made +portable merely by using a pickle. Native Spark model training and persistence +are additional work, not an existing consequence of distributed prediction. + +SM-16 verified one selected Databricks serverless regression workflow: Polars +training, registered bundle loading, both Spark prediction modes, monthly Delta +replacement/replay, shared admission and real access denial. It did not certify +all 100 registrations, Spark training, classification on Databricks, HTTP serving, +online feature lookup or SQL endpoint calls. + +Code entry points reviewed: + +- `skyulf-core/skyulf/core/capabilities.py` and `registry.py`. +- `preprocessing/imputation/simple.py`, `scaling/standard.py` and the registration inventory. +- `inference/bundle.py`, `_model.py`, `spark.py` and `integrations/mlflow/model.py`. +- `integrations/databricks/{batch,delta,delta_admission,_contracts}.py`. + +## Changes to SM-17 + +| Task | Deliverable and acceptance boundary | +| --- | --- | +| SM-17-00 | Complete per-ID/per-configuration inventory; fit/apply/codec/inference/runtime tests tracked separately; aliases linked, optional packages counted | +| SM-17a | Casting, cleaning, date/math/interaction/polynomial and basic scaling; native expressions and fitted-state parity | +| SM-17b | Remaining imputation strategies, encoding, bins/ranges and robust/quantile statistics; exact/approximate policy, category order, unseen/null behavior | +| SM-17c | Selection, general/power transforms and outliers; selected-column apply separated from distributed fit; row filtering preserves X/y/key alignment | +| SM-17d | Group/window/history and target/WOE OOF contracts; train-only state, deterministic ordering/ties, partition-boundary and leakage tests | +| SM-17e | Tokenization/vectorization/embedding and geo; vocabulary/hash/normalization parity, sparse/vector schemas, optional dependency and worker packaging | +| SM-17f | Splits, resampling and inspection; deterministic membership, training-only row changes, bounded previews and distributed aggregate profiles | +| SM-17g | Current-model inference coverage, including XGBoost/LightGBM, ensembles/calibration, non-probabilistic classifiers, clustering and explicit output contracts; save/load/registry/worker parity | +| SM-17h | Native distributed model fit and transform: explicit Spark ML backend, feature-vector metadata, label/probability mapping, model persistence and MLflow flavor; no implicit sklearn-to-Spark substitution | +| SM-17i | Evaluation, CV/tuning, thresholds and explainability/SHAP contracts for model backends; distinguish parallel trials from distributed fit; explicit bounded execution and metric collection | +| SM-17j | SDK/config usability and preflight: independent platform/FE/model/sink/tracking/registry choices, selected-version bundle loader, actionable unsupported/runtime errors and examples | +| SM-17k | Complete family gates, all-ID coverage guard, fit/save/load/predict integration and selected Databricks runtime checks; no open requested coverage silently converted to DONE | + +For native training, prioritize linear/logistic, tree/forest/GBT and clustering +families after mapping actual local semantics. Other model IDs retain individual +tasks. Ridge/lasso parameterizations, SVC/KNN, boosting libraries, ensembles and +resampling do not automatically have equivalent Spark implementations. Each +needs an explicit backend/adapter decision and evidence; equivalence is not +established by matching class names or random seeds. Distributed library training +such as XGBoost is distinct from Python-worker prediction of a locally fitted model. + +Spark-native models may require a different artifact kind from the current +pickle-backed Python bundle. Version that contract deliberately, preserve old +bundles, and do not require a Spark session in a local HTTP serving process. + +## Non-template patterns reviewed in the supplied example + +Reference root: +`C:/Users/Murat/Desktop/codes-main (1)/codes-main/dbml-mlops-template`. +Paths below are relative to `template/{{.project_name}}/{{.project_name}}_classification`. +The review covered the relevant Python services and structure; it did not execute +the example, audit every notebook/test or establish the example's production readiness. +No source was copied into Skyulf and no resources were deployed. + +| Reference code | Useful pattern | Skyulf placement / state | +| --- | --- | --- | +| `common/config_service.py.tmpl` | Central config and per-developer resource scope | SM-17j SDK configuration; resource generation remains parked SM-20 | +| `src/training/services/{model_factory,training_service}.py.tmpl` | Model family interface, tuning and evaluation separation | SM-17g/h/i; reuse existing Skyulf modeling abstractions | +| `src/training/services/models/random_forest_classifier_service.py.tmpl` | Explicit sklearn/pandas model service | Confirms Databricks placement need not imply Spark-native fit | +| `common/services/feature_store_service.py.tmpl`, `src/training/services/data_preparation_service.py.tmpl` | UC feature tables, training-set lookups, timestamp keys, optional online publication | Parked SM-21; point-in-time joins and online freshness need their own contracts | +| `src/training/services/registry_service.py.tmpl`, `src/validation/services/model_validation.py.tmpl` | Validation against a champion, version tags and explicit deployment lifecycle | Parked SM-22; retain pinned identities and separate evaluation from promotion | +| `src/inference/services/inference_service.py.tmpl` | Feature Store `score_batch` or MLflow Spark UDF scoring | Optional adapters, not a replacement for Skyulf's existing native FE / worker paths | +| `src/deployment/services/endpoint_service.py.tmpl` | Endpoint configuration, ACLs, readiness, traffic routes and inference logging | Parked SM-19a/d; authentication via supported credential providers, bounded retries | +| `src/monitoring/services/data_quality_service.py.tmpl` | Monitoring setup/refresh, data quality and drift integration | Parked SM-23; reuse Skyulf metrics, keep platform provisioning optional | +| `tests/integration/serving_endpoint_test.py.tmpl`, `run_serving_endpoint_locust_test.py.tmpl` | Real endpoint contract and load tests | Parked SM-19; local pyfunc loading is not a serving-endpoint test | + +Adopt concepts, not assumptions: the example's binary classification code uses +probability position 1 and an integer threshold label. Skyulf must preserve its +manifest class order, original labels, multiclass outputs and saved thresholds. +Likewise `randomSplit` does not establish cross-engine row-membership parity; +unbounded local conversions or model loads must not bypass Skyulf resource limits. +The example's automatic first-champion promotion is not a default for Skyulf. + +## Batch, live and SQL access + +| Access path | Current state | Remaining work | +| --- | --- | --- | +| Local Python prediction | Implemented for the current bundle contract, with pandas/Polars input | Broader node/model coverage in SM-17 | +| Distributed Spark prediction | Native FE + Python model, or worker Python FE + model | Broader coverage and native Spark models in SM-17 | +| Scheduled/monthly Delta batch | Spark runner and retry/publication guards implemented; schedule caller-owned | SM-15L deferred; orchestration conveniences separate from correctness | +| Existing Skyulf HTTP deployment | Existing backend path uses legacy artifacts | Bridge and compatibility in parked SM-18; not proof of Databricks endpoint support | +| Databricks live HTTP serving | MLflow pyfunc packaging exists; endpoint integration not delivered | Parked SM-19a: create/update/readiness, model dependencies, query ACLs, schema/parity, timeout/error behavior | +| SQL `ai_query` | No Skyulf invocation adapter or live validation yet | Parked SM-19b: invoke the existing serving endpoint, named struct/signature, return schema, CAN QUERY, row errors and capacity | +| Continuous/streaming inference | Not provided by the batch runner | Parked optional SM-19c: checkpoint/state/watermark, model updates and idempotency | + +`ai_query` is an invocation surface for an existing Model Serving endpoint, not +a third model-training engine or necessarily a separate endpoint deployment. +SQL endpoint calls also do not inherit the direct Delta runner's idempotent +publication guarantees automatically. + +Live serving can reuse the Python model + fitted FE bundle for compatible +row-local operations. Window/history-dependent FE needs caller-supplied context +or an explicit lookup design; a one-row REST request cannot reconstruct a whole +Spark partition. Spark-trained model serving needs an independently validated +serving artifact/runtime; Spark batch support alone is insufficient. + +## Usability recommendation + +Today the API is usable by an engineer, but it is still several explicit steps: +resolve a registry version, load the bundle, construct the period/snapshot spec, +select admission and execute. The SM-16 probe's uploads, grants and wheel checks +were validation work, not the intended everyday user workflow. + +SM-17j should provide one documented config-driven entry path and a preflight +report. Keep platform, FE engine, model backend, sink and tracking/registry +independent. Derive schema/feature order/model digest/code version when already +known, but retain explicit period, source snapshot, target version and alias +promotion choices. Give a minimal notebook example and an advanced customization +example. Do not create resources or start jobs implicitly during config validation. +Backend/Canvas controls and generated DAB files remain parked. + +## Verified platform references + +- [Databricks serverless environment 4](https://docs.databricks.com/aws/en/release-notes/serverless/environment-version/four) + supports `pyspark.ml` and `mlflow.spark`, with model-size and unsupported-model + limits. Do not preserve the outdated blanket assumption that serverless cannot + train Spark ML models; Skyulf still needs its own adapter and runtime tests. +- [Serverless limitations](https://docs.databricks.com/aws/en/compute/serverless/limitations): + Connect APIs, cache restrictions and bounded UDF memory affect implementation. +- [Custom model serving](https://docs.databricks.com/aws/en/machine-learning/model-serving/custom-models): + logging a compatible MLflow model is a prerequisite, not endpoint validation. +- [ai_query](https://docs.databricks.com/aws/en/sql/language-manual/functions/ai_query): + existing endpoint, compatible input schema, permissions and supported runtime. + +These references were checked on 2026-09-22. Runtime support must be rechecked +when implementing each adapter, including serverless versus classic compute. From 903c8c94b8002059cfd8a92acb53fb718ac739cc Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 10:37:44 +0300 Subject: [PATCH 31/85] feat(core): package fitted local pipelines with MLflow Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 + docs/user_guide/mlflow_models.md | 86 +++++++ .../04-databricks-integration-plan.md | 12 +- initiatives/spark_and_mlflow/HANDOFF.md | 38 ++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 34 ++- .../skyulf/inference/local_pipeline.py | 228 ++++++++++++++++ .../skyulf/integrations/mlflow/local_model.py | 159 ++++++++++++ .../skyulf/integrations/mlflow/model.py | 8 +- .../skyulf/integrations/mlflow/registry.py | 2 +- skyulf-core/skyulf/pipeline/_pipeline.py | 24 +- .../integrations/test_local_mlflow_model.py | 179 +++++++++++++ .../test_local_pipeline_artifact.py | 243 ++++++++++++++++++ 12 files changed, 986 insertions(+), 33 deletions(-) create mode 100644 skyulf-core/skyulf/inference/local_pipeline.py create mode 100644 skyulf-core/skyulf/integrations/mlflow/local_model.py create mode 100644 skyulf-core/tests/integrations/test_local_mlflow_model.py create mode 100644 skyulf-core/tests/integrations/test_local_pipeline_artifact.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index c27b336d9..6a1c36931 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -22,6 +22,12 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added +- Versioned local pandas/Polars pipeline artifact and MLflow pyfunc packaging + preserve fitted encoding/binning, model state, input order, class probabilities + and explicit tuned thresholds without refitting. The fit engine and exact + runtime requirements are recorded; registry resolution pins the local payload + digest. The declared execution scope is whole-frame local batch, with HTTP + row-local and Spark execution left for separate capability validation. - Shared Delta-table publish admission with conditional ownership updates, non-expiring claims and owner-only release. Real Delta tests cover independent sessions, concurrent claims and malformed authorities. Live serverless diff --git a/docs/user_guide/mlflow_models.md b/docs/user_guide/mlflow_models.md index fe46ce80c..bf66a951a 100644 --- a/docs/user_guide/mlflow_models.md +++ b/docs/user_guide/mlflow_models.md @@ -1,5 +1,91 @@ # MLflow model packaging (development) +## Fitted local pipelines (pandas or Polars) + +Use a **local pipeline artifact** when fitted preprocessing contains nodes that +the portable Spark bundle does not yet support, such as categorical encoding or +binning. This path saves the whole fitted pipeline, its recorded training engine, +raw and model-feature column order and dtypes, dependency versions, and a payload +checksum. It never fits the pipeline again. It is separate from the portable +Spark-capable `InferenceBundle` described below. + +```python +import mlflow +import pandas as pd + +from skyulf.inference.local_pipeline import ( + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, +) +from skyulf.integrations.mlflow import TrackingConfig, track_run +from skyulf.integrations.mlflow.local_model import log_local_model + +# fitted_pipeline was already trained on pandas or Polars data. +save_local_pipeline(fitted_pipeline, "artifacts/local-pipeline") +config = TrackingConfig( + enabled=True, + tracking_uri="sqlite:///mlflow.db", + experiment_name="customer-risk", +) +with track_run(config, run_name="fit-2026-09") as run: + model_uri = log_local_model( + "artifacts/local-pipeline", + run_id=run.run_id, + artifact_path="model", + tracking_uri=config.tracking_uri, + ) + +request_frame = pd.DataFrame({"age": [42.0], "income": [72000.0]}) +local = load_local_pipeline("artifacts/local-pipeline") +local_predictions = predict_local_pipeline(request_frame, local) +mlflow.set_tracking_uri(config.tracking_uri) +pyfunc_predictions = mlflow.pyfunc.load_model(model_uri).predict(request_frame) +``` + +The example columns must match the fitted pipeline's actual raw schema. Direct +local prediction accepts a pandas or Polars frame, validates column names, +order, and dtypes after converting to the **recorded fit engine**, and returns a +pandas DataFrame. A pandas input retains its index; a Polars input receives a +range index. The MLflow pyfunc boundary takes named pandas input; a pipeline +trained on Polars is explicitly converted back to Polars before applying its +learned preprocessing and model. MLflow may align named columns and cast values +according to its signature before that conversion. Check parity for each input +dtype you intend to serve, especially nullable or categorical dtypes. + +For classifiers, the output is `prediction` followed by +`probability_0`, `probability_1`, and so on in the saved model class order. Pass +`use_tuned_thresholds=True` to `save_local_pipeline` only when the fitted +pipeline has stored tuned thresholds and those decisions are intended for this +artifact; otherwise predictions use the estimator's default decision rule. +The current parity evidence is deliberately narrow: + +| Model family | Fitted engines | Verified preprocessing and outputs | +| --- | --- | --- | +| scikit-learn linear regression | pandas, Polars | One-hot encoding; custom binning followed by one-hot encoding; `prediction` | +| scikit-learn logistic regression | pandas, Polars | Class order, probabilities and explicit tuned decisions | + +Other model families, input dtypes, and context-dependent nodes need their own +parity checks before production use. The manifest records the concrete model +class so a later preflight can compare it with this evidence. + +This package declares `whole_frame_local` scope. It supports bounded local +batch inference, including inside a Databricks Python task with the recorded +dependencies installed. It does **not** certify independent HTTP row requests, +Spark worker partitions, or Spark-native feature engineering; those require +separate capability checks. It does not write Delta tables. The model URI points +to a concrete run artifact; registering or promoting an alias is a separate, +explicit step. + +Install `skyulf-core[mlflow]` in the loading environment. The MLflow model +records exact package requirements, including the Skyulf version; provide the +matching Skyulf wheel when the version is unpublished. The wheel is not embedded +in the model. Only load local pipeline artifacts from trusted producers: pickle +can execute code while loading, and the checksum detects corruption rather than +authenticating the source. + +## Portable inference bundles + Skyulf can package an existing `InferenceBundle` as an MLflow `pyfunc` model. The package contains the frozen feature state, estimator payload, manifest, and runtime requirements already produced by the bundle workflow. It does not fit diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md index 917052c66..d7ae3282e 100644 --- a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -87,23 +87,23 @@ Proposed areas: standalone pipeline persistence/prediction contracts, `skyulf-core/skyulf/integrations/mlflow/`, integration tests and the MLflow guide. Reuse existing fitted pipeline behavior; do not implement another FE engine. -- [ ] SM-26a: audit existing standalone save/load/predict semantics, fitted FE, +- [x] SM-26a: audit existing standalone save/load/predict semantics, fitted FE, local engine selection, schema/order, labels/probabilities/thresholds and model dependencies. Define a versioned local artifact contract distinct from the existing portable bundle; retain backward compatibility and trusted loading. -- [ ] SM-26b: package and restore the fitted local pipeline through MLflow pyfunc. +- [x] SM-26b: package and restore the fitted local pipeline through MLflow pyfunc. Preserve learned state without refit. An MLflow pandas input boundary must not silently switch an engine-sensitive Polars pipeline; any conversion is explicit and preserves dtypes, nulls, column order and output semantics. -- [ ] Include the required code/dependencies and a signature/input example. +- [x] Include the required code/dependencies and a signature/input example. Use the current registry/version-pinning services; do not promote aliases. -- [ ] SM-26c: prove original -> saved -> clean-environment MLflow predictions for +- [x] SM-26c: prove original -> saved -> clean-environment MLflow predictions for pandas and Polars. Include representative FE beyond mean imputation/scaling, such as encoding/binning, and explicitly track each advertised model family. -- [ ] Separate whole-frame local prediction eligibility, row-local HTTP eligibility +- [x] Separate whole-frame local prediction eligibility, row-local HTTP eligibility and Spark-worker/native eligibility. Context-dependent or row-changing FE does not become safe for requests or partitions merely because it can be serialized. -- [ ] Keep Python local batch prediction available without a Delta writer. No +- [x] Keep Python local batch prediction available without a Delta writer. No implicit Spark collection, new native Spark ports or backend artifact bridge. Acceptance: new local-package paths reproduce the original fitted pipeline under diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 79808fdb1..bf62ce862 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,24 +1,24 @@ -# Session handoff - 2026-09-22 +# Session handoff - 2026-09-23 SM-00 through SM-16 are complete for their documented scopes. The selected Databricks serverless regression workflow passed. Latest user direction: **Build a small-data pandas/Polars training and local batch path, then its first working Databricks Bundle. Spark may handle table I/O in that first path; Spark FE/model execution and its Bundle option follow. -SM-15L is reopened for monthly UC output; SM-18 remains parked. Start with -SM-26 local MLflow packaging, then SM-25. After the first Bundle, SM-27 adds +SM-15L is reopened for monthly UC output; SM-18 remains parked. SM-26 local +MLflow packaging is complete; start with SM-25. After the first Bundle, SM-27 adds explicit full-history rescore and SM-22/SM-28 add optional monthly retraining with controlled candidate/champion promotion.** Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-16 are complete. Start SM-26 from +- SM-00 through SM-16 and SM-26 are complete. Start SM-25 from [04-databricks-integration-plan.md](04-databricks-integration-plan.md). The first Bundle and its two-month table rehearsal are specified in [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). - This planning update changed priorities only; no implementation or new cloud - execution. The previous Spark-first direction is superseded. Preserve the later + SM-26 added local artifact and MLflow packaging without cloud execution. The + previous Spark-first direction is superseded. Preserve the later [NODE_SUPPORT.md](NODE_SUPPORT.md) inventory and [gap review](reports/2026-09-22-spark-databricks-gap-review.md). The review enumerated all 100 source registration IDs and added model training, @@ -27,11 +27,12 @@ Target release: 0.9.0. Branch: `090`. open unless implemented or explicitly deferred by the user. Broad SM-17 follows the first local Bundle. The current Spark integration uses compatible bundles; pandas/Polars -> Spark is not support for arbitrary local FE or model artifacts. -- SM-26 explicitly separates broader local pipeline packaging from native Spark - porting. Preserve the fitted local FE/model behavior and test clean-environment - MLflow parity; classify local, row-local serving and distributed eligibility - separately. SM-25, SM-24a, SM-15L and SM-20a follow this artifact - contract. No new support is implemented by this planning update. +- SM-26 separates fitted pandas/Polars pipeline packaging from native Spark + porting. The versioned trusted-pickle artifact records fit engine, schemas, + model class, runtime versions and a checksum; the MLflow pyfunc restores it + without refitting. Its declared scope is whole-frame local prediction; + row-local HTTP and Spark modes fail a scope check. SM-25, SM-24a, SM-15L + and SM-20a follow this artifact contract. - The registry-bundle loader and first registry-to-Spark probe are implemented. Local validation passed 29 combined tests; the selected live platform gate is now complete. Tested 0.9.0 wheel hashes are recorded in the platform file. @@ -103,7 +104,8 @@ Keep new documentation and diagram labels in English. ## Current execution boundaries -- `predict_local` consumes the new standalone bundle; the frontend does not +- `predict_local_pipeline` consumes the new fitted local artifact, while + `predict_local` consumes the portable standalone bundle. The frontend does not call it yet. Frontend inference uses `POST /deployment/predict` and `DeploymentService`, which loads the existing artifact, applies FE, aligns model columns and predicts. The backend artifact bridge belongs to SM-18. @@ -152,6 +154,18 @@ dtypes fail at packaging. Producer uv files and temporary paths are excluded. Registry-to-G2 evidence continued through SM-14 and the completed SM-16 live gate. Scheduling configuration, endpoints and templates remain later work. +SM-26 added `save_local_pipeline`/`load_local_pipeline`/`predict_local_pipeline` +and `log_local_model`. The pandas and Polars MLflow 3.16.1 lane proved +categorical encoding, null input, classification probabilities and tuned +decisions after load; an isolated subprocess also reloaded the logged model. +The changed 0.9.0 wheel was installed into the isolated environment and +`python -I` resolved the new module from site-packages. +Custom binning followed by encoding passed both local engines. The registry +adapter now resolves the local payload digest alongside the existing portable +bundle digest; no alias was promoted. This was local validation only. The +matching Skyulf wheel remains an explicit deployment dependency, and broader +model families still require parity evidence. See the MLflow model guide. + SM-14 added explicit MLflow registry publication and resolution. The adapter publishes only `runs:/...` artifacts, leaves alias promotion explicit, resolves an alias once to a concrete `models:/name/version` URI, and returns the packaged diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 9ed8643c5..5cc9967b5 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,15 +1,15 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-22. **SM-00–SM-16 complete; SM-26 next. Target: 0.9.0.** +Updated: 2026-09-23. **SM-00–SM-16 and SM-26 complete; SM-25 next. Target: 0.9.0.** First deliverable: pandas/Polars training and local batch on Databricks, then a working local-engine Bundle. Spark expansion follows that Bundle. SM-15L is reopened for monthly UC output; SM-18 and continuous streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-26. +and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-25. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). -This planning update has not generated a project or started a job. +SM-26 added a local MLflow package; no Bundle was generated or cloud job started. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -38,8 +38,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | WAIT | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | | SM-17 | Complete existing Spark node/model coverage | SM-20a | LATER | Resume only after the first local Bundle; preserve all inventoried gaps | | SM-18 | Backend/Canvas and legacy artifact bridge | SM-17 | PARKED | Capability UI/API, DAG contracts and existing deployment compatibility | -| SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | READY | Preserve fitted FE/model/engine semantics beyond the portable Spark subset; clean-environment prediction parity; Spark eligibility separate | -| SM-25 | Local-first config / SDK preflight | SM-26 | WAIT | Choose pandas/Polars, runtime, store and sink; reject incompatible local packages before jobs | +| SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | +| SM-25 | Local-first config / SDK preflight | SM-26 | READY | Choose pandas/Polars, runtime, store and sink; reject incompatible local packages before jobs | | SM-24a | Local training and bounded batch prediction | SM-25 | WAIT | Reuse fitted pandas/Polars pipeline and pinned MLflow model; no Spark FE/model dependency | | SM-20a | First local-engine Bundle/template | SM-24a, verified SM-15L | WAIT | Generate, validate, deploy and run pandas/Polars train/monthly batch with pinned MLflow/UC model | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | @@ -140,6 +140,30 @@ SM-17 requires the full tracked scope above. Some algorithms may need an explici alternative backend rather than an equivalent native Spark implementation; that decision must not hide missing support. SM-19 streaming remains optional and parked. +## SM-26 — 2026-09-23 local packaging validation, DONE + +- Added a versioned, trusted local pipeline artifact with recorded pandas/Polars + fit engine, raw/model feature schemas, model class, exact dependency versions, + payload checksum, classification classes and explicit tuned-threshold choice. + Legacy pipeline pickles still load; those without a recorded engine require a + refit before local MLflow packaging. +- Added MLflow pyfunc packaging and a synthetic input example/signature for the + supported scalar inputs. Its pandas boundary converts back to the recorded + Polars engine when needed. Whole-frame local is the only declared execution + scope; HTTP row-local and Spark scopes are rejected. Existing explicit registry + publication and pinned-version resolution now carry the local payload digest. +- Isolated MLflow 3.16.1 integration: **16 local artifact/pyfunc tests passed** + for categorical encoding, binning, null input, classes/probabilities, tuned + thresholds, cross-engine requests, and a fresh isolated Python subprocess + load. The 0.9.0 wheel was built from the changed source and installed into the + isolated environment; `python -I` resolved the new module from site-packages. + Existing MLflow packaging and registry compatibility: **47 passed, 1 skipped**. + Pipeline unit regression: **385 passed, 2 skipped**. Focused Ruff and ty checks + passed. No Databricks job or Delta writer was added in this task. +- [MLflow model guide](../../docs/user_guide/mlflow_models.md) lists the tested + model families and the wheel, serving and Spark limits. Next: SM-25 config and + preflight, then SM-24a local Databricks batch workflow. + ## SM-16 — 2026-09-22 local and live validation, DONE - Baseline `d43e74ca`. Added a trusted pinned registry-bundle loader and a diff --git a/skyulf-core/skyulf/inference/local_pipeline.py b/skyulf-core/skyulf/inference/local_pipeline.py new file mode 100644 index 000000000..7e79ce595 --- /dev/null +++ b/skyulf-core/skyulf/inference/local_pipeline.py @@ -0,0 +1,228 @@ +"""Versioned artifacts for fitted pandas/Polars pipelines. + +The payload is pickle: only load artifacts from a trusted producer. The +checksum detects damaged bytes but does not authenticate their origin. +""" + +from __future__ import annotations + +import json +import pickle +from dataclasses import dataclass +from pathlib import Path +from typing import Literal + +import numpy as np +import pandas as pd +import polars as pl +from pydantic import BaseModel, ConfigDict, Field +from sklearn.base import is_classifier + +from ..core.portable_state import _bad_constant, _unique_object +from ..core.schema import SkyulfSchema +from ..pipeline import SkyulfPipeline +from ._manifest import checksum, runtime_requirements + +_MAX_MANIFEST_BYTES = 64 * 1024 +_MAX_PIPELINE_BYTES = 256 * 1024 * 1024 + + +class LocalPipelineManifest(BaseModel): + """Record the fit engine, raw schema, runtime and serialized pipeline identity.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + format_version: Literal[1] = 1 + fitted_engine: Literal["pandas", "polars"] + input_columns: tuple[str, ...] = Field(min_length=1) + input_dtypes: tuple[str, ...] + feature_columns: tuple[str, ...] = Field(min_length=1) + feature_dtypes: tuple[str, ...] + requirements: tuple[tuple[str, str], ...] + pipeline_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") + model_class: str = Field(min_length=1) + execution_scope: Literal["whole_frame_local"] = "whole_frame_local" + task: Literal["regression", "classification"] + classes: tuple[str | int | float | bool, ...] = () + use_tuned_thresholds: bool = False + + +@dataclass(frozen=True) +class LocalPipelineArtifact: + """A validated manifest and fitted local pipeline loaded from one directory.""" + + manifest: LocalPipelineManifest + pipeline: SkyulfPipeline + + +def _recorded_schemas(pipeline: SkyulfPipeline) -> tuple[SkyulfSchema, SkyulfSchema]: + """Require the raw and model feature schemas from a successful model fit.""" + schemas = getattr(pipeline, "_inference_schemas", None) + if schemas is None or pipeline.fitted_engine not in {"pandas", "polars"}: + raise ValueError("Missing fitted local engine or schemas; refit this pipeline.") + if pipeline.model_estimator is None or pipeline.model_estimator.model is None: + raise ValueError("Local artifact requires a fitted model.") + return schemas + + +def _manifest( + pipeline: SkyulfPipeline, payload: bytes, use_tuned_thresholds: bool +) -> LocalPipelineManifest: + """Derive metadata from the successful fit rather than caller-supplied labels.""" + raw, features = _recorded_schemas(pipeline) + estimator = pipeline.model_estimator + if estimator is None: + raise ValueError("Local artifact requires a fitted model.") + model = estimator._unwrap_tuned_model() + fitted_engine = pipeline.fitted_engine + if fitted_engine not in ("pandas", "polars"): + raise ValueError("Local artifact requires a recorded pandas or Polars fit engine.") + classification = is_classifier(model) + classes = tuple(np.asarray(model.classes_).tolist()) if classification else () + if classification and not callable(getattr(model, "predict_proba", None)): + raise ValueError("Local classification artifact requires predict_proba().") + if use_tuned_thresholds and (not classification or pipeline._tuned_thresholds is None): + raise ValueError("Tuned thresholds require fitted classification thresholds.") + return LocalPipelineManifest( + fitted_engine=fitted_engine, + input_columns=raw.columns, + input_dtypes=tuple(raw.dtypes.get(name, "unknown") for name in raw.columns), + feature_columns=features.columns, + feature_dtypes=tuple(features.dtypes.get(name, "unknown") for name in features.columns), + requirements=runtime_requirements(), + pipeline_sha256=checksum(payload), + model_class=f"{type(model).__module__}.{type(model).__qualname__}", + task="classification" if classification else "regression", + classes=classes, + use_tuned_thresholds=use_tuned_thresholds, + ) + + +def _check_runtime(manifest: LocalPipelineManifest) -> None: + """Reject incompatible Python or dependency versions before loading pickle.""" + current = dict(runtime_requirements()) + required = dict(manifest.requirements) + if set(required) != set(current): + raise ValueError("Local artifact runtime requirements are incomplete.") + for name in ("python", "skyulf-core", "scikit-learn", "numpy", "scipy", "pandas", "polars"): + actual, expected = current[name], required[name] + matches = ( + actual.split(".")[:2] == expected.split(".")[:2] + if name == "python" + else actual == expected + ) + if not matches: + raise ValueError( + f"Local artifact runtime mismatch for {name}: requires {expected}, found {actual}." + ) + + +def save_local_pipeline( + pipeline: SkyulfPipeline, path: str | Path, *, use_tuned_thresholds: bool = False +) -> None: + """Write a fitted pipeline and its manifest to a new directory.""" + if type(pipeline) is not SkyulfPipeline: + raise TypeError("Expected a fitted SkyulfPipeline.") + _recorded_schemas(pipeline) + payload = pickle.dumps(pipeline, protocol=pickle.HIGHEST_PROTOCOL) + if len(payload) > _MAX_PIPELINE_BYTES: + raise ValueError("Local pipeline payload exceeds the size limit.") + manifest = _manifest(pipeline, payload, use_tuned_thresholds) + metadata = manifest.model_dump_json().encode("utf-8") + if len(metadata) > _MAX_MANIFEST_BYTES: + raise ValueError("Local pipeline manifest exceeds the size limit.") + destination = Path(path) + destination.mkdir(parents=True, exist_ok=False) + (destination / "manifest.json").write_bytes(metadata) + (destination / "pipeline.pkl").write_bytes(payload) + + +def _read_bounded(path: Path, limit: int) -> bytes: + """Limit artifact bytes before JSON or pickle decoding.""" + with path.open("rb") as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError(f"Local artifact {path.name} exceeds the size limit.") + return data + + +def load_local_pipeline(path: str | Path) -> LocalPipelineArtifact: + """Validate and load a trusted producer's local pipeline artifact.""" + source = Path(path) + metadata = _read_bounded(source / "manifest.json", _MAX_MANIFEST_BYTES) + document = json.loads( + metadata.decode("utf-8"), object_pairs_hook=_unique_object, parse_constant=_bad_constant + ) + if type(document) is not dict or type(document.get("format_version")) is not int: + raise ValueError("Invalid local artifact format_version.") + manifest = LocalPipelineManifest.model_validate_json(metadata) + if len(manifest.input_columns) != len(manifest.input_dtypes) or len( + manifest.feature_columns + ) != len(manifest.feature_dtypes): + raise ValueError("Local artifact schema columns and dtypes disagree.") + if any( + len(set(columns)) != len(columns) + for columns in (manifest.input_columns, manifest.feature_columns) + ): + raise ValueError("Local artifact schema columns must be unique.") + _check_runtime(manifest) + payload = _read_bounded(source / "pipeline.pkl", _MAX_PIPELINE_BYTES) + if checksum(payload) != manifest.pipeline_sha256: + raise ValueError("Local pipeline payload checksum mismatch.") + pipeline = pickle.loads(payload) # nosec B301 -- trusted producer only, after size/runtime/checksum checks + if type(pipeline) is not SkyulfPipeline: + raise ValueError("Local artifact payload is not a SkyulfPipeline.") + if _manifest(pipeline, payload, manifest.use_tuned_thresholds) != manifest: + raise ValueError("Local artifact manifest disagrees with its fitted pipeline.") + return LocalPipelineArtifact(manifest, pipeline) + + +def require_local_pipeline_scope( + artifact: LocalPipelineArtifact, + scope: Literal["whole_frame_local", "row_local_http", "spark_worker", "spark_native"], +) -> None: + """Reject execution modes that the local artifact has not been proven to support.""" + if not isinstance(artifact, LocalPipelineArtifact): + raise TypeError("Expected a LocalPipelineArtifact.") + if scope != artifact.manifest.execution_scope: + raise ValueError(f"Local pipeline artifact is not eligible for {scope}.") + + +def predict_local_pipeline( + frame: pd.DataFrame | pl.DataFrame, artifact: LocalPipelineArtifact +) -> pd.DataFrame: + """Apply the fitted local FE and model with the recorded fit engine.""" + if not isinstance(artifact, LocalPipelineArtifact): + raise TypeError("Expected a LocalPipelineArtifact.") + if not isinstance(frame, pd.DataFrame | pl.DataFrame): + raise TypeError("Local prediction requires a pandas or Polars DataFrame.") + if artifact.manifest.fitted_engine == "polars": + native = pl.from_pandas(frame) if isinstance(frame, pd.DataFrame) else frame + else: + native = frame.to_pandas() if isinstance(frame, pl.DataFrame) else frame + expected = SkyulfSchema( + artifact.manifest.input_columns, + dict(zip(artifact.manifest.input_columns, artifact.manifest.input_dtypes, strict=True)), + ) + expected.assert_compatible( + SkyulfSchema.from_dataframe(native), + check_dtypes=True, + check_order=True, + where="local pipeline input", + ) + prediction = np.asarray( + artifact.pipeline.predict( + native, use_tuned_thresholds=artifact.manifest.use_tuned_thresholds + ) + ) + if prediction.shape != (len(frame),): + raise ValueError("Local pipeline prediction shape disagrees with input rows.") + index = frame.index if isinstance(frame, pd.DataFrame) else pd.RangeIndex(len(frame)) + result = pd.DataFrame({"prediction": pd.Series(prediction, index=index)}) + if artifact.manifest.task == "classification": + transformed = artifact.pipeline.feature_engineer.transform(native, preserve_rows=True) + probabilities = np.asarray(artifact.pipeline._predict_proba_transformed(transformed)) + if probabilities.shape != (len(frame), len(artifact.manifest.classes)): + raise ValueError("Local pipeline probability shape disagrees with recorded classes.") + for position in range(len(artifact.manifest.classes)): + result[f"probability_{position}"] = probabilities[:, position] + return result diff --git a/skyulf-core/skyulf/integrations/mlflow/local_model.py b/skyulf-core/skyulf/integrations/mlflow/local_model.py new file mode 100644 index 000000000..2fe00a2a4 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/local_model.py @@ -0,0 +1,159 @@ +"""Optional MLflow pyfunc adapter for fitted local pipeline artifacts. + +The artifact is for whole-frame local batches. A pyfunc model here does not +certify row-local HTTP serving or Spark partition safety. +""" + +from __future__ import annotations + +import inspect +import tempfile +from pathlib import Path +from typing import Any + +import mlflow # ty: ignore[unresolved-import] +import pandas as pd + +from ...inference._manifest import label_dtype +from ...inference.local_pipeline import ( + LocalPipelineArtifact, + load_local_pipeline, + predict_local_pipeline, +) +from .model import _make_client, _mlflow_dtype, _scrub_local_artifact_uri + + +class SkyulfLocalPythonModel(mlflow.pyfunc.PythonModel): + """Load one fitted local pipeline and retain its recorded execution engine.""" + + def __init__(self) -> None: + """Start unloaded until MLflow provides the saved artifact path.""" + self._artifact: LocalPipelineArtifact | None = None + + def load_context(self, context: Any) -> None: + """Validate the trusted pipeline artifact before the first prediction.""" + try: + artifact_path = context.artifacts["local_pipeline"] + except (AttributeError, KeyError) as exc: + raise ValueError("MLflow model is missing the local pipeline artifact.") from exc + self._artifact = load_local_pipeline(artifact_path) + + def predict( + self, context: Any, model_input: pd.DataFrame, params: dict[str, Any] | None = None + ) -> pd.DataFrame: + """Apply the saved fit engine to MLflow's named pandas input columns.""" + del context, params + if self._artifact is None: + raise RuntimeError("SkyulfLocalPythonModel.load_context() was not called.") + if not isinstance(model_input, pd.DataFrame): + raise TypeError("Skyulf local pyfunc requires a pandas DataFrame.") + return predict_local_pipeline(model_input, self._artifact) + + +def log_local_model( + local_artifact_path: str | Path, + *, + run_id: str, + artifact_path: str, + tracking_uri: str | None = None, +) -> str: + """Log a fitted local pipeline under one explicit MLflow run and artifact path.""" + if type(run_id) is not str or not run_id.strip(): + raise ValueError("run_id must be a non-empty string.") + if type(artifact_path) is not str or not artifact_path.strip(): + raise ValueError("artifact_path must be a non-empty string.") + if any(marker in artifact_path for marker in ("#", "?")): + raise ValueError("artifact_path cannot contain URI delimiters.") + if tracking_uri is not None and (type(tracking_uri) is not str or not tracking_uri.strip()): + raise ValueError("tracking_uri must be a non-empty string or None.") + local_path = Path(local_artifact_path).resolve() + artifact = load_local_pipeline(local_path) + client = _make_client(tracking_uri) + client.get_run(run_id) + with tempfile.TemporaryDirectory(prefix="skyulf-local-mlflow-") as directory: + model_path = Path(directory) / "model" + save_options: dict[str, Any] = {} + if "uv_project_path" in inspect.signature(mlflow.pyfunc.save_model).parameters: + save_options["uv_project_path"] = directory + mlflow.pyfunc.save_model( + path=str(model_path), + python_model=SkyulfLocalPythonModel(), + artifacts={"local_pipeline": str(local_path)}, + signature=_signature(artifact), + input_example=_input_example(artifact), + pip_requirements=_pip_requirements(artifact), + metadata={ + "skyulf_artifact_kind": "local_pipeline", + "skyulf_fitted_engine": artifact.manifest.fitted_engine, + "skyulf_execution_scope": "whole_frame_local", + "skyulf_local_pipeline_digest": artifact.manifest.pipeline_sha256, + }, + mlflow_model=mlflow.models.Model(run_id=run_id, artifact_path=artifact_path), + **save_options, + ) + _scrub_local_artifact_uri(model_path, "local_pipeline") + client.log_artifacts(run_id, str(model_path), artifact_path=artifact_path) + return f"runs:/{run_id}/{artifact_path}" + + +def _normalized_dtype(dtype: str) -> str: + """Map fitted pandas/Polars labels to the supported MLflow scalar vocabulary.""" + normalized = dtype.lower() + return {"object": "string", "str": "string", "utf8": "string", "boolean": "bool"}.get( + normalized, normalized + ) + + +def _signature(artifact: LocalPipelineArtifact) -> Any: + """Declare ordered raw inputs and prediction/probability output columns.""" + from mlflow.models import ( # noqa: PLC0415 - optional dependency boundary # ty: ignore[unresolved-import] + ModelSignature, + ) + from mlflow.types import ( # noqa: PLC0415 - optional dependency boundary # ty: ignore[unresolved-import] + ColSpec, + Schema, + ) + + manifest = artifact.manifest + inputs = Schema( + [ + ColSpec(_mlflow_dtype(_normalized_dtype(dtype)), name=name) + for name, dtype in zip(manifest.input_columns, manifest.input_dtypes, strict=True) + ] + ) + prediction_dtype = "float64" if manifest.task == "regression" else label_dtype(manifest.classes) + outputs = [ColSpec(_mlflow_dtype(prediction_dtype), name="prediction")] + if manifest.task == "classification": + outputs.extend( + ColSpec(_mlflow_dtype("float64"), name=f"probability_{position}") + for position in range(len(manifest.classes)) + ) + return ModelSignature(inputs=inputs, outputs=Schema(outputs)) + + +def _input_example(artifact: LocalPipelineArtifact) -> pd.DataFrame: + """Build a synthetic typed row without retaining training data.""" + values: dict[str, pd.Series] = {} + for name, dtype in zip( + artifact.manifest.input_columns, artifact.manifest.input_dtypes, strict=True + ): + normalized = _normalized_dtype(dtype) + if normalized == "string": + values[name] = pd.Series(["example"], dtype="object") + elif normalized == "bool": + values[name] = pd.Series([False], dtype="bool") + elif normalized.startswith(("int", "uint")): + values[name] = pd.Series([0], dtype=normalized) + elif normalized.startswith("float"): + values[name] = pd.Series([0.0], dtype=normalized) + else: + raise ValueError(f"Unsupported MLflow local input dtype: {dtype}.") + return pd.DataFrame(values) + + +def _pip_requirements(artifact: LocalPipelineArtifact) -> list[str]: + """Pin the fitted runtime and optional MLflow flavor for reproducible loading.""" + return [ + *(f"{name}=={value}" for name, value in artifact.manifest.requirements if name != "python"), + f"mlflow=={mlflow.__version__}", + ] diff --git a/skyulf-core/skyulf/integrations/mlflow/model.py b/skyulf-core/skyulf/integrations/mlflow/model.py index 56f7ff362..303d948a7 100644 --- a/skyulf-core/skyulf/integrations/mlflow/model.py +++ b/skyulf-core/skyulf/integrations/mlflow/model.py @@ -124,14 +124,14 @@ def _make_client(tracking_uri: str | None) -> Any: return MlflowClient(tracking_uri=tracking_uri) -def _scrub_local_artifact_uri(model_path: Path) -> None: +def _scrub_local_artifact_uri(model_path: Path, artifact_key: str = "bundle") -> None: """Remove the temporary producer path from the portable MLflow metadata.""" model = mlflow.models.Model.load(str(model_path)) flavor = model.flavors[mlflow.pyfunc.FLAVOR_NAME] artifacts = flavor.get("artifacts", {}) - bundle_artifact = artifacts.get("bundle") - if isinstance(bundle_artifact, dict) and "uri" in bundle_artifact: - bundle_artifact["uri"] = "bundle" + saved_artifact = artifacts.get(artifact_key) + if isinstance(saved_artifact, dict) and "uri" in saved_artifact: + saved_artifact["uri"] = artifact_key model.save(str(model_path / "MLmodel")) diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py index 742d10f1a..e02c79db1 100644 --- a/skyulf-core/skyulf/integrations/mlflow/registry.py +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -190,7 +190,7 @@ def resolve_model( except Exception as exc: # noqa: BLE001 - artifact metadata is another registry boundary raise _translate_error(exc, name=name, version=concrete_version) from exc metadata = model.metadata or {} - digest = metadata.get("skyulf_bundle_digest") + digest = metadata.get("skyulf_bundle_digest") or metadata.get("skyulf_local_pipeline_digest") return ResolvedModel( name=name, version=concrete_version, diff --git a/skyulf-core/skyulf/pipeline/_pipeline.py b/skyulf-core/skyulf/pipeline/_pipeline.py index 16f6e4ca1..7d69a6d36 100644 --- a/skyulf-core/skyulf/pipeline/_pipeline.py +++ b/skyulf-core/skyulf/pipeline/_pipeline.py @@ -145,6 +145,7 @@ def __init__(self, config: PipelineConfig | dict[str, Any]): self._target_column: str | None = None self._tuned_thresholds: dict[Any, float] | None = None self._inference_schemas: tuple[SkyulfSchema, SkyulfSchema] | None = None + self._fitted_engine: str | None = None # Initialize model estimator if config is present if self.modeling_config: @@ -342,6 +343,7 @@ def fit( self._target_column = None self._tuned_thresholds = None self._inference_schemas = None + self._fitted_engine = None if self.model_estimator is not None: self.model_estimator.model = None try: @@ -363,10 +365,12 @@ def _fit( """Fit validated data, publishing metadata only after all stages complete.""" metrics = {} input_schema = None + fitted_engine = None if self.model_estimator is not None: raw_train = data.train if isinstance(data, SplitDataset) else data raw_features = raw_train[0] if isinstance(raw_train, tuple) else raw_train input_schema = SkyulfSchema.from_dataframe(raw_features).drop((target_column,)) + fitted_engine = str(get_engine(raw_features).name) # 1. Feature Engineering logger.info("Starting Feature Engineering...") @@ -423,6 +427,7 @@ def _fit( if self.model_estimator.model is not None and input_schema is not None: self._inference_schemas = (input_schema, model_schema) + self._fitted_engine = fitted_engine self._fit_metrics = metrics self._target_column = target_column @@ -500,12 +505,16 @@ def get_fitted_split( _to_pandas(y_test), ) - def _predict_proba_transformed(self, transformed_data: pd.DataFrame | SkyulfDataFrame) -> Any: + def _predict_proba_transformed( + self, transformed_data: pd.DataFrame | pl.DataFrame | SkyulfDataFrame + ) -> Any: """Run predict_proba on already-transformed data, raising if unsupported.""" if self.model_estimator is None or self.model_estimator.model is None: raise ValueError("Pipeline not fitted or no model configured.") + # Existing model appliers dispatch Polars at runtime, although their + # shared annotation names only pandas and the Skyulf frame protocol. proba = self.model_estimator.applier.predict_proba( - transformed_data, self.model_estimator.model + cast(Any, transformed_data), self.model_estimator.model ) if proba is None: raise ValueError( @@ -516,7 +525,7 @@ def _predict_proba_transformed(self, transformed_data: pd.DataFrame | SkyulfData def optimize_thresholds( self, - X_val: pd.DataFrame | SkyulfDataFrame, + X_val: pd.DataFrame | pl.DataFrame | SkyulfDataFrame, y_val: pd.Series | Any, metric: Callable[[Any, Any], float], strategy: str | None = None, @@ -600,7 +609,7 @@ def optimize_thresholds( def predict( self, - data: pd.DataFrame | SkyulfDataFrame, + data: pd.DataFrame | pl.DataFrame | SkyulfDataFrame, use_tuned_thresholds: bool = False, ) -> Any: """Generate predictions. @@ -640,7 +649,7 @@ def predict( # 2. Modeling if not use_tuned_thresholds: predictions = self.model_estimator.applier.predict( - transformed_data, self.model_estimator.model + cast(Any, transformed_data), self.model_estimator.model ) validate_prediction_rows( len(data), prediction_row_count(predictions), stage="Model prediction" @@ -728,6 +737,11 @@ def is_fitted(self) -> bool: return True return self.model_estimator is not None and self.model_estimator.model is not None + @property + def fitted_engine(self) -> str | None: + """Return the successful model fit's frame engine, if recorded.""" + return getattr(self, "_fitted_engine", None) + def fingerprint(self) -> str: """Return a deterministic SHA-256 over topology + fitted artifacts. diff --git a/skyulf-core/tests/integrations/test_local_mlflow_model.py b/skyulf-core/tests/integrations/test_local_mlflow_model.py new file mode 100644 index 000000000..91b8ed4e3 --- /dev/null +++ b/skyulf-core/tests/integrations/test_local_mlflow_model.py @@ -0,0 +1,179 @@ +"""MLflow transport tests for whole-frame local pandas/Polars pipelines.""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +import polars as pl +import pytest +from sklearn.metrics import accuracy_score + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import ( + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, +) +from skyulf.pipeline import SkyulfPipeline + +mlflow = pytest.importorskip("mlflow") +from skyulf.integrations.mlflow.local_model import log_local_model # noqa: E402 +from skyulf.integrations.mlflow.registry import register_model, resolve_model # noqa: E402 +from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run # noqa: E402 + + +@pytest.fixture(autouse=True) +def restore_tracking_uri(): + """Each pyfunc test must leave the caller's MLflow tracking URI unchanged.""" + previous = mlflow.get_tracking_uri() + try: + yield + finally: + mlflow.set_tracking_uri(previous) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_local_pyfunc_matches_saved_categorical_pipeline( + engine: str, tmp_path, monkeypatch +) -> None: + """MLflow must restore fitted categorical FE and the recorded engine without refitting.""" + monkeypatch.chdir(tmp_path) + frame = pd.DataFrame( + { + "city": ["Riga", "Vilnius", "Riga", "Tallinn", "Vilnius", "Tallinn"], + "amount": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + "target": [11.0, 24.0, 13.0, 36.0, 27.0, 38.0], + } + ) + native = pl.from_pandas(frame) if engine == "polars" else frame + pipeline = SkyulfPipeline( + { + "preprocessing": [ + { + "name": "city", + "transformer": "OneHotEncoder", + "params": { + "columns": ["city"], + "drop_original": True, + "handle_unknown": "ignore", + }, + } + ], + "modeling": {"type": "linear_regression"}, + } + ) + if isinstance(native, pl.DataFrame): + training, heldout = native.slice(0, 5), native.slice(5, 1) + else: + training, heldout = native.iloc[:5], native.iloc[5:] + pipeline.fit(SplitDataset(train=training, test=heldout), target_column="target") + query = pd.DataFrame({"city": ["Riga", None], "amount": [8.0, 9.0]}) + expected = np.asarray(pipeline.predict(pl.from_pandas(query) if engine == "polars" else query)) + artifact_path = tmp_path / "local" + save_local_pipeline(pipeline, artifact_path) + uri = f"sqlite:///{(tmp_path / 'tracking.db').as_posix()}" + config = TrackingConfig(enabled=True, tracking_uri=uri, experiment_name=f"local-{engine}") + assert config.tracking_uri is not None + + with track_run(config, run_name="local-package") as run: + assert run.run_id is not None + model_uri = log_local_model( + artifact_path, + run_id=run.run_id, + artifact_path="model", + tracking_uri=config.tracking_uri, + ) + + mlflow.set_tracking_uri(config.tracking_uri) + loaded = mlflow.pyfunc.load_model(model_uri) + result = loaded.predict(query) + saved = predict_local_pipeline(query, load_local_pipeline(artifact_path)) + + np.testing.assert_allclose(result["prediction"], expected, rtol=0, atol=1e-10) + pd.testing.assert_frame_equal(result.reset_index(drop=True), saved.reset_index(drop=True)) + assert loaded.metadata.signature is not None + assert loaded.metadata.metadata["skyulf_fitted_engine"] == engine + mlmodel_file = mlflow.artifacts.download_artifacts( + f"{model_uri}/MLmodel", dst_path=str(tmp_path / "download") + ) + mlmodel_text = Path(mlmodel_file).read_text(encoding="utf-8") + assert "uri: local_pipeline" in mlmodel_text + assert "skyulf-local-mlflow-" not in mlmodel_text + + registered = register_model( + model_uri, + f"local_{engine}", + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + resolved = resolve_model( + f"local_{engine}", + version=registered.version, + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ) + assert resolved.model_uri == f"models:/local_{engine}/{registered.version}" + assert resolved.digest == load_local_pipeline(artifact_path).manifest.pipeline_sha256 + + child = subprocess.run( + [ + sys.executable, + "-I", + "-c", + "import json, mlflow, pandas as pd, sys; " + "mlflow.set_tracking_uri(sys.argv[1]); " + "frame = pd.DataFrame({'city': ['Riga', None], 'amount': [8.0, 9.0]}); " + "print(json.dumps(mlflow.pyfunc.load_model(sys.argv[2]).predict(frame).to_dict('list')))", + config.tracking_uri, + model_uri, + ], + capture_output=True, + text=True, + check=True, + ) + np.testing.assert_allclose(json.loads(child.stdout)["prediction"], expected, rtol=0, atol=1e-10) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_local_pyfunc_preserves_tuned_classification(engine: str, tmp_path, monkeypatch) -> None: + """Class probabilities and saved threshold decisions survive MLflow loading.""" + monkeypatch.chdir(tmp_path) + train = pd.DataFrame( + { + "x": [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0], + "label": ["no", "no", "no", "yes", "yes", "yes"], + } + ) + native = pl.from_pandas(train) if engine == "polars" else train + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=native, test=native.head(0)), target_column="label") + query = pd.DataFrame({"x": [-2.5, -0.25, 0.25, 2.5]}) + native_query = pl.from_pandas(query) if engine == "polars" else query + pipeline.optimize_thresholds( + native_query, np.array(["no", "yes", "yes", "yes"]), accuracy_score, grid_points=5 + ) + artifact_path = tmp_path / "local" + save_local_pipeline(pipeline, artifact_path, use_tuned_thresholds=True) + expected = predict_local_pipeline(query, load_local_pipeline(artifact_path)) + uri = f"sqlite:///{(tmp_path / 'tracking.db').as_posix()}" + config = TrackingConfig(enabled=True, tracking_uri=uri, experiment_name=f"classes-{engine}") + assert config.tracking_uri is not None + + with track_run(config, run_name="class-package") as run: + assert run.run_id is not None + model_uri = log_local_model( + artifact_path, + run_id=run.run_id, + artifact_path="model", + tracking_uri=config.tracking_uri, + ) + + mlflow.set_tracking_uri(config.tracking_uri) + actual = mlflow.pyfunc.load_model(model_uri).predict(query) + pd.testing.assert_frame_equal(actual, expected) + assert actual.columns.tolist() == ["prediction", "probability_0", "probability_1"] diff --git a/skyulf-core/tests/integrations/test_local_pipeline_artifact.py b/skyulf-core/tests/integrations/test_local_pipeline_artifact.py new file mode 100644 index 000000000..8c486dfba --- /dev/null +++ b/skyulf-core/tests/integrations/test_local_pipeline_artifact.py @@ -0,0 +1,243 @@ +"""A fitted local pipeline keeps its execution semantics when transported.""" + +from __future__ import annotations + +import json + +import numpy as np +import pandas as pd +import polars as pl +import pytest +from sklearn.metrics import accuracy_score + +from skyulf.data.dataset import SplitDataset +from skyulf.pipeline import SkyulfPipeline + + +def _fitted_pipeline(engine: str) -> tuple[SkyulfPipeline, pd.DataFrame]: + """Fit categorical FE that the initial portable Spark bundle cannot encode.""" + train = pd.DataFrame( + { + "city": ["Riga", "Vilnius", "Riga", "Tallinn", "Vilnius", "Tallinn"], + "amount": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + "target": [11.0, 24.0, 13.0, 36.0, 27.0, 38.0], + } + ) + pipeline = SkyulfPipeline( + { + "preprocessing": [ + { + "name": "encode_city", + "transformer": "OneHotEncoder", + "params": { + "columns": ["city"], + "drop_original": True, + "handle_unknown": "ignore", + }, + } + ], + "modeling": {"type": "linear_regression"}, + } + ) + data = pl.from_pandas(train) if engine == "polars" else train + if isinstance(data, pl.DataFrame): + training, held_out = data.slice(0, 5), data.slice(5, 1) + else: + training, held_out = data.iloc[:5], data.iloc[5:] + pipeline.fit(SplitDataset(train=training, test=held_out), target_column="target") + query = pd.DataFrame( + {"city": ["Vilnius", "Riga", "Tallinn"], "amount": [7.0, 8.0, 9.0]}, + index=[31, 9, 42], + ) + return pipeline, query + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_fit_engine_survives_existing_pipeline_round_trip(engine: str, tmp_path) -> None: + """MLflow packaging must know which local engine produced the fitted state.""" + pipeline, _ = _fitted_pipeline(engine) + path = tmp_path / "pipeline.pkl" + pipeline.save(str(path)) + loaded = SkyulfPipeline.load(str(path)) + + assert loaded.fitted_engine == engine + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_local_artifact_preserves_fitted_categorical_predictions(engine: str, tmp_path) -> None: + """A versioned local artifact must replay categorical FE without refitting.""" + from skyulf.inference.local_pipeline import ( # noqa: PLC0415 - red test imports new API + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, + ) + + pipeline, query = _fitted_pipeline(engine) + native_query = pl.from_pandas(query) if engine == "polars" else query + expected = np.asarray(pipeline.predict(native_query)) + path = tmp_path / "local-artifact" + save_local_pipeline(pipeline, path) + manifest = json.loads((path / "manifest.json").read_text(encoding="utf-8")) + restored = load_local_pipeline(path) + result = predict_local_pipeline(query, restored) + polars_result = predict_local_pipeline(pl.from_pandas(query), restored) + + assert manifest["format_version"] == 1 + assert manifest["fitted_engine"] == engine + assert manifest["input_columns"] == ["city", "amount"] + assert list(result.columns) == ["prediction"] + assert result.index.tolist() == query.index.tolist() + np.testing.assert_allclose(result["prediction"].to_numpy(), expected, rtol=0, atol=1e-10) + assert polars_result.index.tolist() == list(range(len(query))) + np.testing.assert_allclose(polars_result["prediction"].to_numpy(), expected, rtol=0, atol=1e-10) + + +def test_local_artifact_rejects_reordered_input(tmp_path) -> None: + """Reordered raw columns must fail before fitted FE sees a changed schema.""" + from skyulf.inference.local_pipeline import ( # noqa: PLC0415 - red test imports new API + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, + ) + + pipeline, query = _fitted_pipeline("pandas") + path = tmp_path / "local-artifact" + save_local_pipeline(pipeline, path) + + with pytest.raises(ValueError, match="column order"): + predict_local_pipeline(query[["amount", "city"]], load_local_pipeline(path)) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_local_artifact_preserves_class_probabilities_and_tuned_threshold( + engine: str, tmp_path +) -> None: + """Class labels, probability positions and explicit tuned decisions must survive saving.""" + from skyulf.inference.local_pipeline import ( + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, + ) + + train = pd.DataFrame( + {"x": [-3.0, -2.0, -1.0, 1.0, 2.0, 3.0], "label": ["no", "no", "no", "yes", "yes", "yes"]} + ) + native_train = pl.from_pandas(train) if engine == "polars" else train + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "logistic_regression"}}) + pipeline.fit(SplitDataset(train=native_train, test=native_train.head(0)), target_column="label") + query = pd.DataFrame({"x": [-2.5, -0.25, 0.25, 2.5]}) + native_query = pl.from_pandas(query) if engine == "polars" else query + pipeline.optimize_thresholds( + native_query, np.array(["no", "yes", "yes", "yes"]), accuracy_score, grid_points=5 + ) + expected = np.asarray(pipeline.predict(native_query, use_tuned_thresholds=True)) + path = tmp_path / "classified" + save_local_pipeline(pipeline, path, use_tuned_thresholds=True) + loaded = load_local_pipeline(path) + actual = predict_local_pipeline(query, loaded) + + assert loaded.manifest.classes == ("no", "yes") + assert loaded.manifest.use_tuned_thresholds is True + assert actual.columns.tolist() == ["prediction", "probability_0", "probability_1"] + np.testing.assert_array_equal(actual["prediction"].to_numpy(), expected) + np.testing.assert_allclose(actual[["probability_0", "probability_1"]].sum(axis=1), 1.0) + + +def test_local_artifact_rejects_tampered_payload(tmp_path) -> None: + """A damaged pipeline payload must be rejected before pickle deserialization.""" + from skyulf.inference.local_pipeline import load_local_pipeline, save_local_pipeline + + pipeline, _ = _fitted_pipeline("pandas") + path = tmp_path / "local-artifact" + save_local_pipeline(pipeline, path) + payload = path / "pipeline.pkl" + payload.write_bytes(payload.read_bytes() + b"changed") + + with pytest.raises(ValueError, match="checksum"): + load_local_pipeline(path) + + +def test_legacy_pipeline_loads_but_requires_refit_for_local_artifact(tmp_path) -> None: + """Older pickle files remain loadable without inventing a missing fit engine.""" + from skyulf.inference.local_pipeline import save_local_pipeline + + pipeline, _ = _fitted_pipeline("pandas") + del pipeline._fitted_engine + legacy_path = tmp_path / "legacy.pkl" + pipeline.save(str(legacy_path)) + loaded = SkyulfPipeline.load(str(legacy_path)) + + assert loaded.fitted_engine is None + with pytest.raises(ValueError, match="refit"): + save_local_pipeline(loaded, tmp_path / "new-local") + + +def test_local_artifact_rejects_serving_and_spark_scopes(tmp_path) -> None: + """A whole-frame local package must not be treated as endpoint or Spark eligible.""" + from skyulf.inference.local_pipeline import ( + load_local_pipeline, + require_local_pipeline_scope, + save_local_pipeline, + ) + + pipeline, _ = _fitted_pipeline("pandas") + path = tmp_path / "local-artifact" + save_local_pipeline(pipeline, path) + artifact = load_local_pipeline(path) + + assert require_local_pipeline_scope(artifact, "whole_frame_local") is None + for scope in ("row_local_http", "spark_worker", "spark_native"): + with pytest.raises(ValueError, match="not eligible"): + require_local_pipeline_scope(artifact, scope) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_local_artifact_replays_binning_and_encoding(engine: str, tmp_path) -> None: + """Saved bin edges and downstream category positions must both survive loading.""" + from skyulf.inference.local_pipeline import ( + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, + ) + + train = pd.DataFrame( + {"x": [0.5, 1.5, 2.5, 3.5, 4.5, 5.5], "target": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]} + ) + native = pl.from_pandas(train) if engine == "polars" else train + pipeline = SkyulfPipeline( + { + "preprocessing": [ + { + "name": "bands", + "transformer": "CustomBinning", + "params": { + "columns": ["x"], + "bins": [0.0, 2.0, 4.0, 6.0], + "output_suffix": "_band", + }, + }, + { + "name": "encode_bands", + "transformer": "OneHotEncoder", + "params": { + "columns": ["x_band"], + "drop_original": True, + "handle_unknown": "ignore", + }, + }, + ], + "modeling": {"type": "linear_regression"}, + } + ) + if isinstance(native, pl.DataFrame): + training, heldout = native.slice(0, 5), native.slice(5, 1) + else: + training, heldout = native.iloc[:5], native.iloc[5:] + pipeline.fit(SplitDataset(train=training, test=heldout), target_column="target") + query = pd.DataFrame({"x": [1.0, 3.0, 5.0]}) + expected = np.asarray(pipeline.predict(pl.from_pandas(query) if engine == "polars" else query)) + path = tmp_path / "binned" + save_local_pipeline(pipeline, path) + actual = predict_local_pipeline(query, load_local_pipeline(path)) + + np.testing.assert_allclose(actual["prediction"], expected, rtol=0, atol=1e-10) From 1575525e3e0a1effa0a66c75543cebe7dfd5cf57 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 17:08:45 +0300 Subject: [PATCH 32/85] feat: validate local Databricks workflows and MLflow inference Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 10 + docs/user_guide/databricks_batch.md | 3 + docs/user_guide/databricks_local_sdk.md | 249 +++++++++ docs/user_guide/mlflow_registry.md | 6 + .../04-databricks-integration-plan.md | 61 ++- .../06-sm24a-live-validation-plan.md | 110 ++++ .../spark_and_mlflow/07-sm24a-node-matrix.csv | 63 +++ .../08-sm24a-live-validation-report.md | 120 +++++ .../09-sm24a-scaler-outlier-audit.md | 29 ++ .../10-sm24a-heldout-metrics-report.md | 33 ++ initiatives/spark_and_mlflow/HANDOFF.md | 17 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 73 ++- mkdocs.yml | 1 + .../examples/databricks_local_sm24a_job.py | 406 +++++++++++++++ .../databricks_local_sm24a_node_audit.py | 129 +++++ .../databricks_local_sm24a_registry_probe.py | 134 +++++ ...bricks_local_sm24a_scaler_outlier_audit.py | 288 ++++++++++ .../integrations/databricks/__init__.py | 42 +- .../integrations/databricks/local_batch.py | 251 +++++++++ .../integrations/databricks/local_sdk.py | 490 ++++++++++++++++++ .../skyulf/integrations/mlflow/registry.py | 72 ++- .../test_databricks_local_batch.py | 307 +++++++++++ .../test_databricks_local_five_models.py | 198 +++++++ .../integrations/test_databricks_local_sdk.py | 288 ++++++++++ .../integrations/test_local_mlflow_model.py | 111 +++- 25 files changed, 3450 insertions(+), 41 deletions(-) create mode 100644 docs/user_guide/databricks_local_sdk.md create mode 100644 initiatives/spark_and_mlflow/06-sm24a-live-validation-plan.md create mode 100644 initiatives/spark_and_mlflow/07-sm24a-node-matrix.csv create mode 100644 initiatives/spark_and_mlflow/08-sm24a-live-validation-report.md create mode 100644 initiatives/spark_and_mlflow/09-sm24a-scaler-outlier-audit.md create mode 100644 initiatives/spark_and_mlflow/10-sm24a-heldout-metrics-report.md create mode 100644 skyulf-core/examples/databricks_local_sm24a_job.py create mode 100644 skyulf-core/examples/databricks_local_sm24a_node_audit.py create mode 100644 skyulf-core/examples/databricks_local_sm24a_registry_probe.py create mode 100644 skyulf-core/examples/databricks_local_sm24a_scaler_outlier_audit.py create mode 100644 skyulf-core/skyulf/integrations/databricks/local_batch.py create mode 100644 skyulf-core/skyulf/integrations/databricks/local_sdk.py create mode 100644 skyulf-core/tests/integrations/test_databricks_local_batch.py create mode 100644 skyulf-core/tests/integrations/test_databricks_local_five_models.py create mode 100644 skyulf-core/tests/integrations/test_databricks_local_sdk.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 6a1c36931..e8a2d2b5d 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -22,6 +22,16 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added +- Local-engine Databricks SDK configuration and preflight for bounded + pandas/Polars batches. It selects trusted local or portable artifacts, + resolves MLflow aliases once to concrete versions, checks metadata and + source/sink compatibility, and can probe the fitted predictor with a sample. + Existing Skyulf FE nodes and models need no separate SDK allowlist. +- Explicit local-engine training and UC batch scoring: a bounded split produces + the existing full-pipeline artifact; a versioned Delta source is filtered by + requested month, narrowed, row-limited and checked against a decoded-byte + budget before whole-frame pandas/Polars prediction. The result carries source + and model identity diagnostics. Local-result Delta publication remains follow-up. - Versioned local pandas/Polars pipeline artifact and MLflow pyfunc packaging preserve fitted encoding/binning, model state, input order, class probabilities and explicit tuned thresholds without refitting. The fit engine and exact diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md index 486910db4..26ebda863 100644 --- a/docs/user_guide/databricks_batch.md +++ b/docs/user_guide/databricks_batch.md @@ -13,6 +13,9 @@ exclusive admission and a restricted principal's target-write denial, with unchanged data/version and released ownership afterward. This is a bounded regression workflow, not certification of every runtime or production workload. Tracking and registry remain optional and independent of the engine. +For small-data pandas/Polars scoring on Databricks job compute, see the +[local-engine SDK](databricks_local_sdk.md). Its UC source and Delta target +adapters are still separate follow-up tasks. This runner currently requires Spark. Delta itself can also be written from pandas/Polars through [Arrow and delta-rs](https://delta-io.github.io/delta-rs/usage/writing/); a local-engine Skyulf Delta sink diff --git a/docs/user_guide/databricks_local_sdk.md b/docs/user_guide/databricks_local_sdk.md new file mode 100644 index 000000000..d19e64e08 --- /dev/null +++ b/docs/user_guide/databricks_local_sdk.md @@ -0,0 +1,249 @@ +# Local-engine SDK for Databricks jobs + +The first local workflow runs pandas or Polars feature engineering and a fitted +scikit-learn model **inside one Python process**. `runtime="databricks"` means +that process may be a Databricks job task; it does not switch inference to Spark. +The same code also runs with `runtime="local"`. No Bundle project or +`databricks.yml` is needed to use this SDK. + +SM-25 provides configuration, artifact selection and preflight. It accepts a +caller-owned, bounded pandas/Polars frame and returns predictions. SM-24a adds +an explicit, versioned UC Delta source reader for monthly local batches. +Guarded UC Delta publication remains SM-15L; choosing that sink still produces +a `PreflightError` before a job is submitted. + +## Fit and score a small batch + +Install the same `skyulf-core`, pandas, Polars and scikit-learn versions in the +training and scoring environments. The local artifact records those versions, +the fit engine and the raw/feature schemas. It contains trusted Python pickle; +only load packages from your own controlled producer. + +```python +import pandas as pd + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import save_local_pipeline +from skyulf.integrations.databricks import ( + InputSource, LocalWorkflowConfig, ModelSelection, OutputSink, + prepare_local_workflow, +) +from skyulf.pipeline import SkyulfPipeline + +train = pd.DataFrame({ + "x": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + "target": [2.0, 4.0, 6.0, 8.0, 10.0, 12.0], +}) +pipeline = SkyulfPipeline({ + "preprocessing": [], + "modeling": {"type": "linear_regression"}, +}) +pipeline.fit( + SplitDataset(train=train.iloc[:5], test=train.iloc[5:]), + target_column="target", +) +save_local_pipeline(pipeline, "/tmp/customer-model") + +config = LocalWorkflowConfig( + runtime="databricks", # or "local" on a workstation + engine="pandas", # must match the recorded fit engine + source=InputSource(kind="caller_frame", max_rows=10_000, max_bytes=32_000_000), + model=ModelSelection(kind="local_pipeline", path="/tmp/customer-model"), + sink=OutputSink(kind="return_frame"), +) +prepared = prepare_local_workflow(config) +query = pd.DataFrame({"x": [7.0, 8.0]}) +predictions = prepared.predict(query) +assert prepared.preflight.feature_order == ("x",) +print(predictions) +``` + +The example uses a path within one process. A Databricks job's temporary path +is not a cross-job model store. For separate training and scoring jobs, log the +artifact with `log_local_model`, register that run model explicitly, then select +the registered version in scoring. An alias is read once and converted to a +concrete `models:/name/version` reference; later alias changes cannot alter the +already prepared predictor. + +```python +from skyulf.integrations.databricks import ModelSelection + +selection = ModelSelection( + kind="local_pipeline", + name="catalog.schema.customer_model", + alias="champion", # or version="7"; never both + tracking_uri=tracking_uri, + registry_uri=registry_uri, +) +config = config.model_copy(update={"model": selection}) +prepared = prepare_local_workflow(config) # read-only registry resolution and load +print(prepared.preflight.model_version, prepared.preflight.model_digest) +``` + +Obtain `tracking_uri` and `registry_uri` from your job's non-secret settings; +authenticate through the runtime's credential provider. Do not put tokens or +passwords into config or store URIs. Registering or changing an alias is a +separate, explicit operation. The local SDK never promotes a model. + +## Preflight and custom pipelines + +`LocalWorkflowConfig` is frozen, serializable and has no implicit source +snapshot, period or promotion decision. `preflight_local(config, artifact=...)` +performs offline checks without a registry call, package load or job submission. +It returns issues with a code, category and suggested fix. For a registry +selection, offline preflight reports `model_unresolved`; call +`prepare_local_workflow` when read-only registry access is allowed. That step +loads the pinned package and performs full preflight before returning a +predictor. `local_issues`, `remote_issues` and `remote_checked` keep the two +stages visible. It may deserialize trusted pickle, but creates no cloud resource. +If representative rows are available before submitting a job, pass +`probe_frame=sample` to `preflight_local` or `prepare_local_workflow`. The probe +runs the actual fitted FE and model and reports a `prediction_probe_failed` +issue for an incompatible sample. A passing sample is evidence for that sample, +not a guarantee about every later batch. + +```python +from skyulf.inference.local_pipeline import load_local_pipeline +from skyulf.integrations.databricks import preflight_local + +artifact = load_local_pipeline("/tmp/customer-model") +report = preflight_local(config.model_copy(update={ + "model": ModelSelection(kind="local_pipeline", path="/tmp/customer-model") +}), artifact=artifact) +for issue in report.issues: + print(issue.category, issue.code, issue.fix) +``` + +For custom feature engineering, edit the normal `SkyulfPipeline` preprocessing +configuration, fit it on training data, save it, and compare predictions before +and after loading. The SDK has **no separate node or model allowlist**: it +restores the fitted `SkyulfPipeline` and calls its existing prediction path. +Integration examples cover imputation, scaling, encoding, binning, linear and +logistic regression, and a MinMaxScaler/random-forest combination on both local +engines. Other library combinations remain governed by their own fitted +inference behavior and should receive replay tests before production use. +The package is not eligible for Spark-native, Spark-worker or row-local HTTP +execution. The separate `portable_bundle` selection uses +`InferenceBundle` metadata and its own `predict_local` path for supported +portable FE; selecting the wrong package kind fails preflight. + +For example, an advanced pipeline may fit explicit binning followed by encoding +before it is packaged; its saved edges and category positions are then replayed +by the local artifact: + +```python +pipeline = SkyulfPipeline({ + "preprocessing": [ + {"name": "bands", "transformer": "CustomBinning", "params": { + "columns": ["x"], "bins": [0.0, 2.0, 4.0, 6.0], + "output_suffix": "_band", + }}, + {"name": "encode_bands", "transformer": "OneHotEncoder", "params": { + "columns": ["x_band"], "drop_original": True, + "handle_unknown": "ignore", + }}, + ], + "modeling": {"type": "linear_regression"}, +}) +# Fit with SplitDataset, then save_local_pipeline as in the first example. +``` + +`InputSource` defaults to 100,000 rows and 128 MiB. Set tighter limits for each +job. `PreparedLocalWorkflow.predict` checks both before running FE and the model. +It preserves the caller's input column order and rejects schema mismatches; it +does not silently collect a Spark DataFrame. On Databricks, supply either a +bounded caller-owned frame or the explicit pinned UC source adapter below. + +## Evaluate the held-out split in the model run + +Keep labeled test rows outside the fit split. After fitting and loading the +artifact, `evaluate_local_holdout` calls the saved pipeline's normal prediction +path on those raw test features. It returns `heldout_mae`, `heldout_rmse` and +`heldout_r2` for regression; classification returns `heldout_accuracy` and +`heldout_f1_weighted`, plus `heldout_f1` for binary models (the model's second +class is positive). A negative R2 is a valid poor-generalization result, not a +logging failure. The caller chooses the split and logs metrics to the same +MLflow run ID that contains the model artifact: + +```python +import mlflow + +from skyulf.data.dataset import SplitDataset +from skyulf.integrations.databricks import evaluate_local_holdout, fit_local_workflow +from skyulf.integrations.mlflow.local_model import log_local_model + +# `frame` is a bounded, labeled pandas or Polars frame with 1,000 rows. +training, heldout = frame[:800], frame[800:] +artifact_path = "/tmp/customer-model" +artifact = fit_local_workflow( + {"preprocessing": preprocessing, "modeling": {"type": model_type}}, + SplitDataset(train=training, test=heldout), + target_column="target", + artifact_path=artifact_path, + max_rows=1000, + max_bytes=4_000_000, +) +metrics = evaluate_local_holdout(artifact, heldout, target_column="target") +with mlflow.start_run(run_name="customer-model") as run: + mlflow.log_param("heldout_rows", len(heldout)) + mlflow.log_metrics(metrics) + model_uri = log_local_model( + artifact_path, run_id=run.info.run_id, + artifact_path="model", tracking_uri="databricks", + ) +``` + +The held-out labels are used only for evaluation. Monthly scoring reads raw +features without labels and applies the already fitted FE and model. The +SM-24a live validation (`initiatives/spark_and_mlflow/10-sm24a-heldout-metrics-report.md`) +uses five model configurations with 800 training and 200 held-out rows each. + +## Fit and score a pinned UC source + +`fit_local_workflow` requires an explicit `SplitDataset`; it bounds the total +rows and in-memory bytes before fitting and saves the same trusted artifact as +`save_local_pipeline`. Tracking and registration remain opt-in calls through +`track_run`, `log_local_model` and `register_model`. They do not move an alias. + +```python +from datetime import UTC, datetime + +from skyulf.integrations.databricks import ( + InputSource, LocalSourceSpec, LocalWorkflowConfig, ModelSelection, + OutputSink, prepare_local_workflow, score_local_source, +) + +table = "catalog.schema.new_entities" +config = LocalWorkflowConfig( + runtime="databricks", + engine="polars", # must match the registered artifact's fit engine + source=InputSource(kind="uc_table", table=table, version=12, + max_rows=10_000, max_bytes=32_000_000), + model=ModelSelection(kind="local_pipeline", + name="catalog.schema.customer_model", version="7", + tracking_uri="databricks", registry_uri="databricks-uc"), + sink=OutputSink(kind="return_frame"), +) +prepared = prepare_local_workflow(config) # resolves a concrete model version +period = LocalSourceSpec( + table=table, version=12, row_keys=("entity_id",), + input_columns=("amount", "city"), # exact saved raw input order + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + max_rows=10_000, max_bytes=32_000_000, +) +result = score_local_source(spark, period, prepared) +print(result.predictions, result.diagnostics) +``` + +The reader applies the pinned Delta version, half-open UTC period filter, +column projection, deterministic row-key order and `max_rows + 1` limit before +iterating on the driver. It stops when decoded serialized rows or the resulting +local frame exceed `max_bytes`, and rejects duplicate row keys. This byte guard +measures decoded payload and local memory, not Spark's private wire framing; +very wide individual rows should therefore be excluded or handled by a +separately proven paged transport. The selected source and its limits must match +the prepared workflow. The result keeps row keys outside the model input and +records the source version, period, model digest and concrete model version. +No prediction table is created here. Whole-frame FE retains local pandas or +Polars behavior even though Spark performs the bounded UC read. diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 086791aa8..35dcd8212 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -74,6 +74,12 @@ downloaded package, and checks the package/bundle digest against `resolved.diges The same bundle can then be passed to `predict_local` or either Spark inference mode, subject to their existing schema and FE capabilities. +For fitted pandas/Polars packages created with `log_local_model`, use +`load_registered_local_pipeline(resolved, ...)` instead. It verifies the +declared local artifact path, scope, engine and payload digest against the +pinned registry version. That package supports whole-frame local inference; +it does not become a Spark bundle merely because it is registered. + ```python from skyulf.integrations.mlflow.registry import load_registered_bundle diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md index d7ae3282e..701937317 100644 --- a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -1,6 +1,7 @@ # Local-first Databricks integration and Bundle plan -Updated: 2026-09-22. Planning only; no implementation or new cloud execution. +Updated: 2026-09-23. SM-26, SM-25 and SM-24a are implemented and validated; +SM-15L and the first Bundle remain planned. Baseline: `63dd3e21` and the completed, scoped SM-16 evidence. ## Current direction @@ -15,9 +16,10 @@ SM-15L as a prerequisite for monthly UC table output in the first Bundle. SM-18 Backend/Canvas work and continuous streaming remain parked. Full SM-17 node/model expansion waits until the first local Bundle works. -Latest refinement: **SM-26 comes first**, making broader existing fitted local -pandas/Polars pipelines usable through MLflow without waiting for native Spark -node ports. This is planned packaging work, not existing support. +SM-26 made broader existing fitted local pandas/Polars pipelines usable through +MLflow without waiting for native Spark node ports. SM-24a then validated the +first bounded local-engine Databricks training and scoring path; see its +[live report](08-sm24a-live-validation-report.md). The first scenario is pandas/Polars FE and Python-model training, followed by local Python batch prediction in a Databricks job and monthly publication to a @@ -64,10 +66,10 @@ UC publication and Bundle claims need their own cloud evidence. | Order | Task | Depends on | State | | --- | --- | --- | --- | -| 1 | SM-26: local pipeline MLflow packaging | SM-16; existing local persistence | READY | -| 2 | SM-25: local-first SDK configuration and preflight | SM-26 | WAIT | -| 3 | SM-24a: local training and bounded batch prediction | SM-25 | WAIT | -| 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | WAIT | +| 1 | SM-26: local pipeline MLflow packaging | SM-16; existing local persistence | DONE | +| 2 | SM-25: local-first SDK configuration and preflight | SM-26 | DONE | +| 3 | SM-24a: local training and bounded batch prediction | SM-25 | DONE | +| 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | READY | | 5 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; verified SM-15L | WAIT | | After first Bundle | SM-27: bounded full-history rescore and selectable Bundle mode | SM-20a; SM-15L | LATER | | After first Bundle | SM-22 then SM-28: validation/promotion and optional monthly retraining | SM-20a; SM-22 for SM-28 | LATER | @@ -119,16 +121,16 @@ Proposed implementation area: `skyulf-core/skyulf/integrations/databricks/`; config/preflight/workflow modules, integration tests and an English SDK guide. Names below describe responsibilities; settle public signatures in the task design. -- [ ] Define immutable configuration for runtime, input source, FE/model execution, +- [x] Define immutable configuration for runtime, input source, FE/model execution, optional stores and output sink without embedding credentials. -- [ ] Reuse bundle metadata to resolve feature order, model digest and output schema; +- [x] Reuse bundle metadata to resolve feature order, model digest and output schema; resolve an alias once to a pinned version. Preserve explicit caller-owned inputs. -- [ ] Provide a preflight result with node/config/model/runtime incompatibilities +- [x] Provide a preflight result with node/config/model/runtime incompatibilities and actionable fixes. Distinguish local checks from optional read-only remote checks. -- [ ] Document a short pandas/Polars fit -> local batch workflow that can run +- [x] Document a short pandas/Polars fit -> local batch workflow that can run on Databricks job compute, plus an advanced custom-code entry point. Keep source size limits explicit and do not generate a project to use the SDK. -- [ ] Select among verified local-package and portable-bundle contracts explicitly. +- [x] Select among verified local-package and portable-bundle contracts explicitly. Keep wider native engine/model choices in parked SM-17j; packaging a local pipeline is not a shortcut to claim broader Spark support. @@ -140,30 +142,35 @@ decisions. Spark preflight expands only with later tested Spark options. ## SM-24a - Reusable training and batch workflows Reference: inference/data/config services; reuse Skyulf's fitted local pipeline. -Proposed files: a workflow module in the Databricks integration, a thin executable -example, integration tests and `docs/user_guide/databricks_batch.md` updates. +Delivered in `integrations/databricks/local_batch.py`, the +[local-engine guide](../../docs/user_guide/databricks_local_sdk.md), runnable +examples and integration tests. The [live validation report](08-sm24a-live-validation-report.md) +records separate UC training and inference tables, five cross-job model cases +and a per-node preprocessing audit. -- [ ] Compose existing local pandas/Polars SkyulfPipeline fit, SM-26 local +- [x] Compose existing local pandas/Polars SkyulfPipeline fit, SM-26 local package export and optional tracking/registration as a thin training entry point. Accept explicit training/split inputs and a bounded local source. -- [ ] Read a named UC table or other declared source through an explicit bounded +- [x] Read a named UC table or other declared source through an explicit bounded local adapter. Filter the requested month at the pinned source version before collecting locally; enforce row/byte ceilings. A full two-month table download or an implicit unbounded Spark collect is not acceptable. -- [ ] Expose pure Python batch prediction for verified SM-26 local packages; +- [x] Expose pure Python batch prediction for verified SM-26 local packages; preserve required whole-frame context and input order. This task returns predictions; SM-15L handles publication. -- [ ] Compose pinned registry load, package preflight and local prediction. -- [ ] Return structured diagnostics with source, period, model and code identity; - do not claim the Spark runner's durable publication receipt. -- [ ] Accept explicit period/backfill parameters and business timezone; retries +- [x] Compose pinned registry load, package preflight and local prediction. +- [x] Return structured diagnostics with source, period and model identity; + the separate job report records installed code versions. Do not claim the + Spark runner's durable publication receipt. +- [x] Accept explicit period/backfill parameters and business timezone; retries reuse the same request rather than refreshing the target version silently. -- [ ] Keep table/control provisioning an explicit setup step, separate from scoring. +- [x] Keep table/control provisioning an explicit setup step, separate from scoring. -Acceptance: pandas/Polars training and local batch prediction preserve the -declared engine and clean-environment model parity, including tracking-off -behavior. Bounded reads fail before exhausting process memory. Registration -never promotes an alias implicitly; no table-write success is claimed here. +Acceptance evidence: pandas/Polars training and local batch prediction preserve +the declared engine and cross-job model parity. Bounded reads reject excess +rows and decoded/local-frame bytes; Spark wire bytes and one-row peak transport +are not capped. Registration never promotes an alias implicitly; no table-write +success is claimed here. The stronger transport guarantee is SM-24d. ## SM-15L - Local monthly UC Delta publication diff --git a/initiatives/spark_and_mlflow/06-sm24a-live-validation-plan.md b/initiatives/spark_and_mlflow/06-sm24a-live-validation-plan.md new file mode 100644 index 000000000..4de1e7abb --- /dev/null +++ b/initiatives/spark_and_mlflow/06-sm24a-live-validation-plan.md @@ -0,0 +1,110 @@ +# SM-24a live Databricks validation plan + +Status: completed for the documented small-data scope on 2026-09-23. The +[live report](08-sm24a-live-validation-report.md) records concrete evidence. +This is a validation gate for the reusable local training and bounded batch +workflow, not the first Databricks Bundle or the monthly Delta sink. + +## Test area and data + +Use the previously selected `skyulf` CLI profile and its workspace. The user +selected the new isolated UC schema `workspace.skyulf_sm24a_20260923` on +2026-09-23. Use names prefixed `skyulf_sm24a_` and retain the final +resource list and job IDs in the validation report. + +Create two small managed Delta source tables with a fixed seed: + +| Table | Purpose | Initial size | +| --- | --- | ---: | +| `skyulf_sm24a_train_source` | Explicit training/validation rows with regression and classification labels | about 1,000 rows | +| `skyulf_sm24a_score_source` | New entities with the same raw feature columns but no labels; two monthly periods | about 80 rows per period | + +Use distinct entity IDs across training and scoring. Include numeric nulls and +outliers, skewed categorical values, an unseen scoring category, timestamps, +and deterministic target rules. Record both Delta source versions. Training +must not read labels from the scoring table, and scoring must not accept label +columns. The second table is the user's requested independent inference input. +SM-24a returns predictions and a diagnostic report; SM-15L will later publish +them to a separate UC Delta prediction table. + +## Model and preprocessing gate + +First prove each selected configuration locally on both its fit engine and a +fresh loaded artifact. The live training job then fits five separate pipelines +on Databricks; a separate scoring job loads their concrete UC model versions. +These are planned cases, not claims of current Databricks parity: + +| Case | Fit engine | Model family | Preprocessing under test | +| --- | --- | --- | --- | +| R1 | pandas | `linear_regression` | numeric imputation, standard scaling, feature math | +| R2 | Polars | `random_forest_regressor` | numeric bounds, custom binning, one-hot encoding | +| C1 | pandas | `logistic_regression` | imputation, ordinal encoding, robust scaling | +| C2 | Polars | `random_forest_classifier` | categorical encoding, numeric scaling, interaction | +| R3 | pandas | `gradient_boosting_regressor` | KNN imputation, selection, power or general transform | + +The exact node parameters and order are fixed only after local fit, save, load +and prediction parity succeeds; incompatible combinations must be corrected or +reported, never quietly dropped. Regression outputs are compared by row key +within a stated numeric tolerance. Classification labels must match exactly; +probability column order must match saved classes and each row must sum to one. +Include null and unseen-category scoring rows in the comparison. + +The five pipelines cannot certify all preprocessing registrations. The current +[inventory](NODE_SUPPORT.md) lists 62 preprocessing IDs, including aliases, +optional dependencies, inspection/split steps, resampling and other train-only +operations. Add a machine-readable per-ID report with one row for every ID: +`inference_eligible`, `train_only`, `inspection`, `optional_dependency`, or +`unsupported`, plus local result, live result, parameters and reason. Run +fit/save/load/predict probes on Databricks for each inference-eligible local +node that can use a bounded fixture; test train-only effects separately without +claiming they run at inference. A failed or inapplicable row remains visible. +Broader fixes remain in SM-17 after the first Bundle, but the audit itself is +part of this gate. + +The [current 62-ID matrix](07-sm24a-node-matrix.csv) records all unrun rows +explicitly. A category is a triage judgment, not a claim of full compatibility. + +## Cross-job sequence + +1. Provision the two test tables once. Record their schema, row counts, distinct + keys and Delta versions. Keep training and scoring rows disjoint. +2. Run the training job on Databricks serverless with the tested Skyulf wheel + and pinned dependencies. Give it explicit train/validation inputs. Package + each fitted local pipeline, log it to MLflow, and register five test UC + model versions. Do not set or move a champion alias. +3. Run a separate scoring job. For one requested month and pinned source + version, filter the Delta source before moving data to the Python driver. + Project only row keys and required raw input columns. Apply `max_rows + 1` + in Spark, then enforce decoded serialized-row and local-frame byte budgets. + Never call unbounded `collect()` or `toPandas()` on the full table. The + selected Spark iterator does not report exact wire bytes; a single wide row + can arrive before the decoded-byte check rejects it. This is an explicit + small-data boundary, not a hard network-byte guarantee. A workload that + requires a hard transport limit needs a separate proven adapter before use. +4. Resolve each chosen model once to a concrete version, load the trusted + package, run local pandas/Polars prediction and retain row keys separately. + Compare with the training job's saved pre-package reference predictions and + a small direct-estimator oracle. Record model version/digest, code version, + source version, UTC period boundaries, timezone, counts and comparison. +5. Repeat for the second month. Verify the first month's input is not rescored. + Re-run one identical request to check deterministic prediction and identity. + Publication/replay of a Delta prediction table belongs to SM-15L. + +Negative cases: reordered/missing input columns, wrong model artifact kind, +incompatible runtime, an over-row and over-byte source, unknown model version, +and a changed alias after pinning. Each must fail with a bounded, actionable +result before an unbounded read or any target write. `max_bytes` means decoded +payload/local-frame bytes, not Spark wire bytes. Keep serverless tasks +time-bounded, record actual compute use, and never modify production tables. + +## Completion evidence + +SM-24a is ready to close only after local and live reports identify the exact +wheel/dependency versions, UC source versions, five concrete registered-model +versions, the per-node matrix, passed/failed cases and retained test resources. +The report must distinguish the demonstrated five-model path from untested +model families. It must not claim monthly Delta publication or Bundle deployment. + +Platform references: [Delta versioned reads](https://docs.databricks.com/aws/en/delta/tutorial), +[serverless limitations](https://docs.databricks.com/aws/en/compute/serverless/limitations), +and [serverless task dependencies](https://docs.databricks.com/aws/en/compute/serverless/dependencies). diff --git a/initiatives/spark_and_mlflow/07-sm24a-node-matrix.csv b/initiatives/spark_and_mlflow/07-sm24a-node-matrix.csv new file mode 100644 index 000000000..b4ca7402d --- /dev/null +++ b/initiatives/spark_and_mlflow/07-sm24a-node-matrix.csv @@ -0,0 +1,63 @@ +registration_id,category,local_result,live_result,parameters,reason,live_evidence +CustomBinning,inference_eligible,pass,pass,"[{""case"":""R2"",""params"":{""columns"":[""x""],""bins"":[-1000.0,0.0,5.0,10.0,1000.0],""output_suffix"":""_band""}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +GeneralBinning,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a""],""n_bins"":4,""strategy"":""uniform""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +KBinsDiscretizer,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a""],""n_bins"":4,""strategy"":""uniform""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +Casting,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a""],""target_type"":""float32""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +AliasReplacement,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_low""],""alias_type"":""custom"",""custom_map"":{""red"":""warm""}}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +InvalidValueReplacement,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a"",""num_b"",""num_c""],""rule"":""negative""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +TextCleaning,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_low""],""operations"":[{""op"":""case"",""mode"":""upper""}]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +ValueReplacement,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_low""],""mapping"":{""red"":""warm""}}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +Deduplicate,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +DropMissingColumns,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""with_missing""],""threshold"":0.05}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +DropMissingRows,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +MissingIndicator,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""with_missing""]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +DummyEncoder,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_a"",""cat_b""]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +HashEncoder,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_high""],""n_features"":4}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +LabelEncoder,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_a"",""cat_b""]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +OneHotEncoder,inference_eligible,pass,pass,"[{""case"":""R2"",""params"":{""columns"":[""city"",""x_band""],""handle_unknown"":""ignore"",""drop_original"":true}},{""case"":""C2"",""params"":{""columns"":[""city""],""handle_unknown"":""ignore"",""drop_original"":true}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +OrdinalEncoder,inference_eligible,pass,pass,"[{""case"":""C1"",""params"":{""columns"":[""city""],""handle_unknown"":""use_encoded_value"",""unknown_value"":-1}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +TargetEncoder,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_a"",""cat_b""],""target_column"":""target""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +WOEEncoder,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""cat_a"",""cat_b""],""target_column"":""target""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +FeatureGeneration,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""operations"":[{""operation_type"":""arithmetic"",""input_columns"":[""num_a"",""num_b""],""method"":""add""}]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +FeatureGenerationNode,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""operations"":[{""operation_type"":""arithmetic"",""input_columns"":[""num_a"",""num_b""],""method"":""add""}]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +FeatureMath,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""operations"":[{""operation_type"":""arithmetic"",""input_columns"":[""num_a"",""num_b""],""method"":""add""}]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +FeatureInteraction,inference_eligible,pass,pass,"[{""case"":""R1"",""params"":{""columns"":[""x"",""z""]}},{""case"":""C2"",""params"":{""columns"":[""x"",""z""]}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +PolynomialFeatures,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""lat1"",""lat2""]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +PolynomialFeaturesNode,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""lat1"",""lat2""]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +CorrelationThreshold,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a"",""num_b"",""num_c""],""threshold"":0.95}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +feature_selection,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""method"":""variance"",""threshold"":0.0}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +ModelBasedSelection,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a"",""num_b""],""target_column"":""target"",""estimator"":""RandomForest""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +UnivariateSelection,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a"",""num_b""],""target_column"":""target"",""score_func"":""f_classif"",""k"":1}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +VarianceThreshold,inference_eligible,pass,pass,"[{""case"":""R3"",""params"":{""columns"":[""x"",""z""],""threshold"":0.0}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +GeoDistance,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""lat1_col"":""lat1"",""lon1_col"":""lon1"",""lat2_col"":""lat2"",""lon2_col"":""lon2""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +H3Index,optional_dependency,not_run,not_run,,Requires an optional runtime dependency and an isolated replay probe., +IterativeImputer,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""with_missing"",""num_a""]}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +KNNImputer,inference_eligible,pass,pass,"[{""case"":""R3"",""params"":{""columns"":[""x"",""z""],""n_neighbors"":3}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +SimpleImputer,inference_eligible,pass,pass,"[{""case"":""R1"",""params"":{""columns"":[""z""],""strategy"":""mean""}},{""case"":""R2"",""params"":{""columns"":[""z""],""strategy"":""median""}},{""case"":""C1"",""params"":{""columns"":[""z""],""strategy"":""mean""}},{""case"":""C2"",""params"":{""columns"":[""z""],""strategy"":""mean""}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +DataSnapshot,inspection,targeted_tests_pass,not_applicable,,Existing inspection tests passed in the focused 317-test suite; no scoring feature transform is claimed., +DatasetProfile,inspection,targeted_tests_pass,not_applicable,,Existing inspection tests passed in the focused 317-test suite; no scoring feature transform is claimed., +EllipticEnvelope,conditional_inference,guard_pass,guard_pass,"[{""case"":""filtered_batch_guard_pandas_polars"",""params"":{""columns"":[""x""],""random_state"":42}}]","Fitted transform removes an extreme row; predict rejects the shortened batch on both engines. A batch with no filtered rows can score, but one prediction per input is not guaranteed for arbitrary inputs.",973375074755539 +IQR,conditional_inference,guard_pass,guard_pass,"[{""case"":""filtered_batch_guard_pandas_polars"",""params"":{""columns"":[""x""]}}]","Fitted transform removes an extreme row; predict rejects the shortened batch on both engines. A batch with no filtered rows can score, but one prediction per input is not guaranteed for arbitrary inputs.",973375074755539 +ManualBounds,conditional_inference,guard_pass,guard_pass,"[{""case"":""filtered_batch_guard_pandas_polars"",""params"":{""columns"":[""x""],""bounds"":{""x"":{""lower"":0,""upper"":99}}}}]","Fitted transform removes an extreme row; predict rejects the shortened batch on both engines. A batch with no filtered rows can score, but one prediction per input is not guaranteed for arbitrary inputs.",973375074755539 +Winsorize,inference_eligible,pass,pass,"[{""case"":""R2"",""params"":{""columns"":[""x""]}},{""case"":""mlflow_cross_job_pandas_polars"",""params"":{""columns"":[""x""],""model"":""linear_regression"",""rows_per_month"":20}}]","Saved full pipelines passed pandas and Polars; concrete MLflow/UC model versions replayed 20 keyed rows in each of two months, including an extreme input. Winsorize clipped that input.","973375074755539,629958980658605" +ZScore,conditional_inference,guard_pass,guard_pass,"[{""case"":""filtered_batch_guard_pandas_polars"",""params"":{""columns"":[""x""]}}]","Fitted transform removes an extreme row; predict rejects the shortened batch on both engines. A batch with no filtered rows can score, but one prediction per input is not guaranteed for arbitrary inputs.",973375074755539 +Oversampling,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +Undersampling,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +MaxAbsScaler,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a"",""num_b"",""num_c""]}},{""case"":""mlflow_cross_job_pandas_polars"",""params"":{""columns"":[""x""],""model"":""linear_regression"",""rows_per_month"":20}}]","Saved full pipelines passed pandas and Polars; concrete MLflow/UC model versions replayed 20 keyed rows in each of two months, including an extreme input.","973375074755539,629958980658605" +MinMaxScaler,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a"",""num_b"",""num_c""]}},{""case"":""mlflow_cross_job_pandas_polars"",""params"":{""columns"":[""x""],""model"":""linear_regression"",""rows_per_month"":20}}]","Saved full pipelines passed pandas and Polars; concrete MLflow/UC model versions replayed 20 keyed rows in each of two months, including an extreme input.","973375074755539,629958980658605" +RobustScaler,inference_eligible,pass,pass,"[{""case"":""C1"",""params"":{""columns"":[""x"",""z""]}},{""case"":""mlflow_cross_job_pandas_polars"",""params"":{""columns"":[""x""],""model"":""linear_regression"",""rows_per_month"":20}}]","Saved full pipelines passed pandas and Polars; concrete MLflow/UC model versions replayed 20 keyed rows in each of two months, including an extreme input.","973375074755539,629958980658605" +StandardScaler,inference_eligible,pass,pass,"[{""case"":""R1"",""params"":{""columns"":[""x"",""z""]}},{""case"":""C2"",""params"":{""columns"":[""x"",""z""]}},{""case"":""mlflow_cross_job_pandas_polars"",""params"":{""columns"":[""x""],""model"":""linear_regression"",""rows_per_month"":20}}]","Saved full pipelines passed pandas and Polars; concrete MLflow/UC model versions replayed 20 keyed rows in each of two months, including an extreme input.","973375074755539,629958980658605" +Split,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +TrainTestSplitter,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +feature_target_split,train_only,targeted_tests_pass,not_applicable,,Existing train/split/row-effect integration tests passed (317 focused tests); node is not advertised for local batch inference., +DateFeatures,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""date_col""],""drop_original"":true}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +LagFeatures,unsupported,not_run,not_run,,Whole-frame model-input or temporal-context compatibility is unproven., +RollingAggregate,unsupported,not_run,not_run,,Whole-frame model-input or temporal-context compatibility is unproven., +GeneralTransformation,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_c""],""transformation"":""log""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +PowerTransformer,inference_eligible,pass,pass,"[{""case"":""R3"",""params"":{""columns"":[""x"",""z""]}}]",Full-pipeline fit/save/load/predict passed in five-model local test.,217135029658639 +SimpleTransformation,inference_eligible,pass,pass,"[{""case"":""node_audit_pandas_polars"",""params"":{""columns"":[""num_a""],""transformation"":""abs""}}]",Full-pipeline fit/save/load/predict passed on pandas and Polars with a bounded fixture; live serverless audit passed.,262581913302220 +count_vectorizer,unsupported,not_run,not_run,,Whole-frame model-input or temporal-context compatibility is unproven., +hashing_vectorizer,unsupported,not_run,not_run,,Whole-frame model-input or temporal-context compatibility is unproven., +sentence_embedder,optional_dependency,not_run,not_run,,Requires an optional runtime dependency and an isolated replay probe., +tfidf_vectorizer,unsupported,not_run,not_run,,Whole-frame model-input or temporal-context compatibility is unproven., +tokenizer,unsupported,not_run,not_run,,Whole-frame model-input or temporal-context compatibility is unproven., diff --git a/initiatives/spark_and_mlflow/08-sm24a-live-validation-report.md b/initiatives/spark_and_mlflow/08-sm24a-live-validation-report.md new file mode 100644 index 000000000..3df66bbdc --- /dev/null +++ b/initiatives/spark_and_mlflow/08-sm24a-live-validation-report.md @@ -0,0 +1,120 @@ +# SM-24a live validation report + +Status: completed for the documented small-data scope on 2026-09-23. This +report separates local proof from remote results. The +[plan](06-sm24a-live-validation-plan.md) states the accepted transport +boundary; the [62-ID matrix](07-sm24a-node-matrix.csv) keeps inapplicable and +untested nodes visible. + +## Local evidence + +- The SM-24a reader, training entry and five model configurations passed 29 + focused tests (one real Spark test skipped in the base environment). +- The requested-month read passed separately against real local Spark in the + repository's Linux/Java test environment: 1 passed. +- Ruff, Ty and `mkdocs build --strict` passed for the changed files/docs. +- Five fit/save/load/predict cases passed locally: R1 pandas linear regression, + R2 Polars random forest regression, C1 pandas logistic regression, C2 Polars + random forest classification, R3 pandas gradient boosting regression. + Eleven distinct preprocessing registration IDs appeared in those cases. + Their predictions also matched direct calls to the fitted estimators (exact + class labels; regression tolerance `1e-12`). The core unit suite passed + 3,911 tests with 71 optional skips. Separate targeted train-only and + inspection suites passed 317 tests. +- Another 30 inference-eligible registrations passed local fit/save/load/ + predict probes on both pandas and Polars (60 probe runs). Each probe used a + bounded, node-specific fixture and a nonempty fitted candidate state. This + verifies those configurations, not every parameter combination. +- The Delta reader limits returned row count before driver iteration, then + measures serialized decoded rows and local-frame memory. Spark wire framing + is opaque to this API; this is not an exact network-byte measurement. + +## Isolated Databricks resources + +- Profile: previously selected `skyulf` on + `https://dbc-45604623-c18b.cloud.databricks.com`. +- Schema: `workspace.skyulf_sm24a_20260923`, ID + `e756f7db-08eb-4bd0-a897-28a81396a550`. +- Workspace folder: + `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923`. +- Uploaded wheel: `skyulf_core-0.9.0-py3-none-any.whl`, SHA-256 + `fefdb71f020ee80975d507c8b55730e53e8c82d5206e3bd6eaa8cd967e07223b`. +- Uploaded notebook: `local_sm24a_job` in the same folder. +- Training parent run: `127884897177470`, task run `613571036409051`, + 900-second timeout, zero retries; **SUCCESS** after 142 seconds. +- Source tables: `workspace.skyulf_sm24a_20260923.skyulf_sm24a_train_source` + (1,000 rows, Delta version 0) and + `workspace.skyulf_sm24a_20260923.skyulf_sm24a_score_source` + (160 rows, two 80-row months, Delta version 0). +- Model versions: `skyulf_sm24a_r1`, `r2`, `c1`, `c2`, `r3` in the same schema, + each at concrete version `1`. The full name/digest/run ID receipt is retained + in `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/training_receipt.json` + and locally at `.cache/sm24a-training-receipt.json`. + +| Case | Engine | Model class | MLflow run ID | Pipeline SHA-256 | +| --- | --- | --- | --- | --- | +| R1 | pandas | LinearRegression | `c96af1092692454d9c32aba21694285b` | `1c1cc2f41e23f718d56d02f44245cb2121fff34a6b6af8eb569396fe4e81cfb7` | +| R2 | Polars | RandomForestRegressor | `61896c2ed4aa449faa2b474ce62dcbea` | `5854d1ec07026200381d28d68d12833b7db2c8e47590d9fe7b8678a8525e3da2` | +| C1 | pandas | LogisticRegression | `af5fe6ea6ef242c78b84cbd30a80bc41` | `ed0f38b8b7ccb8ae83f7d3358acb72fb036ea15093ca7e912894578b5e46dac5` | +| C2 | Polars | RandomForestClassifier | `25a0008472724cee8094009f14fafa6c` | `a78530cdcba46509f88aec4949fb998fea66cd1122c1bf2d1e4afb3e6467fc1c` | +| R3 | pandas | GradientBoostingRegressor | `19db554ff23147a0a5445587763c7453` | `53b68cf37ae56e85f4c538dfdb463aa035bfadde92d65987617b3ed67035fd94` | + +- Observed training runtime: `skyulf-core 0.9.0`, `mlflow 3.16.1`, + `pandas 2.2.3`, `polars 1.44.2`, `scikit-learn 1.6.1`. +- Separate scoring parent run: `217135029658639`, 900-second timeout, + zero retries; task `204469025040289`; **SUCCESS**. The Jobs API reported + 56 seconds of execution duration and 135 seconds of setup duration. All five + pinned version-1 models scored 80 January and 80 February rows from source + version 0. Each model-month output matched its training-job reference by + entity key; class labels matched exactly and probability rows summed to one. +- Independent replay/negative parent run: `242324305571657`, task + `1045750740187935`; **SUCCESS**. Jobs API execution duration: 134 seconds; + setup duration: 175 seconds. Repeating R1 January returned an identical + prediction frame and source/model diagnostics. Reordered or missing inputs, + changed source version, row/byte budget breaches, wrong engine, wrong + artifact kind and Spark runtime were each rejected before scoring. +- Per-node audit parent run: `262581913302220`, task `154157693596997`; + **SUCCESS**, 900-second timeout and zero retries. Jobs API execution duration: + 38 seconds; setup duration: 135 seconds. All remaining 30 inference-eligible + registrations passed an isolated fit/save/load/predict probe on both pandas + and Polars (60/60). The [62-ID matrix](07-sm24a-node-matrix.csv) now records + 41 inference-eligible IDs with live evidence, 11 train-only, two inspection, + two optional-dependency and six unsupported IDs. A passing fixture does not + claim universal parameter or source-schema compatibility. +- Registry negative/pinning parent run: `460312914130071`, task + `420698524557946`; **SUCCESS**, 900-second timeout and zero retries. Jobs + API execution duration: 75 seconds; setup duration: 215 seconds. An unknown + model version returned `registry_model_missing`. A disposable alias on R1 + moved from version 1 to newly registered test version 2 after preparation; + the prepared workflow still scored 80 January rows with concrete version 1 + and matched its reference. The alias was deleted in the job's `finally` + block. R1 version 2 remains as a test-owned registry record. + +The training job created exactly two test-owned Delta source tables, registered +five test UC model versions and returned reference predictions. No alias was +moved and no prediction table was written. The separate scoring job proved +cross-job prediction parity on two months; neither job rescored the other +month during a monthly request. Reference predictions came from the saved local +artifact before registration, not from an independent pre-package estimator. +The latter was checked separately in local tests. + +## Scope and follow-up + +The reader enforces a Spark-side `max_rows + 1` limit, then decoded +serialized-row and local-frame byte caps. The selected Spark iterator does +not expose actual wire bytes, and a single wide row may arrive before the +decoded-byte check. The [plan](06-sm24a-live-validation-plan.md) explicitly +accepts this boundary for small data; [SM-24d](OPEN_QUEUE.md) tracks a hard +transport budget if larger or wide-row sources require it. The test did not +publish predictions to a UC Delta table or deploy a Bundle. Those are SM-15L +and SM-20a respectively. Unsupported/optional nodes remain visible in the +matrix, and the probes do not certify every model/parameter combination. +## Subsequent audits + +The [scaler/outlier audit](09-sm24a-scaler-outlier-audit.md) refined four +row-filtering outlier registrations from the original `train_only` category to +`conditional_inference`; the current matrix has 41 inference-eligible, four +conditional and seven train-only registrations. The +[held-out metrics audit](10-sm24a-heldout-metrics-report.md) later logged +200-row test metrics in the same MLflow runs as five new test model versions. +The counts above describe the original audit snapshot. diff --git a/initiatives/spark_and_mlflow/09-sm24a-scaler-outlier-audit.md b/initiatives/spark_and_mlflow/09-sm24a-scaler-outlier-audit.md new file mode 100644 index 000000000..f1e84e2ca --- /dev/null +++ b/initiatives/spark_and_mlflow/09-sm24a-scaler-outlier-audit.md @@ -0,0 +1,29 @@ +# SM-24a scaler and outlier inference audit + +Status: completed on 2026-09-23 for the bounded pandas/Polars Databricks workflow. The executable probe is [`databricks_local_sm24a_scaler_outlier_audit.py`](../../skyulf-core/examples/databricks_local_sm24a_scaler_outlier_audit.py). This audit tests the existing implementation; it does not add a new inference endpoint or a Spark-native transform. + +## Result + +| Nodes | pandas | Polars | Inference behavior | +| --- | --- | --- | --- | +| MaxAbsScaler, MinMaxScaler, RobustScaler, StandardScaler | Passed | Passed | Apply fitted scaling state and return one prediction per input, including an extreme value. | +| Winsorize | Passed | Passed | Apply fitted percentile clipping and return one prediction per input. | +| IQR, ZScore, ManualBounds, EllipticEnvelope | Guard passed | Guard passed | An extreme value is filtered by the fitted transform; prediction raises a row-count error instead of silently returning fewer predictions. An input on which no row is filtered can still score. | + +The 62-ID matrix currently has 41 inference-eligible registrations, four conditional outlier registrations, seven train-only, two inspection, two optional-dependency and six unsupported registrations. Eight optional/unsupported registrations remain `not_run`; this audit does not claim they work in inference. + +`train_only` in the earlier node matrix was too coarse for the four filtering outlier nodes. They are fitted and applied during inference, but arbitrary batches cannot be promised one output per input. The [node matrix](07-sm24a-node-matrix.csv) now records their conditional inference behavior and the live guard evidence. + +## Evidence + +- Local regression gate: 219 focused outlier, row-contract and numeric tests passed. A separate saved-artifact probe fitted, saved, loaded and predicted all five row-preserving nodes on both engines (10/10); each returned three predictions, and Winsorize clipped `x=1000`. +- Databricks training parent run `973375074755539`, task `176846010524557`: **SUCCESS** with a 900-second timeout and zero retries. It read 1,000 training rows from `workspace.skyulf_sm24a_20260923.skyulf_sm24a_train_source` at Delta version 0. It created a test-only two-month scoring table `workspace.skyulf_sm24a_20260923.skyulf_sm24a_scaler_outlier_score_source` at Delta version 0, with 20 rows per month and one `x=1000` row in each month. +- The training job fitted and registered 10 separate linear-regression pipelines: five preprocessing nodes times two engines. Each model was registered under a test-only Unity Catalog name at concrete version 1; no alias was changed. The receipt with exact names, versions, digests, run IDs, metrics and reference predictions is in `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/scaler_receipt.json` and locally in `.cache/sm24a-scaler-receipt.json`. +- All four filtering outlier nodes removed the extreme row in their direct transform. `SkyulfPipeline.predict` rejected the shortened batch for each node and both engines (8/8 guarded cases) in the Databricks training job. The existing local row-contract test also checks that normal rows still predict. +- Independent scoring parent run `629958980658605`, task `1090605491396608`: **SUCCESS**. It loaded all 10 concrete model versions via the MLflow/Unity Catalog workflow and scored January and February separately. All 20 model-month cases retained all 20 entity keys, including the extreme key, and matched the training-job saved-artifact reference at absolute tolerance `1e-9`. This reference is a replay comparison, not an independent mathematical oracle. +- The new MLflow runs log `heldout_mae`, `heldout_rmse`, `heldout_r2`, engine and preprocessing. The tracking API confirmed these are present for the MaxAbsScaler/pandas run `d3a87c86c7e94f6ab907ab656736164f`; its held-out R2 was 0.9473 on this synthetic fixture. Metric presence was checked directly, not inferred from the receipt. +- Focused Ruff and Ty checks passed for the probe script. The live wheel was the previously validated `skyulf-core 0.9.0` wheel in the isolated SM-24a workspace folder. + +## Scope + +Here, "live" means a Databricks serverless **batch job** reading bounded Delta rows into a pandas or Polars local pipeline and loading a saved model through MLflow. It does not mean a Model Serving HTTP endpoint or distributed Spark-native FE. The latter remains separate work in the Spark node matrix. The test did not write a prediction Delta table, deploy a Bundle, or certify every parameter combination. Filtering outlier nodes require an explicit product policy if prediction must return a result for every row: keep and flag, clip, or reject the batch. The current behavior is rejection when any row is removed. diff --git a/initiatives/spark_and_mlflow/10-sm24a-heldout-metrics-report.md b/initiatives/spark_and_mlflow/10-sm24a-heldout-metrics-report.md new file mode 100644 index 000000000..9c6780f81 --- /dev/null +++ b/initiatives/spark_and_mlflow/10-sm24a-heldout-metrics-report.md @@ -0,0 +1,33 @@ +# SM-24a held-out metrics in the model MLflow run + +Status: completed on 2026-09-23 for the isolated small-data Databricks workflow. The [notebook](../../skyulf-core/examples/databricks_local_sm24a_job.py) now evaluates the saved local pipeline on the 200 rows reserved from each 1,000-row training source and logs the resulting metrics in the same MLflow run as its model artifact. The reusable calculation is `evaluate_local_holdout` in the local Databricks integration. + +## Split and metric contract + +- Source: `workspace.skyulf_sm24a_20260923.skyulf_sm24a_train_source`, Delta version 0. The bounded reader returns 1,000 rows ordered by `entity_id`; the first 800 are used for fit and the remaining 200 for held-out evaluation. The test labels are never inputs to prediction. The split is deterministic by key, neither randomized nor a true time split. +- The saved artifact predicts the raw held-out features through its recorded pandas or Polars engine. The evaluator does not refit feature engineering or the model. Regression logs `heldout_mae`, `heldout_rmse`, `heldout_r2`. Binary classification logs `heldout_accuracy`, `heldout_f1` for the model's second class, and `heldout_f1_weighted`. +- Within one `mlflow.start_run`, the notebook logs the source/split parameters and held-out metrics, then passes `run.info.run_id` to `log_local_model`. Registration uses the resulting `runs://model` URI and a concrete UC model version. No alias is moved. + +## Live results + +Training parent run `579498050611865`, task `209306932523734`: **SUCCESS**, 900-second timeout, zero retries. It used the existing version-0 source tables and registered new test-only `skyulf_sm24a_metrics_*` model names at version 1. The wheel SHA-256 is `3548c90bf34bae417716ad176c3ccfdb9d85d73b270999672c3a101f5971bdee`. + +| Case | Engine / model | MLflow run ID | 200-row held-out metrics | +| --- | --- | --- | --- | +| R1 | pandas / linear regression | `fc3fe38d14854198956d143415bb856e` | MAE 0.673; RMSE 0.819; R2 0.993 | +| R2 | Polars / random forest regression | `66c68cd3618f45ff95beed7c16bbb503` | MAE 20.379; RMSE 22.531; R2 -4.299 | +| C1 | pandas / logistic regression | `418d55e524954227b4d24d43d7090165` | Accuracy 0.710; binary F1 0.773; weighted F1 0.711 | +| C2 | Polars / random forest classification | `934ee10da4ea4182b9ae76d151136e19` | Accuracy 0.575; binary F1 0.706; weighted F1 0.538 | +| R3 | pandas / gradient boosting regression | `910362725ecc472c870beeed4e040890` | MAE 16.855; RMSE 19.438; R2 -2.944 | + +The Databricks tracking API confirmed, for **each** of the five finished runs, its held-out metric keys, `heldout_rows=200` parameter and `model` artifact directory. The UC registry API confirmed all five version-1 records were READY and each pointed to the matching `runs://model` URI. The full unrounded values, model digests and versions are in `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/metrics_r1/training_receipt.json` and local `.cache/sm24a-metrics-receipt.json`. + +Independent scoring parent run `1112210778543224`, task `655818910990971`: **SUCCESS**. It loaded the five new concrete model versions and scored the pinned version-0 monthly source. Each model returned all 80 January and 80 February entity keys; all 10 model-month outputs matched the training job's saved-artifact reference. This proves the new metered packages still load and score in a separate job. The reference is a replay comparison, not an independent model-quality oracle. + +The negative R2 values and the C2 classification scores show that some example models generalize poorly to this key-ordered held-out set. The logging contract works; these scores are **not** a model-quality approval for production. Model selection, representative splitting and promotion thresholds require separate decisions. Earlier SM-24a runs remain unchanged and do not gain metrics retroactively. + +## Validation and scope + +The focused local Databricks batch/five-model gate passed **14 tests, one optional skip**. A full Core test run reached **10,142 passed and 348 skipped**, with one unrelated failure: the optional SentenceEmbedder wrapped-Polars test attempted a Hugging Face download and the current sandbox denied network access (`WinError 10013`). The new evaluator's regression and classification tests passed on both pandas and Polars. Ruff, Ruff format and Ty passed for the changed Python files. + +This audit did not create a prediction Delta table, deploy a Bundle, change an alias, or test an HTTP serving endpoint. SM-15L remains the next monthly Delta-publication task. Its infrastructure test may use these pinned example models, but their held-out scores should be reviewed before any production promotion. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index bf62ce862..f9ce3e83e 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -6,18 +6,31 @@ Databricks serverless regression workflow passed. Latest user direction: working Databricks Bundle. Spark may handle table I/O in that first path; Spark FE/model execution and its Bundle option follow. SM-15L is reopened for monthly UC output; SM-18 remains parked. SM-26 local -MLflow packaging is complete; start with SM-25. After the first Bundle, SM-27 adds +MLflow packaging, SM-25 SDK preflight and SM-24a live local batch are complete; +start with SM-15L. After the first Bundle, SM-27 adds explicit full-history rescore and SM-22/SM-28 add optional monthly retraining with controlled candidate/champion promotion.** Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-16 and SM-26 are complete. Start SM-25 from +- SM-00 through SM-16, SM-24a, SM-25 and SM-26 are complete. Start SM-15L from [04-databricks-integration-plan.md](04-databricks-integration-plan.md). The first Bundle and its two-month table rehearsal are specified in [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). SM-26 added local artifact and MLflow packaging without cloud execution. The + SM-25 SDK adds immutable local workflow configuration, local/remote preflight, + explicit path or pinned registry artifact selection and caller-frame limits. + It has no separate FE node or model-family allowlist: the fitted local + pipeline's own prediction contract governs them. A representative sample can + be probed before job submission. SM-24a added versioned UC reads, bounded + local training and monthly pandas/Polars scoring. Its + [live report](08-sm24a-live-validation-report.md) records two isolated UC + source tables in `workspace.skyulf_sm24a_20260923`, five cross-job models, + replay/negative checks and the 62-ID preprocessing matrix. Local-result + Delta writes remain SM-15L; no prediction table or Bundle was created. + The current `max_bytes` limit measures decoded payload and local frame + memory, not exact Spark wire bytes; SM-24d tracks a hard transport budget. previous Spark-first direction is superseded. Preserve the later [NODE_SUPPORT.md](NODE_SUPPORT.md) inventory and [gap review](reports/2026-09-22-spark-databricks-gap-review.md). diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 5cc9967b5..87322fb35 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,12 +1,12 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00–SM-16 and SM-26 complete; SM-25 next. Target: 0.9.0.** +Updated: 2026-09-23. **SM-00–SM-16 and SM-24a/25/26 complete; SM-15L next. Target: 0.9.0.** First deliverable: pandas/Polars training and local batch on Databricks, then a working local-engine Bundle. Spark expansion follows that Bundle. SM-15L is reopened for monthly UC output; SM-18 and continuous streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-25. +and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-15L. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). SM-26 added a local MLflow package; no Bundle was generated or cloud job started. @@ -35,14 +35,15 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | | SM-16 | Gerçek Databricks kapısı | SM-15 | DONE | Selected serverless workflow passed; live evidence below | -| SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | WAIT | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | +| SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | READY | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | | SM-17 | Complete existing Spark node/model coverage | SM-20a | LATER | Resume only after the first local Bundle; preserve all inventoried gaps | | SM-18 | Backend/Canvas and legacy artifact bridge | SM-17 | PARKED | Capability UI/API, DAG contracts and existing deployment compatibility | | SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | -| SM-25 | Local-first config / SDK preflight | SM-26 | READY | Choose pandas/Polars, runtime, store and sink; reject incompatible local packages before jobs | -| SM-24a | Local training and bounded batch prediction | SM-25 | WAIT | Reuse fitted pandas/Polars pipeline and pinned MLflow model; no Spark FE/model dependency | +| SM-25 | Local-first config / SDK preflight | SM-26 | DONE | Immutable local config; pinned artifact load, bounded frame and actionable preflight; no node/model allowlist | +| SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | | SM-20a | First local-engine Bundle/template | SM-24a, verified SM-15L | WAIT | Generate, validate, deploy and run pandas/Polars train/monthly batch with pinned MLflow/UC model | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | +| SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | | SM-22 | Optional model validation and controlled promotion | SM-20a, current evaluation/registry | LATER | Pinned candidate/champion comparison, explicit version promotion and rollback | | SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | LATER | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | | SM-28 | Monthly retraining and challenger workflow | SM-20a, SM-22 | LATER | Label-aware schedule, leakage-safe training, candidate/champion report, explicit promotion, and independent pinned scoring job | @@ -68,12 +69,14 @@ in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). 1. **SM-26:** fitted pandas/Polars pipeline -> MLflow package -> same local predictions. 2. **SM-25:** config, pinned local artifact loading, limits and preflight. 3. **SM-24a:** local training and bounded local batch prediction in Databricks. + Its [live validation report](08-sm24a-live-validation-report.md) records two + source tables, five cross-job models and every preprocessing registration ID. 4. **SM-15L:** convert only final local predictions for guarded Spark Delta publication; each new month adds results while earlier months remain unchanged. 5. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle using the [two-month rehearsal](05-sm20-bundle-plan.md). 6. **After SM-20a:** SM-27 adds explicit `full_rebuild` alongside the default `period_update`; SM-22 then SM-28 add candidate/champion validation and optional monthly retraining. These are separate from monthly scoring. -7. **Later:** optional SM-24b/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. +7. **Later:** optional SM-24b/24d/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. SM-26 is the explicit packaging task added after the local-first MLflow discussion. It reuses the fitted local pipeline rather than requiring every FE node to gain a @@ -140,6 +143,60 @@ SM-17 requires the full tracked scope above. Some algorithms may need an explici alternative backend rather than an equivalent native Spark implementation; that decision must not hide missing support. SM-19 streaming remains optional and parked. +## SM-24a — 2026-09-23 local and Databricks validation, DONE + +- Added explicit bounded pandas/Polars training and a pinned UC Delta monthly + reader. Spark filters/projects/limits the source; saved local FE/model runs in + one Python process. This stage returns predictions and diagnostics, not a + Delta prediction table. The [local guide](../../docs/user_guide/databricks_local_sdk.md) + includes code and the decoded-byte boundary. +- Five pandas/Polars model packages trained and registered in isolated schema + `workspace.skyulf_sm24a_20260923`; an independent serverless scoring job + matched both 80-row months by key. Replay and negative cases passed. All 30 + additional inference-eligible preprocessing registrations passed on both + engines in a separate live audit, making 41 live-evidenced eligible IDs in + the [62-ID matrix](07-sm24a-node-matrix.csv). Train-only, inspection, + optional and unsupported IDs remain explicit. +- An unknown registry version failed preflight. A disposable alias moved to + R1 version 2 after preparation; the prepared predictor remained on version 1 + and returned the expected 80 rows. The alias was deleted. The full + [report](08-sm24a-live-validation-report.md) lists runs, versions, resources + and test results. +- A follow-up [scaler and outlier audit](09-sm24a-scaler-outlier-audit.md) + registered 10 pandas/Polars MLflow models with held-out metrics and passed + a separate two-month scoring replay. Four filtering outlier nodes reject + shortened prediction batches; Winsorize clips and preserves rows. +- A [200-row held-out metrics audit](10-sm24a-heldout-metrics-report.md) + logged regression MAE/RMSE/R2 and classification accuracy/F1 in the same + MLflow runs as five new test models. All five registered versions passed a + separate two-month scoring replay. R2/R3 had negative held-out R2; those + example models are not approved for production promotion. +- The Spark iterator does not expose actual wire-byte counts. `max_bytes` + bounds accepted decoded rows and local-frame memory; a very wide row can + arrive before rejection. [SM-24d](OPEN_QUEUE.md) retains the stronger + transport-budget option for wider or larger workloads. Next: SM-15L. + +## SM-25 — 2026-09-23 local SDK validation, DONE + +- Added frozen `LocalWorkflowConfig` with explicit runtime, pandas/Polars engine, + bounded caller frame or declared future UC source, local/portable artifact + selection, optional MLflow store URIs and return/declared future Delta sink. + Config parsing performs no remote call and rejects embedded URI credentials. +- Local preflight reports actionable config, source, sink, artifact, engine, + node-contract and model-contract issues. Optional read-only registry preparation + resolves an alias once, loads the concrete version, and checks package digest. + The SDK has no separate FE/model allowlist; a fitted SkyulfPipeline controls + local prediction. An optional representative-frame probe exercises that + actual path before submission. Inference input is capped by rows and bytes. +- After the allowlist correction, **20 local SDK tests passed**, including + pandas/Polars MinMaxScaler + random-forest replay. The combined isolated + MLflow SDK, local-package and registry gate passed **39/39**. + The broader Core unit run completed **3927 passed, 71 skipped** before that + narrow correction; Ruff, repository Ty and strict MkDocs passed after it. No + Databricks job, UC source adapter or Delta writer was added in SM-25. +- [Local-engine SDK guide](../../docs/user_guide/databricks_local_sdk.md). + Next: SM-24a local training and bounded batch workflow. + ## SM-26 — 2026-09-23 local packaging validation, DONE - Added a versioned, trusted local pipeline artifact with recorded pandas/Polars @@ -161,8 +218,8 @@ decision must not hide missing support. SM-19 streaming remains optional and par Pipeline unit regression: **385 passed, 2 skipped**. Focused Ruff and ty checks passed. No Databricks job or Delta writer was added in this task. - [MLflow model guide](../../docs/user_guide/mlflow_models.md) lists the tested - model families and the wheel, serving and Spark limits. Next: SM-25 config and - preflight, then SM-24a local Databricks batch workflow. + model families and the wheel, serving and Spark limits. This task handed off + to SM-25 and then SM-24a. ## SM-16 — 2026-09-22 local and live validation, DONE diff --git a/mkdocs.yml b/mkdocs.yml index ad7cff39c..72b04f937 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -80,6 +80,7 @@ nav: - MLflow Models (Development): user_guide/mlflow_models.md - MLflow Registry (Development): user_guide/mlflow_registry.md - Databricks Batch (Development): user_guide/databricks_batch.md + - Databricks Local SDK (Development): user_guide/databricks_local_sdk.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/skyulf-core/examples/databricks_local_sm24a_job.py b/skyulf-core/examples/databricks_local_sm24a_job.py new file mode 100644 index 000000000..976f0a0d8 --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm24a_job.py @@ -0,0 +1,406 @@ +# Databricks notebook source +"""One-time SM-24a training and separate monthly scoring validation job. + +This script creates only isolated test sources in the supplied schema. It does +not publish predictions or move a registry alias. The two stages are submitted +as separate serverless runs; scoring receives the training receipt explicitly. +""" + +from __future__ import annotations + +import json +import tempfile +from dataclasses import replace +from datetime import UTC, datetime +from importlib.metadata import version +from pathlib import Path +from typing import Any, cast + +import mlflow # ty: ignore[unresolved-import] +import numpy as np +import pandas as pd +import polars as pl + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import predict_local_pipeline +from skyulf.integrations.databricks import ( + InputSource, + LocalSourceSpec, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + PreflightError, + evaluate_local_holdout, + fit_local_workflow, + prepare_local_workflow, + read_local_source, + score_local_source, +) +from skyulf.integrations.mlflow.local_model import log_local_model +from skyulf.integrations.mlflow.registry import register_model + +SCHEMA = "workspace.skyulf_sm24a_20260923" +EXPERIMENT = "/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/experiment" +TRAIN_SOURCE = f"{SCHEMA}.skyulf_sm24a_train_source" +SCORE_SOURCE = f"{SCHEMA}.skyulf_sm24a_score_source" +STARTS = { + "2026-01": (datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 2, 1, tzinfo=UTC)), + "2026-02": (datetime(2026, 2, 1, tzinfo=UTC), datetime(2026, 3, 1, tzinfo=UTC)), +} + + +def _rows(count: int) -> pd.DataFrame: + """Generate deterministic numeric nulls, outliers, labels and categories.""" + positions = np.arange(count) + x = positions.astype("float64") / 12.0 + x[positions == 17] = 45.0 + z = np.sin(positions / 7.0) * 3.0 + 4.0 + z[positions % 19 == 0] = np.nan + clean_z = np.nan_to_num(z, nan=4.0) + return pd.DataFrame( + { + "x": x, + "z": z, + "city": np.array(["Vilnius", "Riga", "Tallinn"])[positions % 3], + "regression_target": 2.0 * x + clean_z + (positions % 3), + "classification_target": (((x % 3.0) + clean_z / 3.0) > 2.4).astype("int64"), + } + ) + + +def _source_spec( + table: str, source_version: int, month: str, columns: tuple[str, ...], *, rows: int +) -> LocalSourceSpec: + """Build one fixed snapshot/period request for a bounded local transfer.""" + start, end = STARTS[month] + return LocalSourceSpec( + table=table, + version=source_version, + period_start=start, + period_end=end, + row_keys=("entity_id",), + input_columns=columns, + max_rows=rows, + max_bytes=4_000_000, + ) + + +def _create_sources(spark) -> dict[str, int]: + """Create exactly two test-owned managed Delta tables once.""" + train = _rows(1_000) + train_rows = [ + ( + f"train-{index:04d}", + datetime(2026, 1, index % 28 + 1, tzinfo=UTC), + float(cast(float, row.x)), + None if pd.isna(row.z) else float(cast(float, row.z)), + str(row.city), + float(cast(float, row.regression_target)), + int(cast(int, row.classification_target)), + ) + for index, row in enumerate(train.itertuples(index=False)) + ] + spark.createDataFrame( + train_rows, + "entity_id string, event_time timestamp, x double, z double, city string, " + "regression_target double, classification_target long", + ).write.format("delta").saveAsTable(TRAIN_SOURCE) + score = _rows(160) + score_rows = [ + ( + f"score-{index:04d}", + datetime(2026, 1 if index < 80 else 2, index % 28 + 1, tzinfo=UTC), + float(cast(float, row.x)), + None if pd.isna(row.z) else float(cast(float, row.z)), + "Stockholm" if index in (0, 80) else str(row.city), + ) + for index, row in enumerate(score.itertuples(index=False)) + ] + spark.createDataFrame( + score_rows, + "entity_id string, event_time timestamp, x double, z double, city string", + ).write.format("delta").saveAsTable(SCORE_SOURCE) + return { + "train": int(spark.sql(f"DESCRIBE HISTORY {TRAIN_SOURCE}").select("version").first()[0]), + "score": int(spark.sql(f"DESCRIBE HISTORY {SCORE_SOURCE}").select("version").first()[0]), + } + + +def train( + spark, + cases: list, + *, + source_versions: dict[str, int] | None = None, + registration_prefix: str = "skyulf_sm24a_", +) -> dict: + """Fit five packages and register the model with its held-out metrics.""" + if source_versions is None: + source_versions = _create_sources(spark) + source = read_local_source( + spark, + _source_spec( + TRAIN_SOURCE, + source_versions["train"], + "2026-01", + ("x", "z", "city", "regression_target", "classification_target"), + rows=1_000, + ), + ) + if len(source) != 1_000 or source["entity_id"].nunique() != 1_000: + raise AssertionError("Training source membership is not the expected 1,000 keys.") + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + mlflow.set_experiment(EXPERIMENT) + receipt = {"source_versions": source_versions, "models": {}, "reference": {}} + with tempfile.TemporaryDirectory(prefix="skyulf-sm24a-") as directory: + for name, engine, model, target, columns, preprocessing in cases: + frame = source.loc[:, [*columns, target]] + native = pl.from_pandas(frame) if engine == "polars" else frame + training = native[:800] + heldout = native[800:] + if len(training) != 800 or len(heldout) != 200: + raise AssertionError("Expected exactly 800 train and 200 held-out rows.") + artifact_path = Path(directory) / name + artifact = fit_local_workflow( + {"preprocessing": preprocessing, "modeling": {"type": model}}, + SplitDataset(train=training, test=heldout), + target_column=target, + artifact_path=artifact_path, + max_rows=1_000, + max_bytes=4_000_000, + ) + heldout_metrics = evaluate_local_holdout(artifact, heldout, target_column=target) + receipt["reference"][name] = {} + for month in STARTS: + query = read_local_source( + spark, + _source_spec(SCORE_SOURCE, source_versions["score"], month, columns, rows=80), + ) + predicted = predict_local_pipeline(query.loc[:, list(columns)], artifact) + receipt["reference"][name][month] = { + key: [ + value.item() if isinstance(value, np.generic) else value + for value in predicted.iloc[index] + ] + for index, key in enumerate(query["entity_id"]) + } + with mlflow.start_run(run_name=f"sm24a-{registration_prefix}{name}") as run: + mlflow.log_params( + { + "fitted_engine": engine, + "model_type": model, + "target_column": target, + "training_rows": 800, + "heldout_rows": 200, + "source_table": TRAIN_SOURCE, + "source_version": source_versions["train"], + } + ) + mlflow.log_metrics(heldout_metrics) + model_uri = log_local_model( + artifact_path, + run_id=run.info.run_id, + artifact_path="model", + tracking_uri="databricks", + ) + registered_name = f"{SCHEMA}.{registration_prefix}{name.lower()}" + registered = register_model( + model_uri, + registered_name, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + receipt["models"][name] = { + "name": registered_name, + "version": str(registered.version), + "run_id": run.info.run_id, + "digest": artifact.manifest.pipeline_sha256, + "engine": engine, + "columns": columns, + "task": artifact.manifest.task, + "model_class": artifact.manifest.model_class, + "heldout_rows": 200, + "heldout_metrics": heldout_metrics, + } + receipt["runtime"] = { + name: version(name) + for name in ("skyulf-core", "mlflow", "pandas", "polars", "scikit-learn") + } + return receipt + + +def _expect_rejection(action, expected: str) -> str: + """Require a bounded negative case to fail with an actionable message.""" + try: + action() + except (PreflightError, ValueError) as exc: + if expected not in str(exc): + raise AssertionError(f"Expected {expected!r} in {type(exc).__name__}: {exc}") from exc + return type(exc).__name__ + raise AssertionError(f"Expected rejection containing {expected!r}.") + + +def score(spark, receipt: dict, *, audit_negative: bool = False) -> dict: + """Read two months from the pinned source and compare five registered models.""" + source_version = int(receipt["source_versions"]["score"]) + report = {"source_version": source_version, "cases": {}} + replay = None + for name, model in receipt["models"].items(): + config = LocalWorkflowConfig( + runtime="databricks", + engine=model["engine"], + source=InputSource( + kind="uc_table", + table=SCORE_SOURCE, + version=source_version, + max_rows=80, + max_bytes=4_000_000, + ), + model=ModelSelection( + kind="local_pipeline", + name=model["name"], + version=model["version"], + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + sink=OutputSink(kind="return_frame"), + ) + prepared = prepare_local_workflow(config) + if prepared.preflight.model_digest != model["digest"]: + raise AssertionError(f"{name}: registry digest differs from training receipt.") + report["cases"][name] = {} + for month in STARTS: + result = score_local_source( + spark, + _source_spec(SCORE_SOURCE, source_version, month, tuple(model["columns"]), rows=80), + prepared, + ) + actual = result.predictions + expected = receipt["reference"][name][month] + if set(actual["entity_id"]) != set(expected): + raise AssertionError(f"{name}: {month} membership differs from reference.") + output_columns = [str(column) for column in actual.columns if column != "entity_id"] + for _, row in actual.iterrows(): + values = expected[row["entity_id"]] + if model["task"] == "classification" and row["prediction"] != values[0]: + raise AssertionError(f"{name}: class label differs for {row['entity_id']}.") + for position, column in enumerate(output_columns): + if column == "prediction" and model["task"] == "classification": + continue + if not np.isclose( + float(row[column]), float(values[position]), rtol=0, atol=1e-9 + ): + raise AssertionError(f"{name}: {column} differs for {row['entity_id']}.") + if model["task"] == "classification": + np.testing.assert_allclose( + actual[ + [ + column + for column in actual.columns + if str(column).startswith("probability_") + ] + ].sum(axis=1), + 1.0, + rtol=0, + atol=1e-9, + ) + report["cases"][name][month] = { + **result.diagnostics, + "reference_match": True, + "row_count": len(actual), + } + if name == "R1" and month == "2026-01": + replay = (prepared, config, result) + if audit_negative: + if replay is None: + raise AssertionError("The R1 January replay fixture was not scored.") + prepared, config, first = replay + model = receipt["models"]["R1"] + spec = _source_spec( + SCORE_SOURCE, source_version, "2026-01", tuple(model["columns"]), rows=80 + ) + second = score_local_source(spark, spec, prepared) + pd.testing.assert_frame_equal(first.predictions, second.predictions) + if first.diagnostics != second.diagnostics: + raise AssertionError("The same request changed its model/source identity.") + report["replay"] = {"case": "R1", "month": "2026-01", "identical": True} + report["negative_cases"] = { + "reordered_inputs": _expect_rejection( + lambda: score_local_source( + spark, replace(spec, input_columns=("z", "x")), prepared + ), + "raw column order", + ), + "missing_input": _expect_rejection( + lambda: score_local_source(spark, replace(spec, input_columns=("x",)), prepared), + "raw column order", + ), + "changed_source_version": _expect_rejection( + lambda: score_local_source(spark, replace(spec, version=1), prepared), + "pinned Delta table and version", + ), + "over_rows": _expect_rejection( + lambda: score_local_source(spark, replace(spec, max_rows=1), prepared), + "max_rows", + ), + "over_bytes": _expect_rejection( + lambda: score_local_source(spark, replace(spec, max_bytes=1), prepared), + "max_bytes", + ), + "wrong_engine": _expect_rejection( + lambda: prepare_local_workflow(config.model_copy(update={"engine": "polars"})), + "engine_mismatch", + ), + "wrong_artifact_kind": _expect_rejection( + lambda: prepare_local_workflow( + config.model_copy( + update={ + "model": ModelSelection( + kind="portable_bundle", + name=model["name"], + version=model["version"], + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + } + ) + ), + "registry_or_artifact_invalid", + ), + "spark_runtime": _expect_rejection( + lambda: prepare_local_workflow(config.model_copy(update={"runtime": "spark"})), + "runtime_unsupported", + ), + } + report["runtime"] = { + name: version(name) + for name in ("skyulf-core", "mlflow", "pandas", "polars", "scikit-learn") + } + return report + + +runtime_dbutils: Any = globals().get("dbutils") +runtime_spark: Any = globals().get("spark") +if runtime_dbutils is not None and runtime_spark is not None: + runtime_dbutils.widgets.text("stage", "train") + runtime_dbutils.widgets.text("payload", "") + stage = runtime_dbutils.widgets.get("stage") + payload = json.loads(runtime_dbutils.widgets.get("payload")) + if stage == "train": + result = train(runtime_spark, payload["cases"]) + elif stage == "train_existing": + result = train( + runtime_spark, + payload["cases"], + source_versions=payload["source_versions"], + registration_prefix="skyulf_sm24a_metrics_", + ) + elif stage == "score": + result = score( + runtime_spark, + json.loads(Path(payload["receipt_path"]).read_text(encoding="utf-8")), + audit_negative=bool(payload.get("audit_negative", False)), + ) + else: + raise ValueError("stage must be train or score.") + runtime_dbutils.notebook.exit(json.dumps(result, default=str)) diff --git a/skyulf-core/examples/databricks_local_sm24a_node_audit.py b/skyulf-core/examples/databricks_local_sm24a_node_audit.py new file mode 100644 index 000000000..f79e6fe8e --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm24a_node_audit.py @@ -0,0 +1,129 @@ +# Databricks notebook source +"""Probe each remaining local FE registration with a saved full pipeline. + +Every candidate is attempted independently on pandas and Polars. Failures +remain visible; a passing fixture is evidence for that configuration only. +""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import polars as pl + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import predict_local_pipeline +from skyulf.integrations.databricks import fit_local_workflow + + +def _fixture() -> pd.DataFrame: + """Provide bounded numeric, missing, categorical, geo and date source rows.""" + rng = np.random.default_rng(42) + count = 80 + a = rng.normal(0, 1, count) + b = rng.normal(5, 2, count) + missing = rng.normal(0, 1, count) + missing[::11] = np.nan + cat_a = rng.choice(["red", "green", "blue"], count) + return pd.DataFrame( + { + "num_a": a, + "num_b": b, + "num_c": rng.exponential(1, count) + 0.1, + "with_missing": missing, + "cat_a": cat_a, + "cat_b": rng.choice(["x", "y", "z"], count), + "cat_low": cat_a, + "cat_high": rng.choice([f"h{index}" for index in range(20)], count), + "lat1": rng.uniform(40, 41, count), + "lon1": rng.uniform(-74, -73, count), + "lat2": rng.uniform(34, 35, count), + "lon2": rng.uniform(-118, -117, count), + "date_col": pd.date_range("2026-01-01", periods=count, freq="D", tz="UTC"), + "target": ((a + b) > 5).astype("int64"), + } + ) + + +def _raw_columns(node: str, params: dict[str, Any]) -> list[str]: + """Include the candidate's real input columns and stable numeric controls.""" + needed = {"num_a", "num_b", "num_c"} + needed.update(params.get("columns", [])) + for key in ("lat1_col", "lon1_col", "lat2_col", "lon2_col"): + if params.get(key): + needed.add(params[key]) + for operation in params.get("operations", []): + needed.update(operation.get("input_columns", [])) + if node == "DateFeatures": + needed.add("date_col") + return sorted(needed) + + +def audit(configs: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: + """Fit, save, reload and predict each bounded candidate on both engines.""" + source = _fixture() + report: dict[str, dict[str, Any]] = {} + with tempfile.TemporaryDirectory(prefix="skyulf-sm24a-nodes-") as directory: + for node, params in configs.items(): + report[node] = {} + columns = _raw_columns(node, params) + for engine in ("pandas", "polars"): + try: + frame = source.loc[:, [*columns, "target"]] + native = pl.from_pandas(frame) if engine == "polars" else frame + steps = [ + {"name": "candidate", "transformer": node, "params": params}, + { + "name": "remaining_categories", + "transformer": "OneHotEncoder", + "params": {"handle_unknown": "ignore"}, + }, + ] + artifact = fit_local_workflow( + { + "preprocessing": steps, + "modeling": { + "type": "random_forest_classifier", + "params": {"n_estimators": 8, "max_depth": 4, "n_jobs": 1}, + }, + }, + SplitDataset(train=native[:64], test=native[64:]), + target_column="target", + artifact_path=Path(directory) / f"{node}-{engine}", + max_rows=80, + max_bytes=2_000_000, + ) + fitted = artifact.pipeline.feature_engineer.fitted_steps[0]["artifact"] + if fitted is None or (isinstance(fitted, dict) and not fitted): + raise ValueError("Candidate produced an empty fitted artifact.") + query = source.loc[72:79, columns] + result = predict_local_pipeline(query, artifact) + if len(result) != len(query) or result["prediction"].isna().any(): + raise ValueError("Prediction did not preserve all requested rows.") + report[node][engine] = { + "status": "pass", + "rows": len(result), + "raw_columns": columns, + "feature_columns": artifact.manifest.feature_columns, + } + except Exception as exc: # noqa: BLE001 - the audit records each candidate failure + report[node][engine] = { + "status": "fail", + "error": f"{type(exc).__name__}: {exc}"[:400], + "raw_columns": columns, + } + return report + + +runtime_dbutils: Any = globals().get("dbutils") +if runtime_dbutils is not None: + runtime_dbutils.widgets.text("config_path", "") + source_path = Path(runtime_dbutils.widgets.get("config_path")) + runtime_dbutils.notebook.exit( + json.dumps(audit(json.loads(source_path.read_text(encoding="utf-8")))) + ) diff --git a/skyulf-core/examples/databricks_local_sm24a_registry_probe.py b/skyulf-core/examples/databricks_local_sm24a_registry_probe.py new file mode 100644 index 000000000..d4b0b428d --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm24a_registry_probe.py @@ -0,0 +1,134 @@ +# Databricks notebook source +"""Verify unknown-version rejection and alias pinning on test-owned UC models.""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, cast + +import mlflow # ty: ignore[unresolved-import] +import numpy as np + +from skyulf.integrations.databricks import ( + InputSource, + LocalSourceSpec, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + PreflightError, + prepare_local_workflow, + score_local_source, +) +from skyulf.integrations.mlflow.registry import register_model + +RECEIPT = Path( + "/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/training_receipt.json" +) +SOURCE = "workspace.skyulf_sm24a_20260923.skyulf_sm24a_score_source" +ALIAS = "sm24a_pinning_probe" + + +def _config(model: dict[str, Any], source_version: int, **selector: str) -> LocalWorkflowConfig: + """Keep all decisions except the registry selector identical across probes.""" + return LocalWorkflowConfig( + runtime="databricks", + engine=model["engine"], + source=InputSource( + kind="uc_table", + table=SOURCE, + version=source_version, + max_rows=80, + max_bytes=4_000_000, + ), + model=ModelSelection( + kind="local_pipeline", + name=model["name"], + tracking_uri="databricks", + registry_uri="databricks-uc", + **selector, + ), + sink=OutputSink(kind="return_frame"), + ) + + +def probe(spark: Any) -> dict[str, Any]: + """Change a disposable alias while retaining the prepared concrete version.""" + receipt = json.loads(RECEIPT.read_text(encoding="utf-8")) + model = receipt["models"]["R1"] + source_version = int(receipt["source_versions"]["score"]) + try: + prepare_local_workflow(_config(model, source_version, version="99999")) + except PreflightError as exc: + unknown_version = tuple(issue.code for issue in exc.result.issues) + if unknown_version != ("registry_model_missing",): + raise AssertionError(f"Unexpected unknown-version result: {unknown_version}") from exc + else: + raise AssertionError("An unknown UC model version was accepted.") + + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + client = mlflow.MlflowClient(tracking_uri="databricks", registry_uri="databricks-uc") + new_version = register_model( + f"runs:/{model['run_id']}/model", + model["name"], + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if str(new_version.version) == model["version"]: + raise AssertionError("The test alias needs two different concrete versions.") + + client.set_registered_model_alias(model["name"], ALIAS, model["version"]) + try: + prepared = prepare_local_workflow(_config(model, source_version, alias=ALIAS)) + if prepared.preflight.model_version != model["version"]: + raise AssertionError("Alias did not initially resolve to the first version.") + client.set_registered_model_alias(model["name"], ALIAS, str(new_version.version)) + moved = client.get_model_version_by_alias(model["name"], ALIAS) + if str(moved.version) != str(new_version.version): + raise AssertionError("The disposable test alias did not move.") + result = score_local_source( + spark, + LocalSourceSpec( + table=SOURCE, + version=source_version, + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + row_keys=("entity_id",), + input_columns=tuple(model["columns"]), + max_rows=80, + max_bytes=4_000_000, + ), + prepared, + ) + expected = receipt["reference"]["R1"]["2026-01"] + if len(result.predictions) != len(expected): + raise AssertionError("Alias probe changed row membership.") + for row in result.predictions.itertuples(index=False): + if row.entity_id not in expected or not np.isclose( + float(cast(Any, row.prediction)), + float(expected[row.entity_id][0]), + rtol=0, + atol=1e-9, + ): + raise AssertionError(f"Pinned prediction changed for {row.entity_id}.") + if result.diagnostics["model_version"] != model["version"]: + raise AssertionError("Prepared workflow followed the moving alias.") + return { + "unknown_version": unknown_version[0], + "alias_initial_version": model["version"], + "alias_moved_version": str(new_version.version), + "prepared_version": result.diagnostics["model_version"], + "reference_match": True, + "row_count": len(result.predictions), + "temporary_alias_deleted": True, + } + finally: + client.delete_registered_model_alias(model["name"], ALIAS) + + +runtime_dbutils: Any = globals().get("dbutils") +runtime_spark: Any = globals().get("spark") +if runtime_dbutils is not None and runtime_spark is not None: + runtime_dbutils.notebook.exit(json.dumps(probe(runtime_spark))) diff --git a/skyulf-core/examples/databricks_local_sm24a_scaler_outlier_audit.py b/skyulf-core/examples/databricks_local_sm24a_scaler_outlier_audit.py new file mode 100644 index 000000000..f938ff67b --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm24a_scaler_outlier_audit.py @@ -0,0 +1,288 @@ +# Databricks notebook source +"""Replay local scaler and outlier pipelines through MLflow on Databricks. + +The train stage reads the existing isolated SM-24a source and creates one +additional test-only scoring table. The score stage runs in a separate job, +loads concrete Unity Catalog model versions, and compares keyed predictions. +""" + +from __future__ import annotations + +import json +import tempfile +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, cast + +import mlflow # ty: ignore[unresolved-import] +import numpy as np +import pandas as pd +import polars as pl +from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import predict_local_pipeline +from skyulf.integrations.databricks import ( + InputSource, + LocalSourceSpec, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + fit_local_workflow, + prepare_local_workflow, + read_local_source, + score_local_source, +) +from skyulf.integrations.mlflow.local_model import log_local_model +from skyulf.integrations.mlflow.registry import register_model +from skyulf.pipeline import SkyulfPipeline + +SCHEMA = "workspace.skyulf_sm24a_20260923" +EXPERIMENT = "/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/experiment" +TRAIN_SOURCE = f"{SCHEMA}.skyulf_sm24a_train_source" +SCORE_SOURCE = f"{SCHEMA}.skyulf_sm24a_scaler_outlier_score_source" +PERIODS = { + "2026-01": (datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 2, 1, tzinfo=UTC)), + "2026-02": (datetime(2026, 2, 1, tzinfo=UTC), datetime(2026, 3, 1, tzinfo=UTC)), +} +NODES = ("MaxAbsScaler", "MinMaxScaler", "RobustScaler", "StandardScaler", "Winsorize") +FILTER_NODES = ("IQR", "ZScore", "ManualBounds", "EllipticEnvelope") + + +def _source( + table: str, version: int, month: str, columns: tuple[str, ...], rows: int +) -> LocalSourceSpec: + """Pin the Delta snapshot, month, raw column order, and driver budget.""" + start, end = PERIODS[month] + return LocalSourceSpec( + table=table, + version=version, + period_start=start, + period_end=end, + row_keys=("entity_id",), + input_columns=columns, + max_rows=rows, + max_bytes=4_000_000, + ) + + +def _create_score_source(spark: Any) -> int: + """Create a test-only two-month source containing one extreme row per month.""" + rows = [ + ( + f"probe-{month}-{index:02d}", + datetime(2026, month, index % 20 + 1, tzinfo=UTC), + 1000.0 if index == 0 else float(index), + ) + for month in (1, 2) + for index in range(20) + ] + spark.createDataFrame(rows, "entity_id string, event_time timestamp, x double").write.format( + "delta" + ).saveAsTable(SCORE_SOURCE) + return int(spark.sql(f"DESCRIBE HISTORY {SCORE_SOURCE}").select("version").first()[0]) + + +def _filter_probes() -> dict[str, dict[str, str]]: + """Require row-filtering outlier nodes to reject a shortened prediction batch.""" + report: dict[str, dict[str, str]] = {} + train = pd.DataFrame({"x": np.arange(100, dtype="float64")}) + train["target"] = 2 * train["x"] + 1 + query = pd.DataFrame({"x": [20.0, 1000.0, 40.0]}) + for node in FILTER_NODES: + report[node] = {} + params: dict[str, Any] = {"columns": ["x"]} + if node == "ManualBounds": + params["bounds"] = {"x": {"lower": 0, "upper": 99}} + if node == "EllipticEnvelope": + params["random_state"] = 42 + config = { + "preprocessing": [{"name": "outliers", "transformer": node, "params": params}], + "modeling": {"type": "linear_regression"}, + } + for engine in ("pandas", "polars"): + native = train if engine == "pandas" else pl.from_pandas(train) + native_query = query if engine == "pandas" else pl.from_pandas(query) + pipeline = SkyulfPipeline(config) + pipeline.fit(native, target_column="target") + if len(pipeline.feature_engineer.transform(native_query)) != 2: + raise AssertionError(f"{node}/{engine}: fixture did not filter the outlier.") + try: + pipeline.predict(native_query) + except ValueError as exc: + if "outliers" not in str(exc) or "row count" not in str(exc): + raise AssertionError(f"{node}/{engine}: wrong rejection: {exc}") from exc + report[node][engine] = "rejected_filtered_batch" + else: + raise AssertionError(f"{node}/{engine}: silently scored a shortened batch.") + return report + + +def train(spark: Any) -> dict[str, Any]: + """Train ten small saved pipelines and log heldout metrics beside each model.""" + train_version = int(spark.sql(f"DESCRIBE HISTORY {TRAIN_SOURCE}").select("version").first()[0]) + score_version = _create_score_source(spark) + source = read_local_source( + spark, _source(TRAIN_SOURCE, train_version, "2026-01", ("x", "regression_target"), 1000) + ) + if len(source) != 1000: + raise AssertionError("Training source was not the expected 1,000 rows.") + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + mlflow.set_experiment(EXPERIMENT) + receipt: dict[str, Any] = { + "train_version": train_version, + "score_version": score_version, + "models": {}, + "reference": {}, + "filter_probes": _filter_probes(), + } + with tempfile.TemporaryDirectory(prefix="skyulf-sm24a-scaler-") as directory: + for node in NODES: + for engine in ("pandas", "polars"): + name = f"{node.lower()}_{engine}" + native = source.loc[:, ["x", "regression_target"]] + if engine == "polars": + native = pl.from_pandas(native) + artifact_path = Path(directory) / name + artifact = fit_local_workflow( + { + "preprocessing": [ + {"name": "feature", "transformer": node, "params": {"columns": ["x"]}} + ], + "modeling": {"type": "linear_regression"}, + }, + SplitDataset(train=native[:800], test=native[800:]), + target_column="regression_target", + artifact_path=artifact_path, + max_rows=1000, + max_bytes=4_000_000, + ) + heldout = source.iloc[800:] + predicted = predict_local_pipeline(heldout.loc[:, ["x"]], artifact)["prediction"] + actual = heldout["regression_target"].to_numpy() + metrics = { + "heldout_mae": float(mean_absolute_error(actual, predicted)), + "heldout_rmse": float(np.sqrt(mean_squared_error(actual, predicted))), + "heldout_r2": float(r2_score(actual, predicted)), + } + receipt["reference"][name] = {} + for month in PERIODS: + query = read_local_source( + spark, _source(SCORE_SOURCE, score_version, month, ("x",), 20) + ) + values = predict_local_pipeline(query.loc[:, ["x"]], artifact)["prediction"] + receipt["reference"][name][month] = dict( + zip(query["entity_id"], values.tolist(), strict=True) + ) + if node == "Winsorize": + probe = pd.DataFrame({"x": [1000.0]}) + clipped = artifact.pipeline.feature_engineer.transform( + probe if engine == "pandas" else pl.from_pandas(probe) + ) + if ( + float(clipped["x"].iloc[0] if engine == "pandas" else clipped["x"][0]) + >= 1000 + ): + raise AssertionError( + f"{name}: fitted Winsorize bounds did not clip the outlier." + ) + with mlflow.start_run(run_name=f"sm24a-{name}") as run: + mlflow.log_params({"engine": engine, "preprocessing": node, "train_rows": 800}) + mlflow.log_metrics(metrics) + model_uri = log_local_model( + artifact_path, + run_id=run.info.run_id, + artifact_path="model", + tracking_uri="databricks", + ) + registered_name = f"{SCHEMA}.skyulf_sm24a_audit_{name}" + registered = register_model( + model_uri, + registered_name, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + receipt["models"][name] = { + "node": node, + "engine": engine, + "name": registered_name, + "version": str(registered.version), + "run_id": run.info.run_id, + "digest": artifact.manifest.pipeline_sha256, + "metrics": metrics, + } + return receipt + + +def score(spark: Any, receipt: dict[str, Any]) -> dict[str, Any]: + """Load registered versions in another job and replay both pinned months.""" + version = int(receipt["score_version"]) + report: dict[str, Any] = {"score_version": version, "cases": {}} + for name, model in receipt["models"].items(): + config = LocalWorkflowConfig( + runtime="databricks", + engine=model["engine"], + source=InputSource( + kind="uc_table", + table=SCORE_SOURCE, + version=version, + max_rows=20, + max_bytes=4_000_000, + ), + model=ModelSelection( + kind="local_pipeline", + name=model["name"], + version=model["version"], + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + sink=OutputSink(kind="return_frame"), + ) + prepared = prepare_local_workflow(config) + if prepared.preflight.model_digest != model["digest"]: + raise AssertionError(f"{name}: loaded model digest differs from training.") + report["cases"][name] = {} + for month in PERIODS: + result = score_local_source( + spark, _source(SCORE_SOURCE, version, month, ("x",), 20), prepared + ) + predictions = result.predictions + expected = receipt["reference"][name][month] + if set(predictions["entity_id"]) != set(expected): + raise AssertionError(f"{name}/{month}: source row keys changed.") + for row in predictions.itertuples(index=False): + if not np.isclose( + cast(float, row.prediction), + cast(float, expected[row.entity_id]), + rtol=0, + atol=1e-9, + ): + raise AssertionError(f"{name}/{month}: prediction changed for {row.entity_id}.") + report["cases"][name][month] = { + "rows": len(predictions), + "reference_match": True, + "outlier_predicted": any("-00" in key for key in predictions["entity_id"]), + "model_version": result.diagnostics["model_version"], + } + return report + + +runtime_dbutils: Any = globals().get("dbutils") +runtime_spark: Any = globals().get("spark") +if runtime_dbutils is not None and runtime_spark is not None: + runtime_dbutils.widgets.text("stage", "train") + runtime_dbutils.widgets.text("receipt_path", "") + stage = runtime_dbutils.widgets.get("stage") + if stage == "train": + output = train(runtime_spark) + elif stage == "score": + output = score( + runtime_spark, + json.loads( + Path(runtime_dbutils.widgets.get("receipt_path")).read_text(encoding="utf-8") + ), + ) + else: + raise ValueError("stage must be train or score.") + runtime_dbutils.notebook.exit(json.dumps(output, default=str)) diff --git a/skyulf-core/skyulf/integrations/databricks/__init__.py b/skyulf-core/skyulf/integrations/databricks/__init__.py index 8c22cd540..510f2cb56 100644 --- a/skyulf-core/skyulf/integrations/databricks/__init__.py +++ b/skyulf-core/skyulf/integrations/databricks/__init__.py @@ -1,5 +1,45 @@ """Optional Databricks batch and Delta integrations.""" from .batch import BatchResult, BatchSpec, run_batch +from .local_batch import ( + LocalScoreResult, + LocalSourceSpec, + evaluate_local_holdout, + fit_local_workflow, + read_local_source, + score_local_source, +) +from .local_sdk import ( + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + PreflightError, + PreflightIssue, + PreflightResult, + PreparedLocalWorkflow, + preflight_local, + prepare_local_workflow, +) -__all__ = ["BatchResult", "BatchSpec", "run_batch"] +__all__ = [ + "BatchResult", + "BatchSpec", + "InputSource", + "LocalWorkflowConfig", + "LocalScoreResult", + "LocalSourceSpec", + "ModelSelection", + "OutputSink", + "PreflightError", + "PreflightIssue", + "PreflightResult", + "PreparedLocalWorkflow", + "evaluate_local_holdout", + "fit_local_workflow", + "preflight_local", + "prepare_local_workflow", + "read_local_source", + "run_batch", + "score_local_source", +] diff --git a/skyulf-core/skyulf/integrations/databricks/local_batch.py b/skyulf-core/skyulf/integrations/databricks/local_batch.py new file mode 100644 index 000000000..791990612 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_batch.py @@ -0,0 +1,251 @@ +"""Bounded Delta reads feeding whole-frame pandas or Polars workflows. + +Spark only selects a pinned, filtered source snapshot. Fitted feature +engineering and model prediction stay on the recorded local engine. +""" + +from __future__ import annotations + +import math +import pickle +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +import pandas as pd +import polars as pl +from sklearn.metrics import ( + accuracy_score, + f1_score, + mean_absolute_error, + mean_squared_error, + r2_score, +) + +from ...data.dataset import SplitDataset +from ...inference.local_pipeline import ( + LocalPipelineArtifact, + load_local_pipeline, + predict_local_pipeline, + save_local_pipeline, +) +from ...pipeline import SkyulfPipeline +from ._contracts import column_name, table_name +from .local_sdk import PreparedLocalWorkflow + + +@dataclass(frozen=True, slots=True, kw_only=True) +class LocalSourceSpec: + """Pin one monthly UC read and its driver-side resource budget.""" + + table: str + version: int + period_start: datetime + period_end: datetime + row_keys: tuple[str, ...] + input_columns: tuple[str, ...] + max_rows: int + max_bytes: int + period_column: str = "event_time" + business_timezone: str = "UTC" + + def __post_init__(self) -> None: + """Reject mutable or ambiguous requests before Spark access.""" + table_name(self.table) + if type(self.version) is not int or self.version < 0: + raise ValueError("version must be a nonnegative Delta snapshot version.") + for name in ("period_start", "period_end"): + value = getattr(self, name) + if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware.") + if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( + tzinfo=None + ): + raise ValueError(f"{name} is not a valid local instant.") + if self.period_start >= self.period_end: + raise ValueError("period_start must precede period_end.") + for name in (*self.row_keys, *self.input_columns, self.period_column): + column_name(name) + if not self.row_keys or not self.input_columns: + raise ValueError("row_keys and input_columns must be nonempty.") + names = [*self.row_keys, *self.input_columns, self.period_column] + if len({name.lower() for name in names}) != len(names): + raise ValueError("Row keys, input columns and period column must be distinct.") + if type(self.max_rows) is not int or self.max_rows <= 0: + raise ValueError("max_rows must be positive.") + if type(self.max_bytes) is not int or self.max_bytes <= 0: + raise ValueError("max_bytes must be positive.") + try: + ZoneInfo(self.business_timezone) + except (TypeError, ValueError, ZoneInfoNotFoundError) as exc: + raise ValueError("business_timezone must name an IANA timezone.") from exc + + +@dataclass(frozen=True, slots=True) +class LocalScoreResult: + """Return predictions with source and model identity for a caller-owned sink.""" + + predictions: pd.DataFrame + diagnostics: dict[str, str | int] + + +def _frame_bytes(frame: pd.DataFrame | pl.DataFrame) -> int: + """Count the actual local frame allocation used for the memory guard.""" + if isinstance(frame, pd.DataFrame): + return int(frame.memory_usage(index=True, deep=True).sum()) + return int(frame.estimated_size()) + + +def fit_local_workflow( + config: dict[str, Any], + data: SplitDataset, + *, + target_column: str, + artifact_path: str | Path, + max_rows: int, + max_bytes: int, +) -> LocalPipelineArtifact: + """Fit an explicit bounded split and save the existing full-pipeline format.""" + if not isinstance(data, SplitDataset): + raise TypeError("Training requires an explicit SplitDataset.") + if not target_column or type(target_column) is not str: + raise ValueError("target_column must be nonempty.") + if type(max_rows) is not int or max_rows <= 0: + raise ValueError("max_rows must be positive.") + if type(max_bytes) is not int or max_bytes <= 0: + raise ValueError("max_bytes must be positive.") + frames = (data.train, data.test, data.validation) + if any( + frame is not None and not isinstance(frame, pd.DataFrame | pl.DataFrame) for frame in frames + ): + raise TypeError("Training splits must be pandas or Polars DataFrames.") + present = [frame for frame in frames if isinstance(frame, pd.DataFrame | pl.DataFrame)] + if sum(len(frame) for frame in present) > max_rows: + raise ValueError("Training input exceeds max_rows.") + if sum(_frame_bytes(frame) for frame in present) > max_bytes: + raise ValueError("Training input exceeds max_bytes.") + pipeline = SkyulfPipeline(config) + pipeline.fit(data, target_column=target_column) + save_local_pipeline(pipeline, artifact_path) + return load_local_pipeline(artifact_path) + + +def evaluate_local_holdout( + artifact: LocalPipelineArtifact, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, +) -> dict[str, float]: + """Measure a saved local pipeline on labeled rows excluded from fitting. + + The caller owns the split. This function never fits preprocessing or a model; + it predicts with the loaded artifact and records only held-out metrics. + Binary F1 uses the artifact's second class as the positive label. + """ + if not isinstance(artifact, LocalPipelineArtifact): + raise TypeError("artifact must be a LocalPipelineArtifact.") + if not isinstance(heldout, pd.DataFrame | pl.DataFrame): + raise TypeError("heldout must be a pandas or Polars DataFrame.") + if len(heldout) < 2: + raise ValueError("heldout must contain at least two labeled rows.") + if target_column not in heldout.columns or target_column in artifact.manifest.input_columns: + raise ValueError("heldout must contain a separate target column.") + columns = list(artifact.manifest.input_columns) + features = ( + heldout.select(columns) if isinstance(heldout, pl.DataFrame) else heldout.loc[:, columns] + ) + actual = heldout[target_column].to_numpy() + predicted = predict_local_pipeline(features, artifact)["prediction"].to_numpy() + if artifact.manifest.task == "regression": + return { + "heldout_mae": float(mean_absolute_error(actual, predicted)), + "heldout_rmse": float(math.sqrt(mean_squared_error(actual, predicted))), + "heldout_r2": float(r2_score(actual, predicted)), + } + metrics = { + "heldout_accuracy": float(accuracy_score(actual, predicted)), + "heldout_f1_weighted": float( + f1_score(actual, predicted, average="weighted", zero_division=0) + ), + } + if len(artifact.manifest.classes) == 2: + metrics["heldout_f1"] = float( + f1_score(actual, predicted, pos_label=artifact.manifest.classes[1], zero_division=0) + ) + return metrics + + +def read_local_source(spark: Any, spec: LocalSourceSpec) -> pd.DataFrame: + """Filter and project a fixed Delta snapshot before bounded driver transfer.""" + if not isinstance(spec, LocalSourceSpec): + raise TypeError("spec must be a LocalSourceSpec.") + source = spark.read.format("delta").option("versionAsOf", spec.version).table(spec.table) + start = spec.period_start.astimezone(UTC).isoformat() + end = spec.period_end.astimezone(UTC).isoformat() + selected = source.where( + f"{column_name(spec.period_column)} >= TIMESTAMP '{start}' AND " + f"{column_name(spec.period_column)} < TIMESTAMP '{end}'" + ) + names = (*spec.row_keys, *spec.input_columns) + selected = selected.select(*names).orderBy(*spec.row_keys).limit(spec.max_rows + 1) + records: list[dict[str, Any]] = [] + serialized_bytes = 0 + for row in selected.toLocalIterator(): + if len(records) >= spec.max_rows: + raise ValueError("Source exceeds max_rows.") + record = row.asDict(recursive=True) if hasattr(row, "asDict") else dict(row) + # This is the decoded row payload, not a claim about Spark wire framing. + serialized_bytes += len(pickle.dumps(record, protocol=pickle.HIGHEST_PROTOCOL)) + if serialized_bytes > spec.max_bytes: + raise ValueError("Source exceeds max_bytes.") + records.append(record) + frame = pd.DataFrame.from_records(records, columns=names) + if _frame_bytes(frame) > spec.max_bytes: + raise ValueError("Source local frame exceeds max_bytes.") + if frame.duplicated(subset=list(spec.row_keys)).any(): + raise ValueError("Source row keys must be unique within the requested period.") + return frame + + +def score_local_source( + spark: Any, spec: LocalSourceSpec, prepared: PreparedLocalWorkflow +) -> LocalScoreResult: + """Score one pinned period without refitting FE or writing a Delta table.""" + if not isinstance(prepared, PreparedLocalWorkflow): + raise TypeError("prepared must be a PreparedLocalWorkflow.") + source = prepared.config.source + if source.kind != "uc_table" or source.table != spec.table or source.version != spec.version: + raise ValueError("Prepared source must match the pinned Delta table and version.") + if spec.max_rows > source.max_rows or spec.max_bytes > source.max_bytes: + raise ValueError("Source budget exceeds the prepared workflow budget.") + expected = ( + prepared.artifact.manifest.input_columns + if isinstance(prepared.artifact, LocalPipelineArtifact) + else tuple(column.name for column in prepared.artifact.manifest.input_schema) + ) + if spec.input_columns != expected: + raise ValueError("Source inputs must match the saved model's raw column order.") + frame = read_local_source(spark, spec) + predictions = prepared.predict(frame.loc[:, list(spec.input_columns)]) + if len(predictions) != len(frame): + raise ValueError("Prediction changed source row membership.") + result = pd.concat( + [ + frame.loc[:, list(spec.row_keys)].reset_index(drop=True), + predictions.reset_index(drop=True), + ], + axis=1, + ) + diagnostics: dict[str, str | int] = { + "source_table": spec.table, + "source_version": spec.version, + "period_start_utc": spec.period_start.astimezone(UTC).isoformat(), + "period_end_utc": spec.period_end.astimezone(UTC).isoformat(), + "business_timezone": spec.business_timezone, + "model_digest": prepared.preflight.model_digest or "", + "model_version": prepared.preflight.model_version or "local_path", + "row_count": len(result), + } + return LocalScoreResult(result, diagnostics) diff --git a/skyulf-core/skyulf/integrations/databricks/local_sdk.py b/skyulf-core/skyulf/integrations/databricks/local_sdk.py new file mode 100644 index 000000000..ab2e96e67 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_sdk.py @@ -0,0 +1,490 @@ +"""Offline configuration and preflight for bounded local-engine jobs. + +The SDK does not submit jobs or read Unity Catalog tables. The separate +local_batch adapter uses the declared table snapshot and period. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Literal +from urllib.parse import parse_qsl, urlsplit + +import pandas as pd +import polars as pl +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from ...inference._manifest import ColumnSpec, label_dtype +from ...inference.bundle import InferenceBundle, load_bundle, predict_local +from ...inference.local_pipeline import ( + LocalPipelineArtifact, + load_local_pipeline, + predict_local_pipeline, +) +from ..mlflow.registry import ( + RegistryAccessError, + RegistryDependencyError, + RegistryError, + RegistryModelNotFoundError, + ResolvedModel, +) + + +class InputSource(BaseModel): + """Select caller-owned rows or describe a pinned UC table read.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + kind: Literal["caller_frame", "uc_table"] + table: str | None = None + version: int | None = None + max_rows: int = Field(default=100_000, gt=0) + max_bytes: int = Field(default=128 * 1024 * 1024, gt=0) + + +class ModelSelection(BaseModel): + """Choose one artifact contract and either a path or pinned registry selector.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + kind: Literal["local_pipeline", "portable_bundle"] + path: str | None = None + name: str | None = None + alias: str | None = None + version: str | None = None + tracking_uri: str | None = None + registry_uri: str | None = None + + @field_validator("tracking_uri", "registry_uri") + @classmethod + def reject_embedded_credentials(cls, value: str | None) -> str | None: + """Keep credentials in the supported runtime provider, outside config.""" + if value is not None: + parsed = urlsplit(value) + query = {key.lower() for key, _ in parse_qsl(parsed.query)} + if ( + parsed.username + or parsed.password + or parsed.fragment + or any( + marker in key + for key in query + for marker in ("token", "password", "secret", "credential", "api_key") + ) + ): + raise ValueError("Store URI must not embed credentials.") + return value + + @model_validator(mode="after") + def validate_selector(self) -> ModelSelection: + """Require exactly one local path or one registry alias/version selector.""" + if self.path is not None: + if not self.path.strip() or any( + value is not None + for value in ( + self.name, + self.alias, + self.version, + self.tracking_uri, + self.registry_uri, + ) + ): + raise ValueError("A local path cannot be combined with registry settings.") + elif ( + not self.name or not self.name.strip() or (self.alias is None) == (self.version is None) + ): + raise ValueError("A registry model needs a name and exactly one alias or version.") + if self.alias is not None and not self.alias.strip(): + raise ValueError("alias must be non-empty.") + if self.version is not None and ( + not self.version.isascii() or not self.version.isdigit() or int(self.version) <= 0 + ): + raise ValueError("version must be a concrete positive integer string.") + return self + + +class OutputSink(BaseModel): + """Select returned predictions or a declared future UC Delta target.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + kind: Literal["return_frame", "uc_delta"] + table: str | None = None + + +class LocalWorkflowConfig(BaseModel): + """Immutable, serializable decisions for one local-engine scoring job.""" + + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + runtime: Literal["local", "databricks", "spark"] + engine: Literal["pandas", "polars"] + source: InputSource + model: ModelSelection + sink: OutputSink + + +@dataclass(frozen=True, slots=True) +class PreflightIssue: + """Identify one incompatibility and an actionable repair.""" + + code: str + category: Literal["config", "source", "node", "model", "runtime", "sink"] + message: str + fix: str + phase: Literal["local", "remote"] = "local" + + +@dataclass(frozen=True, slots=True) +class PreflightResult: + """Keep local evidence separate from optional read-only registry evidence.""" + + issues: tuple[PreflightIssue, ...] + remote_checked: bool + model_version: str | None = None + model_digest: str | None = None + feature_order: tuple[str, ...] = () + output_schema: tuple[ColumnSpec, ...] = () + + @property + def ready(self) -> bool: + """Permit prediction only after metadata and every compatibility check pass.""" + return not self.issues and self.model_digest is not None + + @property + def local_issues(self) -> tuple[PreflightIssue, ...]: + """Expose checks that did not need a registry or workspace read.""" + return tuple(issue for issue in self.issues if issue.phase == "local") + + @property + def remote_issues(self) -> tuple[PreflightIssue, ...]: + """Expose failures from an explicitly requested read-only model lookup.""" + return tuple(issue for issue in self.issues if issue.phase == "remote") + + @property + def output_columns(self) -> tuple[str, ...]: + """Expose output names in the saved model's column order.""" + return tuple(column.name for column in self.output_schema) + + +class PreflightError(ValueError): + """The selected local workflow cannot safely start.""" + + def __init__(self, result: PreflightResult) -> None: + """Retain structured issues for CLI or job diagnostics.""" + self.result = result + super().__init__("; ".join(f"{issue.code}: {issue.fix}" for issue in result.issues)) + + +def _config_issues(config: LocalWorkflowConfig) -> list[PreflightIssue]: + """Reject invalid runtime, source and sink choices before artifact I/O.""" + issues: list[PreflightIssue] = [] + if config.runtime == "spark": + issues.append( + PreflightIssue( + "runtime_unsupported", + "runtime", + "Spark is not a local engine runtime.", + "Choose local or databricks; use the separate Spark batch runner for Spark inference.", + ) + ) + if config.source.kind == "uc_table": + if not config.source.table or config.source.version is None or config.source.version < 0: + issues.append( + PreflightIssue( + "source_unbounded", + "source", + "UC source needs a table and fixed nonnegative snapshot version.", + "Specify table and version; retain explicit max_rows and max_bytes limits.", + ) + ) + elif config.source.table is not None or config.source.version is not None: + issues.append( + PreflightIssue( + "source_conflict", + "source", + "A caller frame cannot also select a UC table or version.", + "Remove table and version from caller_frame input.", + ) + ) + if config.sink.kind == "uc_delta": + issues.append( + PreflightIssue( + "sink_unavailable", + "sink", + "Local-result UC Delta publication is scheduled for SM-15L.", + "Use return_frame until the guarded local-result sink is available.", + ) + ) + elif config.sink.table is not None: + issues.append( + PreflightIssue( + "sink_conflict", + "sink", + "return_frame does not write a table.", + "Remove the sink table or select a supported writer later.", + ) + ) + return issues + + +def preflight_local( + config: LocalWorkflowConfig, + *, + artifact: LocalPipelineArtifact | InferenceBundle | None = None, + resolved: ResolvedModel | None = None, + probe_frame: pd.DataFrame | pl.DataFrame | None = None, +) -> PreflightResult: + """Check selected contracts without network, pickle loading or job submission. + + Pass an already validated artifact for full local checks. An optional small + probe exercises real fitted FE/model prediction before job submission. + Registry selection remains unresolved until explicit preparation. + """ + if not isinstance(config, LocalWorkflowConfig): + raise TypeError("config must be a LocalWorkflowConfig.") + issues = _config_issues(config) + remote_checked = resolved is not None + if config.model.name is not None and resolved is None: + issues.append( + PreflightIssue( + "model_unresolved", + "model", + "Registry identity and artifact metadata have not been checked.", + "Call prepare_local_workflow to resolve the alias once and load its pinned version.", + ) + ) + if resolved is not None and ( + config.model.name != resolved.name + or (config.model.version is not None and config.model.version != resolved.version) + or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" + ): + issues.append( + PreflightIssue( + "model_reference_mismatch", + "model", + "Resolved model differs from the selected concrete identity.", + "Resolve the configured name and selector again before this job.", + "remote", + ) + ) + if artifact is None: + issues.append( + PreflightIssue( + "artifact_unchecked", + "model", + "Artifact metadata is not available for preflight.", + "Load a trusted artifact and rerun preflight.", + ) + ) + return PreflightResult(tuple(issues), remote_checked) + if config.model.kind == "local_pipeline" and isinstance(artifact, LocalPipelineArtifact): + manifest = artifact.manifest + digest = manifest.pipeline_sha256 + feature_order = manifest.feature_columns + label = "float64" if manifest.task == "regression" else label_dtype(manifest.classes) + output = ( + ColumnSpec(name="prediction", dtype=label), + *( + ColumnSpec(name=f"probability_{i}", dtype="float64") + for i in range(len(manifest.classes)) + ), + ) + if config.engine != manifest.fitted_engine: + issues.append( + PreflightIssue( + "engine_mismatch", + "runtime", + "Selected engine differs from the fitted local pipeline.", + f"Choose engine='{manifest.fitted_engine}' or refit the pipeline.", + ) + ) + if manifest.execution_scope != "whole_frame_local": + issues.append( + PreflightIssue( + "scope_unsupported", + "model", + "Local package is not eligible for whole-frame local scoring.", + "Use a package fitted for whole_frame_local.", + ) + ) + if artifact.pipeline.preprocessing_steps != artifact.pipeline.feature_engineer.steps_config: + issues.append( + PreflightIssue( + "node_contract_mismatch", + "node", + "Pipeline FE configuration differs from its fitted transformer.", + "Reload the original fitted artifact instead of changing its steps.", + ) + ) + estimator = artifact.pipeline.model_estimator + if estimator is None or estimator.model is None: + actual_model_class = None + else: + model = estimator._unwrap_tuned_model() + actual_model_class = f"{type(model).__module__}.{type(model).__qualname__}" + if actual_model_class != manifest.model_class: + issues.append( + PreflightIssue( + "model_contract_mismatch", + "model", + "Artifact model class differs from the fitted estimator.", + "Reload a complete fitted artifact without changing its metadata.", + ) + ) + elif config.model.kind == "portable_bundle" and isinstance(artifact, InferenceBundle): + manifest = artifact.manifest + digest = artifact.semantic_digest + feature_order = artifact.feature_order + output = manifest.output_schema + else: + issues.append( + PreflightIssue( + "artifact_kind_mismatch", + "model", + "Selected artifact kind differs from the loaded package.", + "Choose the matching local_pipeline or portable_bundle contract.", + ) + ) + return PreflightResult(tuple(issues), remote_checked) + if resolved is not None and resolved.digest != digest: + issues.append( + PreflightIssue( + "model_digest_mismatch", + "model", + "Resolved registry digest differs from loaded artifact.", + "Reload the selected concrete version and verify its package.", + "remote", + ) + ) + if probe_frame is not None and not issues: + try: + _check_frame_budget(probe_frame, config.source) + if isinstance(artifact, LocalPipelineArtifact): + predict_local_pipeline(probe_frame, artifact) + else: + predict_local(probe_frame, artifact) + except (TypeError, ValueError, RuntimeError) as exc: + issues.append( + PreflightIssue( + "prediction_probe_failed", + "model", + str(exc), + "Fix the sample schema or fitted pipeline; replay a representative batch.", + ) + ) + return PreflightResult( + tuple(issues), + remote_checked, + resolved.version if resolved else None, + digest, + feature_order, + output, + ) + + +@dataclass(frozen=True, slots=True) +class PreparedLocalWorkflow: + """A verified local predictor bound to one loaded artifact and config.""" + + config: LocalWorkflowConfig + artifact: LocalPipelineArtifact | InferenceBundle + preflight: PreflightResult + + def predict(self, frame: pd.DataFrame | pl.DataFrame) -> pd.DataFrame: + """Score only a bounded caller-owned batch with the selected contract.""" + _check_frame_budget(frame, self.config.source) + if isinstance(self.artifact, LocalPipelineArtifact): + return predict_local_pipeline(frame, self.artifact) + return predict_local(frame, self.artifact) + + +def _check_frame_budget(frame: pd.DataFrame | pl.DataFrame, source: InputSource) -> None: + """Bound driver rows and in-memory frame bytes before any prediction.""" + if not isinstance(frame, pd.DataFrame | pl.DataFrame): + raise TypeError("Local workflow requires a pandas or Polars DataFrame.") + if len(frame) > source.max_rows: + raise ValueError("Input exceeds max_rows.") + size = ( + int(frame.memory_usage(index=True, deep=True).sum()) + if isinstance(frame, pd.DataFrame) + else frame.estimated_size() + ) + if size > source.max_bytes: + raise ValueError("Input exceeds max_bytes.") + + +def prepare_local_workflow( + config: LocalWorkflowConfig, *, probe_frame: pd.DataFrame | pl.DataFrame | None = None +) -> PreparedLocalWorkflow: + """Load a trusted path or read a registry alias once, then run full preflight. + + Registry access is read-only. Loading a package deserializes trusted pickle; + call this only for artifacts from a trusted producer. No job is submitted. + """ + if not isinstance(config, LocalWorkflowConfig): + raise TypeError("config must be a LocalWorkflowConfig.") + issues = _config_issues(config) + if issues: + raise PreflightError(PreflightResult(tuple(issues), False)) + selection = config.model + resolved = None + if selection.path is not None: + path = Path(selection.path) + try: + artifact = ( + load_local_pipeline(path) + if selection.kind == "local_pipeline" + else load_bundle(path) + ) + except (OSError, ValueError) as exc: + issue = PreflightIssue( + "artifact_invalid", + "model", + str(exc), + "Select a trusted, complete artifact of the declared kind and compatible runtime.", + ) + raise PreflightError(PreflightResult((issue,), False)) from exc + else: + from ..mlflow.registry import ( # noqa: PLC0415 - optional MLflow client boundary + load_registered_bundle, + load_registered_local_pipeline, + resolve_model, + ) + + if selection.name is None: + raise ValueError("Registry model name is missing.") + try: + resolved = resolve_model( + selection.name, + alias=selection.alias, + version=selection.version, + tracking_uri=selection.tracking_uri, + registry_uri=selection.registry_uri, + ) + loader = ( + load_registered_local_pipeline + if selection.kind == "local_pipeline" + else load_registered_bundle + ) + artifact = loader( + resolved, tracking_uri=selection.tracking_uri, registry_uri=selection.registry_uri + ) + except (RegistryError, OSError, ValueError) as exc: + if isinstance(exc, RegistryAccessError): + code, fix = ( + "registry_access_denied", + "Grant model read/EXECUTE to the job identity.", + ) + elif isinstance(exc, RegistryModelNotFoundError): + code, fix = "registry_model_missing", "Check the model name and alias or version." + elif isinstance(exc, RegistryDependencyError): + code, fix = "mlflow_unavailable", "Install the optional MLflow extra." + else: + code, fix = "registry_or_artifact_invalid", "Check the trusted package metadata." + issue = PreflightIssue(code, "model", str(exc), fix, "remote") + result = PreflightResult( + (issue,), True, resolved.version if resolved is not None else None + ) + raise PreflightError(result) from exc + result = preflight_local(config, artifact=artifact, resolved=resolved, probe_frame=probe_frame) + if not result.ready: + raise PreflightError(result) + return PreparedLocalWorkflow(config, artifact, result) diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py index e02c79db1..6588512f4 100644 --- a/skyulf-core/skyulf/integrations/mlflow/registry.py +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -15,6 +15,7 @@ if TYPE_CHECKING: from ...inference.bundle import InferenceBundle + from ...inference.local_pipeline import LocalPipelineArtifact __all__ = [ "RegistryAccessError", @@ -24,6 +25,7 @@ "RegistryOperationError", "ResolvedModel", "load_registered_bundle", + "load_registered_local_pipeline", "register_model", "resolve_model", ] @@ -121,12 +123,78 @@ def load_registered_bundle( return bundle +def load_registered_local_pipeline( + resolved: ResolvedModel, + *, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> LocalPipelineArtifact: + """Load a trusted local pipeline from one concrete registered-model version. + + The package's declared artifact path and both digests are checked before the + fitted pipeline is returned. A digest is an integrity check, not a signature. + """ + if not isinstance(resolved, ResolvedModel): + raise TypeError("resolved must be a ResolvedModel.") + _validate_registry_options(resolved.name, tracking_uri, registry_uri) + if ( + not isinstance(resolved.version, str) + or not resolved.version.isascii() + or not resolved.version.isdigit() + or int(resolved.version) <= 0 + or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" + ): + raise ValueError("resolved must identify a concrete positive model version.") + if not isinstance(resolved.digest, str) or not resolved.digest.strip(): + raise ValueError("resolved must include the Skyulf local pipeline digest.") + mlflow = _require_mlflow() + client = _make_client(mlflow, tracking_uri, registry_uri) + try: + version = client.get_model_version(resolved.name, resolved.version) + source = getattr(version, "source", None) + artifact_uri = source if isinstance(source, str) and source else resolved.model_uri + local_path = mlflow.artifacts.download_artifacts( + artifact_uri=artifact_uri, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + model = mlflow.models.Model.load(Path(local_path)) + except Exception as exc: # noqa: BLE001 - translate registry and transport failures + raise _translate_error(exc, name=resolved.name, version=resolved.version) from exc + metadata = model.metadata or {} + if ( + metadata.get("skyulf_artifact_kind") != "local_pipeline" + or metadata.get("skyulf_execution_scope") != "whole_frame_local" + or metadata.get("skyulf_local_pipeline_digest") != resolved.digest + ): + raise ValueError( + "Packaged Skyulf local pipeline metadata differs from resolved digest or scope." + ) + artifact_path = _packaged_artifact_path(Path(local_path), model.flavors, "local_pipeline") + from ...inference.local_pipeline import ( # noqa: PLC0415 - lazy pickle dependency + load_local_pipeline, + ) + + artifact = load_local_pipeline(artifact_path) + if ( + artifact.manifest.pipeline_sha256 != resolved.digest + or artifact.manifest.fitted_engine != metadata.get("skyulf_fitted_engine") + ): + raise ValueError("Loaded Skyulf local pipeline identity differs from resolved package.") + return artifact + + def _packaged_bundle_path(package: Path, flavors: dict[str, Any]) -> Path: """Find the declared bundle directory and reject paths escaping the package.""" + return _packaged_artifact_path(package, flavors, "bundle") + + +def _packaged_artifact_path(package: Path, flavors: dict[str, Any], key: str) -> Path: + """Locate a declared artifact directory without allowing package traversal.""" try: - relative = flavors["python_function"]["artifacts"]["bundle"]["path"] + relative = flavors["python_function"]["artifacts"][key]["path"] except (KeyError, TypeError) as exc: - raise ValueError("MLflow model is missing the Skyulf bundle artifact path.") from exc + raise ValueError(f"MLflow model is missing the Skyulf {key} artifact path.") from exc if ( not isinstance(relative, str) or not relative.strip() diff --git a/skyulf-core/tests/integrations/test_databricks_local_batch.py b/skyulf-core/tests/integrations/test_databricks_local_batch.py new file mode 100644 index 000000000..c3c5d840a --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_local_batch.py @@ -0,0 +1,307 @@ +"""Bounded local-engine training and monthly scoring on pinned UC snapshots.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from types import SimpleNamespace +from typing import Any + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import load_local_pipeline +from skyulf.integrations.databricks import local_batch +from skyulf.integrations.databricks.local_batch import ( + LocalSourceSpec, + fit_local_workflow, + read_local_source, + score_local_source, +) +from skyulf.integrations.databricks.local_sdk import ( + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + prepare_local_workflow, +) + + +class _Rows: + """Record Spark operations before yielding a bounded set of fake rows.""" + + def __init__(self, rows, operations): + """Retain the source rows and shared operation log.""" + self.rows = rows + self.operations = operations + + def where(self, expression): + """Record period filtering ahead of driver transfer.""" + self.operations.append(("where", expression)) + return self + + def select(self, *columns): + """Record the narrow projection ahead of driver transfer.""" + self.operations.append(("select", columns)) + return self + + def orderBy(self, *columns): + """Record deterministic key order ahead of driver transfer.""" + self.operations.append(("order", columns)) + return self + + def limit(self, count): + """Record the finite cap before iteration.""" + self.operations.append(("limit", count)) + return self + + def toLocalIterator(self): + """Yield only after snapshot, filter, projection and limit.""" + self.operations.append(("iterator", None)) + return iter(self.rows) + + +class _Reader: + """Stand in for the versioned Delta reader without cloud access.""" + + def __init__(self, rows, operations): + """Retain fake rows and operations.""" + self.rows = rows + self.operations = operations + + def format(self, value): + """Require Delta format.""" + self.operations.append(("format", value)) + return self + + def option(self, key, value): + """Require a concrete version before table access.""" + self.operations.append(("option", key, value)) + return self + + def table(self, name): + """Return the fake source frame.""" + self.operations.append(("table", name)) + return _Rows(self.rows, self.operations) + + +class _Spark: + """Expose only the versioned reader used by this workflow.""" + + def __init__(self, rows, operations): + """Construct the fake reader.""" + self.read = _Reader(rows, operations) + + +def _spec(**changes): + """Keep snapshot and period boundaries explicit in every test.""" + values: dict[str, Any] = { + "table": "workspace.test.score_source", + "version": 2, + "period_start": datetime(2026, 1, 1, tzinfo=UTC), + "period_end": datetime(2026, 2, 1, tzinfo=UTC), + "row_keys": ("entity_id",), + "input_columns": ("x",), + "max_rows": 3, + "max_bytes": 1024, + } + values.update(changes) + return LocalSourceSpec(**values) + + +def test_reader_pins_filters_and_limits_before_local_iteration() -> None: + """A monthly request must never pull an unrestricted UC table to the driver.""" + operations = [] + frame = read_local_source(_Spark([{"entity_id": "b", "x": 2.0}], operations), _spec()) + assert frame.to_dict("records") == [{"entity_id": "b", "x": 2.0}] + assert operations[:3] == [ + ("format", "delta"), + ("option", "versionAsOf", 2), + ("table", "workspace.test.score_source"), + ] + assert [name for name, *_ in operations[3:]] == [ + "where", + "select", + "order", + "limit", + "iterator", + ] + assert ("limit", 4) in operations + + +def test_reader_rejects_row_and_byte_overruns() -> None: + """The requested cap must fail closed even when a source yields excess rows.""" + rows = [{"entity_id": str(i), "x": float(i)} for i in range(4)] + with pytest.raises(ValueError, match="max_rows"): + read_local_source(_Spark(rows, []), _spec()) + with pytest.raises(ValueError, match="max_bytes"): + read_local_source(_Spark(rows[:1], []), _spec(max_bytes=1)) + + +def test_fit_and_score_local_workflow_keeps_keys_outside_model(tmp_path) -> None: + """A loaded fitted pipeline must score the new table without labels or refitting.""" + train = pd.DataFrame({"x": np.arange(8, dtype="float64"), "target": np.arange(8) * 2.0}) + path = tmp_path / "fitted" + fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=train.iloc[:6], test=train.iloc[6:]), + target_column="target", + artifact_path=path, + max_rows=8, + max_bytes=4096, + ) + artifact = load_local_pipeline(path) + config = LocalWorkflowConfig( + runtime="databricks", + engine="pandas", + source=InputSource(kind="uc_table", table="workspace.test.score_source", version=2), + model=ModelSelection(kind="local_pipeline", path=str(path)), + sink=OutputSink(kind="return_frame"), + ) + prepared = prepare_local_workflow(config) + rows = [{"entity_id": "new-1", "x": 2.0}, {"entity_id": "new-2", "x": 4.0}] + scored = score_local_source(_Spark(rows, []), _spec(), prepared) + assert artifact.manifest.input_columns == ("x",) + assert scored.predictions["entity_id"].tolist() == ["new-1", "new-2"] + np.testing.assert_allclose(scored.predictions["prediction"], [4.0, 8.0]) + assert scored.diagnostics["source_version"] == 2 + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_heldout_regression_metrics_use_saved_pipeline_and_200_test_rows(tmp_path, engine) -> None: + """A fitted model must be measured on the reserved labels, not its training rows.""" + x = np.arange(1000, dtype="float64") + frame = pd.DataFrame({"x": x, "target": 2 * x + 1}) + native = frame if engine == "pandas" else pl.from_pandas(frame) + artifact = fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=native[:800], test=native[800:]), + target_column="target", + artifact_path=tmp_path / engine, + max_rows=1000, + max_bytes=100_000, + ) + + metrics = local_batch.evaluate_local_holdout(artifact, native[800:], target_column="target") + + assert set(metrics) == {"heldout_mae", "heldout_rmse", "heldout_r2"} + assert metrics["heldout_mae"] == pytest.approx(0.0, abs=1e-8) + assert metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) + assert metrics["heldout_r2"] == pytest.approx(1.0) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_heldout_classification_metrics_use_reserved_labels(tmp_path, engine) -> None: + """Accuracy and F1 must expose label drift in the 200 rows kept out of fit.""" + x = np.r_[np.full(400, -1.0), np.full(400, 1.0)] + train = pd.DataFrame({"x": x, "target": np.r_[np.zeros(400), np.ones(400)]}) + test_x = np.r_[np.full(100, -1.0), np.full(100, 1.0)] + test_y = np.r_[np.ones(20), np.zeros(80), np.zeros(20), np.ones(80)] + test = pd.DataFrame({"x": test_x, "target": test_y.astype("int64")}) + train["target"] = train["target"].astype("int64") + native_train = train if engine == "pandas" else pl.from_pandas(train) + native_test = test if engine == "pandas" else pl.from_pandas(test) + artifact = fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "logistic_regression"}}, + SplitDataset(train=native_train, test=native_test), + target_column="target", + artifact_path=tmp_path / engine, + max_rows=1000, + max_bytes=100_000, + ) + + metrics = local_batch.evaluate_local_holdout(artifact, native_test, target_column="target") + + assert metrics["heldout_accuracy"] == pytest.approx(0.8) + assert metrics["heldout_f1"] == pytest.approx(0.8) + assert metrics["heldout_f1_weighted"] == pytest.approx(0.8) + + +def test_scoring_rejects_changed_identity_and_raw_column_order_before_read(tmp_path) -> None: + """A mismatched snapshot or input order must never trigger a Spark action.""" + train = pd.DataFrame( + { + "x": np.arange(8, dtype="float64"), + "z": np.arange(8, dtype="float64") * 3, + "target": np.arange(8, dtype="float64") * 2, + } + ) + path = tmp_path / "fitted" + fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=train.iloc[:6], test=train.iloc[6:]), + target_column="target", + artifact_path=path, + max_rows=8, + max_bytes=4096, + ) + prepared = prepare_local_workflow( + LocalWorkflowConfig( + runtime="databricks", + engine="pandas", + source=InputSource(kind="uc_table", table="workspace.test.score_source", version=2), + model=ModelSelection(kind="local_pipeline", path=str(path)), + sink=OutputSink(kind="return_frame"), + ) + ) + operations = [] + source = _Spark([], operations) + with pytest.raises(ValueError, match="pinned Delta table and version"): + score_local_source(source, _spec(version=3, input_columns=("x", "z")), prepared) + with pytest.raises(ValueError, match="raw column order"): + score_local_source(source, _spec(input_columns=("z", "x")), prepared) + assert operations == [] + + +def test_source_spec_rejects_ambiguous_identity_before_spark() -> None: + """Invalid identifiers and naive dates cannot reach a remote read.""" + with pytest.raises(ValueError): + _spec(table="workspace.test.score_source;DROP TABLE x") + with pytest.raises(ValueError, match="timezone-aware"): + _spec(period_start=datetime(2026, 1, 1)) + + +def test_real_spark_iterator_filters_requested_month(monkeypatch) -> None: + """The real Spark API must apply the month predicate before local scoring.""" + spark_sql = pytest.importorskip("pyspark.sql") + monkeypatch.setenv("SPARK_LOCAL_IP", "127.0.0.1") + spark = ( + spark_sql.SparkSession.builder.master("local[1]") + .appName("skyulf-sm24a-local-read") + .config("spark.ui.enabled", "false") + .config("spark.sql.session.timeZone", "UTC") + .getOrCreate() + ) + try: + frame = spark.createDataFrame( + [ + ("jan", datetime(2026, 1, 10, tzinfo=UTC), 1.0), + ("feb", datetime(2026, 2, 10, tzinfo=UTC), 2.0), + ], + "entity_id string, event_time timestamp, x double", + ) + + class Reader: + """Return the real Spark frame after accepting the pinned selector.""" + + def format(self, value): + """Accept Delta selection from the adapter.""" + assert value == "delta" + return self + + def option(self, name, value): + """Check that the source version is explicit.""" + assert (name, value) == ("versionAsOf", 2) + return self + + def table(self, name): + """Yield the known local source frame.""" + assert name == "workspace.test.score_source" + return frame + + result = read_local_source(SimpleNamespace(read=Reader()), _spec()) + assert result.to_dict("records") == [{"entity_id": "jan", "x": 1.0}] + finally: + spark.stop() diff --git a/skyulf-core/tests/integrations/test_databricks_local_five_models.py b/skyulf-core/tests/integrations/test_databricks_local_five_models.py new file mode 100644 index 000000000..eae69594e --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_local_five_models.py @@ -0,0 +1,198 @@ +"""Five realistic pandas/Polars pipelines intended for the SM-24a cloud probe.""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import polars as pl +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import predict_local_pipeline +from skyulf.integrations.databricks.local_batch import fit_local_workflow + +CASES = [ + ( + "R1", + "pandas", + "linear_regression", + "regression_target", + ("x", "z"), + [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["z"], "strategy": "mean"}, + }, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x", "z"]}}, + { + "name": "cross", + "transformer": "FeatureInteraction", + "params": {"columns": ["x", "z"]}, + }, + ], + ), + ( + "R2", + "polars", + "random_forest_regressor", + "regression_target", + ("x", "z", "city"), + [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["z"], "strategy": "median"}, + }, + {"name": "clip", "transformer": "Winsorize", "params": {"columns": ["x"]}}, + { + "name": "band", + "transformer": "CustomBinning", + "params": { + "columns": ["x"], + "bins": [-1000.0, 0.0, 5.0, 10.0, 1000.0], + "output_suffix": "_band", + }, + }, + { + "name": "encode", + "transformer": "OneHotEncoder", + "params": { + "columns": ["city", "x_band"], + "handle_unknown": "ignore", + "drop_original": True, + }, + }, + ], + ), + ( + "C1", + "pandas", + "logistic_regression", + "classification_target", + ("x", "z", "city"), + [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["z"], "strategy": "mean"}, + }, + { + "name": "ordinal", + "transformer": "OrdinalEncoder", + "params": { + "columns": ["city"], + "handle_unknown": "use_encoded_value", + "unknown_value": -1, + }, + }, + {"name": "scale", "transformer": "RobustScaler", "params": {"columns": ["x", "z"]}}, + ], + ), + ( + "C2", + "polars", + "random_forest_classifier", + "classification_target", + ("x", "z", "city"), + [ + { + "name": "fill", + "transformer": "SimpleImputer", + "params": {"columns": ["z"], "strategy": "mean"}, + }, + { + "name": "encode", + "transformer": "OneHotEncoder", + "params": { + "columns": ["city"], + "handle_unknown": "ignore", + "drop_original": True, + }, + }, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x", "z"]}}, + { + "name": "cross", + "transformer": "FeatureInteraction", + "params": {"columns": ["x", "z"]}, + }, + ], + ), + ( + "R3", + "pandas", + "gradient_boosting_regressor", + "regression_target", + ("x", "z"), + [ + { + "name": "fill", + "transformer": "KNNImputer", + "params": {"columns": ["x", "z"], "n_neighbors": 3}, + }, + { + "name": "select", + "transformer": "VarianceThreshold", + "params": {"columns": ["x", "z"], "threshold": 0.0}, + }, + {"name": "power", "transformer": "PowerTransformer", "params": {"columns": ["x", "z"]}}, + ], + ), +] + + +def sample_data(count: int = 120) -> pd.DataFrame: + """Create deterministic missing values, outliers, labels and categories.""" + positions = np.arange(count) + x = positions.astype("float64") / 12.0 + x[positions == 17] = 45.0 + z = np.sin(positions / 7.0) * 3.0 + 4.0 + z[positions % 19 == 0] = np.nan + city = np.array(["Vilnius", "Riga", "Tallinn"])[positions % 3] + clean_z = np.nan_to_num(z, nan=4.0) + return pd.DataFrame( + { + "x": x, + "z": z, + "city": city, + "regression_target": 2.0 * x + clean_z + (positions % 3), + "classification_target": (((x % 3.0) + clean_z / 3.0) > 2.4).astype("int64"), + } + ) + + +@pytest.mark.parametrize("case", CASES, ids=[case[0] for case in CASES]) +def test_five_models_round_trip_on_recorded_local_engine(tmp_path, case) -> None: + """The planned live model families must survive fit, save, load and prediction.""" + name, engine, model, target, columns, preprocessing = case + frame = sample_data().loc[:, [*columns, target]] + native = pl.from_pandas(frame) if engine == "polars" else frame + train = native[:96] + test = native[96:] + artifact = fit_local_workflow( + {"preprocessing": preprocessing, "modeling": {"type": model}}, + SplitDataset(train=train, test=test), + target_column=target, + artifact_path=tmp_path / name, + max_rows=120, + max_bytes=128_000, + ) + query = sample_data(6).loc[:, list(columns)] + if "city" in query: + query.loc[0, "city"] = "new-city" + predictions = predict_local_pipeline(query, artifact) + assert len(predictions) == len(query) + assert predictions["prediction"].notna().all() + native_query = pl.from_pandas(query) if engine == "polars" else query + transformed = artifact.pipeline.feature_engineer.transform(native_query, preserve_rows=True) + estimator = artifact.pipeline.model_estimator + assert estimator is not None + direct = estimator._unwrap_tuned_model().predict( + transformed.to_pandas() if isinstance(transformed, pl.DataFrame) else transformed + ) + if target == "classification_target": + np.testing.assert_array_equal(predictions["prediction"].to_numpy(), direct) + else: + np.testing.assert_allclose(predictions["prediction"].to_numpy(), direct, rtol=0, atol=1e-12) + if target == "classification_target": + np.testing.assert_allclose(predictions[["probability_0", "probability_1"]].sum(axis=1), 1.0) diff --git a/skyulf-core/tests/integrations/test_databricks_local_sdk.py b/skyulf-core/tests/integrations/test_databricks_local_sdk.py new file mode 100644 index 000000000..dafcbdf0c --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_local_sdk.py @@ -0,0 +1,288 @@ +"""Preflight for the first bounded pandas/Polars Databricks workflow.""" + +from __future__ import annotations + +from dataclasses import replace + +import numpy as np +import pandas as pd +import polars as pl +import pytest +from pydantic import ValidationError + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.bundle import build_bundle, save_bundle +from skyulf.inference.local_pipeline import load_local_pipeline, save_local_pipeline +from skyulf.integrations.databricks.local_sdk import ( + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + PreflightError, + preflight_local, + prepare_local_workflow, +) +from skyulf.pipeline import SkyulfPipeline + + +def _artifact(tmp_path, *, steps=None, model="linear_regression"): + """Create a real fitted artifact so metadata and predictor cannot diverge.""" + frame = pd.DataFrame({"x": np.arange(8, dtype="float64"), "target": np.arange(8) * 2.0}) + pipeline = SkyulfPipeline({"preprocessing": steps or [], "modeling": {"type": model}}) + pipeline.fit(SplitDataset(train=frame, test=frame.head(0)), target_column="target") + path = tmp_path / "local" + save_local_pipeline(pipeline, path) + return path, load_local_pipeline(path) + + +def _config(path, **changes): + """Keep each rejection test focused on one workflow decision.""" + values = { + "runtime": "databricks", + "engine": "pandas", + "source": InputSource(kind="caller_frame"), + "model": ModelSelection(kind="local_pipeline", path=str(path)), + "sink": OutputSink(kind="return_frame"), + } + values.update(changes) + return LocalWorkflowConfig(**values) + + +def test_config_load_is_immutable_and_offline(tmp_path, monkeypatch) -> None: + """Reading SDK config must never resolve aliases or mutate a workspace.""" + from skyulf.integrations.mlflow import registry + + monkeypatch.setattr(registry, "resolve_model", lambda *a, **k: pytest.fail("remote call")) + config = _config(tmp_path / "local") + loaded = LocalWorkflowConfig.model_validate_json(config.model_dump_json()) + assert loaded == config + field_name = "engine" + with pytest.raises(ValidationError): + setattr(loaded, field_name, "polars") + + +def test_preflight_selects_local_predictor_and_metadata(tmp_path) -> None: + """The selected engine and feature order must come from the fitted artifact.""" + path, artifact = _artifact(tmp_path) + config = _config(path) + result = preflight_local(config, artifact=artifact) + prepared = prepare_local_workflow(config) + actual = prepared.predict(pd.DataFrame({"x": [2.0, 4.0]})) + assert result.ready and prepared.preflight.ready + assert result.feature_order == ("x",) + assert result.model_digest == artifact.manifest.pipeline_sha256 + assert result.output_columns == ("prediction",) + np.testing.assert_allclose(actual["prediction"], [4.0, 8.0]) + + +@pytest.mark.parametrize( + ("changes", "code"), + [ + ({"engine": "polars"}, "engine_mismatch"), + ({"sink": OutputSink(kind="uc_delta", table="c.s.predictions")}, "sink_unavailable"), + ({"source": InputSource(kind="uc_table", table="c.s.source")}, "source_unbounded"), + ({"runtime": "spark"}, "runtime_unsupported"), + ], +) +def test_incompatible_config_fails_before_loading(tmp_path, monkeypatch, changes, code) -> None: + """Bad engine, source, sink or runtime must fail before artifact or job access.""" + path, artifact = _artifact(tmp_path) + config = _config(path, **changes) + result = preflight_local(config, artifact=artifact) + assert code in {issue.code for issue in result.issues} + with pytest.raises(PreflightError): + prepare_local_workflow(config) + + +def test_changed_in_memory_pipeline_contract_is_reported(tmp_path) -> None: + """A supplied artifact cannot claim a model or FE config different from its payload.""" + path, artifact = _artifact(tmp_path) + pipeline = artifact.pipeline + pipeline.preprocessing_steps = [{"name": "custom", "transformer": "SomeFutureNode"}] + changed = replace(artifact, pipeline=pipeline) + result = preflight_local(_config(path), artifact=changed) + assert "node_contract_mismatch" in {issue.code for issue in result.issues} + manifest = artifact.manifest.model_copy(update={"model_class": "other.FutureModel"}) + result = preflight_local(_config(path), artifact=replace(artifact, manifest=manifest)) + assert "model_contract_mismatch" in {issue.code for issue in result.issues} + + +def test_registry_requires_explicit_remote_preparation(tmp_path, monkeypatch) -> None: + """Local preflight must describe missing registry evidence without contacting MLflow.""" + from skyulf.integrations.mlflow import registry + + monkeypatch.setattr(registry, "resolve_model", lambda *a, **k: pytest.fail("remote call")) + config = _config( + tmp_path / "unused", + model=ModelSelection(kind="local_pipeline", name="catalog.schema.model", alias="champion"), + ) + result = preflight_local(config) + assert not result.ready + assert result.remote_checked is False + assert "model_unresolved" in {issue.code for issue in result.issues} + + +def test_portable_bundle_kind_must_match_artifact(tmp_path) -> None: + """Preflight rejects sending a local pickle package down the portable route.""" + path, artifact = _artifact(tmp_path) + config = _config(path, model=ModelSelection(kind="portable_bundle", path=str(path))) + result = preflight_local(config, artifact=artifact) + assert "artifact_kind_mismatch" in {issue.code for issue in result.issues} + + +def test_portable_bundle_uses_its_saved_feature_and_output_schema(tmp_path) -> None: + """The portable route retains bundle order and schema without changing engines.""" + frame = pd.DataFrame({"x": np.arange(8, dtype="float64"), "target": np.arange(8) * 2.0}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=frame, test=frame.head(0)), target_column="target") + path = tmp_path / "bundle" + save_bundle(build_bundle(pipeline, input_stage="raw", feature_order=("x",)), path) + config = _config(path, model=ModelSelection(kind="portable_bundle", path=str(path))) + prepared = prepare_local_workflow(config) + assert prepared.preflight.feature_order == ("x",) + assert prepared.preflight.output_schema[0].dtype == "float64" + np.testing.assert_allclose(prepared.predict(pd.DataFrame({"x": [2.0]}))["prediction"], [4.0]) + + +def test_caller_frame_size_is_checked_before_prediction(tmp_path) -> None: + """A caller cannot bypass the explicit driver-memory budget at score time.""" + path, _ = _artifact(tmp_path) + config = _config(path, source=InputSource(kind="caller_frame", max_rows=1, max_bytes=1024)) + prepared = prepare_local_workflow(config) + with pytest.raises(ValueError, match="max_rows"): + prepared.predict(pd.DataFrame({"x": [1.0, 2.0]})) + small = _config(path, source=InputSource(kind="caller_frame", max_rows=10, max_bytes=1)) + with pytest.raises(ValueError, match="max_bytes"): + prepare_local_workflow(small).predict(pd.DataFrame({"x": [1.0]})) + + +def test_optional_probe_reports_real_prediction_incompatibility(tmp_path) -> None: + """A sample checks fitted FE/model behavior without a fabricated SDK allowlist.""" + path, artifact = _artifact(tmp_path) + config = _config(path) + bad = pd.DataFrame({"other": [1.0]}) + result = preflight_local(config, artifact=artifact, probe_frame=bad) + assert "prediction_probe_failed" in {issue.code for issue in result.local_issues} + with pytest.raises(PreflightError) as failure: + prepare_local_workflow(config, probe_frame=bad) + assert failure.value.result.issues[0].code == "prediction_probe_failed" + + +def test_registry_alias_is_resolved_once_and_passed_as_a_version(tmp_path, monkeypatch) -> None: + """A moving alias cannot change the artifact selected inside one preparation.""" + from skyulf.integrations.mlflow import registry + + _, artifact = _artifact(tmp_path) + calls = [] + pinned = registry.ResolvedModel( + name="catalog.schema.model", + version="7", + model_uri="models:/catalog.schema.model/7", + signature=None, + digest=artifact.manifest.pipeline_sha256, + ) + + def resolve(*args, **kwargs): + """Return the single concrete version selected for this test job.""" + calls.append(("resolve", args, kwargs)) + return pinned + + def load(resolved, **kwargs): + """Ensure loading follows the prior resolution rather than the alias.""" + calls.append(("load", resolved, kwargs)) + return artifact + + monkeypatch.setattr(registry, "resolve_model", resolve) + monkeypatch.setattr(registry, "load_registered_local_pipeline", load) + config = _config( + tmp_path / "unused", + model=ModelSelection(kind="local_pipeline", name=pinned.name, alias="champion"), + ) + prepared = prepare_local_workflow(config) + assert [call[0] for call in calls] == ["resolve", "load"] + assert calls[1][1] is pinned + assert prepared.preflight.model_version == "7" + + +def test_remote_read_failure_returns_actionable_preflight_issue(tmp_path, monkeypatch) -> None: + """A registry denial must be distinguishable from a local model mismatch.""" + from skyulf.integrations.mlflow import registry + + def denied(*args, **kwargs): + """Simulate read-only MLflow access being rejected by the registry.""" + raise registry.RegistryAccessError("access denied") + + monkeypatch.setattr(registry, "resolve_model", denied) + config = _config( + tmp_path / "unused", + model=ModelSelection(kind="local_pipeline", name="catalog.schema.model", version="7"), + ) + with pytest.raises(PreflightError) as failure: + prepare_local_workflow(config) + result = failure.value.result + assert result.remote_checked + assert result.issues[0].code == "registry_access_denied" + assert result.remote_issues == result.issues + assert result.local_issues == () + assert result.issues[0].fix + + +@pytest.mark.parametrize( + "uri", + [ + "https://name:secret@example.com/mlflow", + "https://example.com/mlflow?access_token=secret", + ], +) +def test_store_uri_rejects_embedded_secret(uri) -> None: + """Serialized workflow config must not carry a store password or token.""" + from pydantic import ValidationError + + with pytest.raises(ValidationError, match="credentials"): + ModelSelection( + kind="local_pipeline", + name="model", + version="1", + tracking_uri=uri, + ) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_impute_and_scale_replay_is_eligible_for_local_sdk(engine, tmp_path) -> None: + """Common numeric FE must replay from a saved package on either local engine.""" + train = pd.DataFrame( + {"x": [1.0, np.nan, 3.0, 4.0, 5.0, 6.0], "target": [2.0, 4.0, 6.0, 8.0, 10.0, 12.0]} + ) + steps = [ + {"name": "fill", "transformer": "SimpleImputer", "params": {"strategy": "mean"}}, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}, + ] + pipeline = SkyulfPipeline({"preprocessing": steps, "modeling": {"type": "linear_regression"}}) + native = pl.from_pandas(train) if engine == "polars" else train + pipeline.fit(SplitDataset(train=native, test=native.head(0)), target_column="target") + path = tmp_path / "pipeline" + save_local_pipeline(pipeline, path) + query = pd.DataFrame({"x": [2.0, np.nan]}) + expected = pipeline.predict(pl.from_pandas(query) if engine == "polars" else query) + prepared = prepare_local_workflow(_config(path, engine=engine)) + assert prepared.preflight.ready + np.testing.assert_allclose(prepared.predict(query)["prediction"], expected) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_existing_library_node_and_model_need_no_sdk_allowlist(engine, tmp_path) -> None: + """A fitted library model and FE node remain usable without SDK registration.""" + train = pd.DataFrame({"x": np.arange(12, dtype="float64"), "target": np.arange(12) ** 2.0}) + steps = [{"name": "range", "transformer": "MinMaxScaler", "params": {"columns": ["x"]}}] + pipeline = SkyulfPipeline( + {"preprocessing": steps, "modeling": {"type": "random_forest_regressor"}} + ) + native = pl.from_pandas(train) if engine == "polars" else train + pipeline.fit(SplitDataset(train=native, test=native.head(0)), target_column="target") + path = tmp_path / "pipeline" + save_local_pipeline(pipeline, path) + query = pd.DataFrame({"x": [2.0, 9.0]}) + expected = pipeline.predict(pl.from_pandas(query) if engine == "polars" else query) + prepared = prepare_local_workflow(_config(path, engine=engine)) + assert prepared.preflight.ready + np.testing.assert_allclose(prepared.predict(query)["prediction"], expected) diff --git a/skyulf-core/tests/integrations/test_local_mlflow_model.py b/skyulf-core/tests/integrations/test_local_mlflow_model.py index 91b8ed4e3..c87d38324 100644 --- a/skyulf-core/tests/integrations/test_local_mlflow_model.py +++ b/skyulf-core/tests/integrations/test_local_mlflow_model.py @@ -6,6 +6,7 @@ import subprocess import sys from pathlib import Path +from typing import Literal, cast import numpy as np import pandas as pd @@ -23,7 +24,11 @@ mlflow = pytest.importorskip("mlflow") from skyulf.integrations.mlflow.local_model import log_local_model # noqa: E402 -from skyulf.integrations.mlflow.registry import register_model, resolve_model # noqa: E402 +from skyulf.integrations.mlflow.registry import ( # noqa: E402 + load_registered_local_pipeline, + register_model, + resolve_model, +) from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run # noqa: E402 @@ -119,6 +124,41 @@ def test_local_pyfunc_matches_saved_categorical_pipeline( ) assert resolved.model_uri == f"models:/local_{engine}/{registered.version}" assert resolved.digest == load_local_pipeline(artifact_path).manifest.pipeline_sha256 + pinned = load_registered_local_pipeline( + resolved, tracking_uri=config.tracking_uri, registry_uri=config.tracking_uri + ) + pd.testing.assert_frame_equal( + predict_local_pipeline(query, pinned).reset_index(drop=True), + saved.reset_index(drop=True), + ) + + from skyulf.integrations.databricks.local_sdk import ( # noqa: PLC0415 - integration boundary + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + prepare_local_workflow, + ) + + workflow = prepare_local_workflow( + LocalWorkflowConfig( + runtime="databricks", + engine=cast(Literal["pandas", "polars"], engine), + source=InputSource(kind="caller_frame"), + model=ModelSelection( + kind="local_pipeline", + name=f"local_{engine}", + version=str(registered.version), + tracking_uri=config.tracking_uri, + registry_uri=config.tracking_uri, + ), + sink=OutputSink(kind="return_frame"), + ) + ) + assert workflow.preflight.model_version == str(registered.version) + pd.testing.assert_frame_equal( + workflow.predict(query).reset_index(drop=True), saved.reset_index(drop=True) + ) child = subprocess.run( [ @@ -177,3 +217,72 @@ def test_local_pyfunc_preserves_tuned_classification(engine: str, tmp_path, monk actual = mlflow.pyfunc.load_model(model_uri).predict(query) pd.testing.assert_frame_equal(actual, expected) assert actual.columns.tolist() == ["prediction", "probability_0", "probability_1"] + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_mlflow_split_pipeline_replays_encoding_winsorize_and_scaling( + engine: str, tmp_path, monkeypatch +) -> None: + """An extreme inference row must remain scoreable after the full MLflow round trip.""" + monkeypatch.chdir(tmp_path) + values = np.arange(60, dtype="float64") + source = pd.DataFrame( + { + "x": values, + "city": np.where(np.arange(60) % 2 == 0, "Riga", "Vilnius"), + "target": 2.0 * values + (np.arange(60) % 2) * 3.0, + } + ) + if engine == "polars": + native = pl.from_pandas(source) + train, heldout = native.slice(0, 48), native.slice(48, 12) + else: + train, heldout = source.iloc[:48], source.iloc[48:] + pipeline = SkyulfPipeline( + { + "preprocessing": [ + {"name": "clip", "transformer": "Winsorize", "params": {"columns": ["x"]}}, + { + "name": "encode", + "transformer": "OneHotEncoder", + "params": { + "columns": ["city"], + "drop_original": True, + "handle_unknown": "ignore", + }, + }, + {"name": "scale", "transformer": "StandardScaler", "params": {"columns": ["x"]}}, + ], + "modeling": {"type": "linear_regression"}, + } + ) + pipeline.fit(SplitDataset(train=train, test=heldout), target_column="target") + bounds = pipeline.feature_engineer.fitted_steps[0]["artifact"]["bounds"]["x"] + query = pd.DataFrame( + { + "x": [1000.0, bounds["upper"], -1000.0, bounds["lower"]], + "city": ["Riga"] * 4, + } + ) + artifact_path = tmp_path / "local" + save_local_pipeline(pipeline, artifact_path) + expected = predict_local_pipeline(query, load_local_pipeline(artifact_path)) + uri = f"sqlite:///{(tmp_path / 'tracking.db').as_posix()}" + config = TrackingConfig(enabled=True, tracking_uri=uri, experiment_name=f"clip-{engine}") + assert config.tracking_uri is not None + + with track_run(config, run_name="split-clip-scale-encode") as run: + assert run.run_id is not None + model_uri = log_local_model( + artifact_path, + run_id=run.run_id, + artifact_path="model", + tracking_uri=config.tracking_uri, + ) + + mlflow.set_tracking_uri(config.tracking_uri) + actual = mlflow.pyfunc.load_model(model_uri).predict(query) + pd.testing.assert_frame_equal(actual, expected) + assert len(actual) == len(query) + assert np.isfinite(actual["prediction"]).all() + np.testing.assert_allclose(actual["prediction"].iloc[[0, 2]], actual["prediction"].iloc[[1, 3]]) From 5e1d5417b2ac38de8d0e12ebde9566e980a98516 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 17:55:37 +0300 Subject: [PATCH 33/85] feat: publish bounded local predictions to UC Delta Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 9 +- docs/user_guide/databricks_local_sdk.md | 91 ++++++ .../04-databricks-integration-plan.md | 34 +-- .../spark_and_mlflow/05-sm20-bundle-plan.md | 19 +- .../11-sm15l-live-validation-report.md | 72 +++++ initiatives/spark_and_mlflow/HANDOFF.md | 35 ++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 37 ++- .../examples/databricks_local_sm15l_job.py | 268 ++++++++++++++++++ .../integrations/databricks/__init__.py | 2 + .../integrations/databricks/_contracts.py | 4 +- .../skyulf/integrations/databricks/batch.py | 2 + .../integrations/databricks/local_batch.py | 10 +- .../integrations/databricks/local_publish.py | 193 +++++++++++++ .../integrations/databricks/local_sdk.py | 49 +++- .../tests/integrations/test_batch_contract.py | 14 + .../test_databricks_local_batch.py | 40 +++ .../integrations/test_databricks_local_sdk.py | 14 +- .../integrations/test_local_delta_publish.py | 253 +++++++++++++++++ 18 files changed, 1081 insertions(+), 65 deletions(-) create mode 100644 initiatives/spark_and_mlflow/11-sm15l-live-validation-report.md create mode 100644 skyulf-core/examples/databricks_local_sm15l_job.py create mode 100644 skyulf-core/skyulf/integrations/databricks/local_publish.py create mode 100644 skyulf-core/tests/integrations/test_local_delta_publish.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index e8a2d2b5d..3253e79ed 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -31,7 +31,14 @@ execution, MLflow registry and Databricks delivery remain under development. the existing full-pipeline artifact; a versioned Delta source is filtered by requested month, narrowed, row-limited and checked against a decoded-byte budget before whole-frame pandas/Polars prediction. The result carries source - and model identity diagnostics. Local-result Delta publication remains follow-up. + and model identity diagnostics. +- Bounded local pandas/Polars predictions can now publish one requested month + to a precreated UC Delta table through an explicit Spark result bridge. + The `local_pipeline` batch mode pins source, model, code and expected target + versions, reuses guarded period replacement and shared admission, and rejects + accidental empty or stale writes. Isolated serverless jobs verified 80 + predictions for each of two months, preserved prior rows and replayed without + another commit. No SQL Connector or Spark FE/model execution is required. - Versioned local pandas/Polars pipeline artifact and MLflow pyfunc packaging preserve fitted encoding/binning, model state, input order, class probabilities and explicit tuned thresholds without refitting. The fit engine and exact diff --git a/docs/user_guide/databricks_local_sdk.md b/docs/user_guide/databricks_local_sdk.md index d19e64e08..51a895286 100644 --- a/docs/user_guide/databricks_local_sdk.md +++ b/docs/user_guide/databricks_local_sdk.md @@ -247,3 +247,94 @@ the prepared workflow. The result keeps row keys outside the model input and records the source version, period, model digest and concrete model version. No prediction table is created here. Whole-frame FE retains local pandas or Polars behavior even though Spark performs the bounded UC read. + +## Publish one local-scored month to a UC Delta table + +`run_local_batch` keeps feature engineering and model prediction in the saved +pandas or Polars engine. Spark reads the pinned UC source and converts only the +bounded final prediction rows to a DataFrame with the target's explicit schema. +The guarded Delta writer then replaces exactly the requested half-open period. +A second month therefore leaves the first month's predictions and run metadata +unchanged; a backfill must explicitly name the earlier period. + +Provision the source, prediction target and admission control table before the +job. The source and target must be different Delta tables. The target must have +the row-key columns with the same Spark types as the source (`long` or +`string`), a `timestamp` period column, the saved model's output columns at +their declared types, and three string columns: +`__skyulf_run_id`, `__skyulf_model_name` and `__skyulf_model_version`. +The control table has exactly one row, `target_id STRING` equal to the target +Delta table ID and nullable `owner STRING` initially null. Every publisher +of this target must use that same control table. The job identity needs read +access to the source/model and write access to the target/control tables. + +```python +from datetime import UTC, datetime, timedelta +from importlib.metadata import version + +from skyulf.integrations.databricks import ( + BatchSpec, InputSource, LocalSourceSpec, LocalWorkflowConfig, + ModelSelection, OutputSink, prepare_local_workflow, run_local_batch, +) +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + +source_table = "catalog.schema.scoring_source" +target_table = "catalog.schema.predictions" +control_table = "catalog.schema.prediction_admission" +source_version = 12 +source = LocalSourceSpec( + table=source_table, + version=source_version, + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + row_keys=("entity_id",), + input_columns=("amount", "city"), + max_rows=10_000, + max_bytes=32_000_000, +) +config = LocalWorkflowConfig( + runtime="databricks", + engine="polars", + source=InputSource( + kind="uc_table", table=source_table, version=source_version, + max_rows=source.max_rows, max_bytes=source.max_bytes, + ), + model=ModelSelection( + kind="local_pipeline", name="catalog.schema.customer_model", version="7", + tracking_uri="databricks", registry_uri="databricks-uc", + ), + sink=OutputSink(kind="uc_delta", table=target_table), +) +prepared = prepare_local_workflow(config) +spec = BatchSpec( + period_start=source.period_start, + period_end=source.period_end, + as_of=datetime.now(UTC) + timedelta(minutes=2), + row_keys=source.row_keys, + output_table=target_table, + model_name=config.model.name, + model_version=prepared.preflight.model_version, + model_digest=prepared.preflight.model_digest, + source_version=source_version, + code_version=version("skyulf-core"), + run_id="january-2026-v1", + expected_target_version=0, # read and pin before submission + mode="local_pipeline", +) +result = run_local_batch( + spark, source, prepared, spec, + admission=DeltaTableAdmission(spark, control_table), +) +print(result.commit_version, result.replayed, result.manifest) +``` + +Use a new logical run ID and the current target version for the next month's +job. Retry an uncertain job with the *identical* spec, including its original +run ID and expected target version; a successful replay returns the existing +receipt. A new run with a stale expected version fails instead of overwriting +newer results. An empty period fails unless `allow_empty=True` is explicit. +The source snapshot must have been committed by `as_of`. The reader and +result both enforce the configured local row and memory budgets; this does not +measure Spark's private wire bytes. The control-row admission protocol protects +participating writers only; do not let other jobs bypass it or manually clear +an owner while a writer may still be active. diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md index 701937317..0fa362cfe 100644 --- a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -1,7 +1,7 @@ # Local-first Databricks integration and Bundle plan -Updated: 2026-09-23. SM-26, SM-25 and SM-24a are implemented and validated; -SM-15L and the first Bundle remain planned. +Updated: 2026-09-23. SM-26, SM-25, SM-24a and SM-15L are implemented and +validated; the first Bundle remains planned. Baseline: `63dd3e21` and the completed, scoped SM-16 evidence. ## Current direction @@ -69,8 +69,8 @@ UC publication and Bundle claims need their own cloud evidence. | 1 | SM-26: local pipeline MLflow packaging | SM-16; existing local persistence | DONE | | 2 | SM-25: local-first SDK configuration and preflight | SM-26 | DONE | | 3 | SM-24a: local training and bounded batch prediction | SM-25 | DONE | -| 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | READY | -| 5 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; verified SM-15L | WAIT | +| 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | DONE | +| 5 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; verified SM-15L | READY | | After first Bundle | SM-27: bounded full-history rescore and selectable Bundle mode | SM-20a; SM-15L | LATER | | After first Bundle | SM-22 then SM-28: validation/promotion and optional monthly retraining | SM-20a; SM-22 for SM-28 | LATER | | Later | SM-24b, SM-19, SM-21, SM-23: optional Jobs API, serving, feature lookup and monitoring | Relevant local adapters | LATER | @@ -174,33 +174,33 @@ success is claimed here. The stronger transport guarantee is SM-24d. ## SM-15L - Local monthly UC Delta publication -The earlier one-day deferral is superseded by the local-first Bundle request. -Proposed area: a local prediction -> UC output adapter and integration tests. -Prefer an explicit local-result -> Spark DataFrame bridge followed by guarded -Delta period replacement, subject to live validation. Databricks documents +The earlier one-day deferral was superseded by the local-first Bundle +request. The verified adapter converts bounded local results to a Spark +DataFrame and uses guarded Delta period replacement. Databricks documents [`spark.createDataFrame` from local data on serverless](https://docs.databricks.com/aws/en/compute/serverless/limitations) and [atomic selective overwrite](https://docs.databricks.com/aws/en/delta/selective-overwrite). The [Python SQL Connector](https://docs.databricks.com/aws/en/dev-tools/python-sql-connector) remains an alternative when a Spark bridge is unavailable; it is not required. -- [ ] Choose and test a bounded UC source reader. After local pandas/Polars +- [x] Choose and test a bounded UC source reader. After local pandas/Polars prediction, convert only the final result to a Spark DataFrame using an explicit target schema. Retain named columns, dtypes, nulls, row keys, labels and model-version metadata; avoid silent Polars-to-pandas semantics. -- [ ] Publish exactly one requested period using a safe, verified transaction +- [x] Publish exactly one requested period using a safe, verified transaction design. Test replay, empty period, stale model/source, concurrent writers, permission denial and failed staging; reject unsupported overwrite policies. A new month adds its predictions while prior-month rows and run metadata stay unchanged. Only an explicit backfill may rescore an earlier month. -- [ ] Reuse the existing guarded `publish_replace_period` where its contract +- [x] Reuse the existing guarded `publish_replace_period` where its contract applies. Its current `BatchSpec` includes Spark inference modes, so define a truthful local publication request or extract shared publication fields; do not label local prediction as `native_features` or `python_pipeline`. -- [ ] Require explicit `as_of`, source snapshot/version, period, target identity, +- [x] Require explicit `as_of`, source snapshot/version, period, target identity, logical run identity and maximum local row/byte limits. Table setup and - cleanup are explicit, and credentials use supported providers. State the - selected Spark compute or SQL warehouse requirement in config and preflight. -- [ ] Record a durable publication receipt and compare rows by key after commit. + cleanup are explicit, and credentials use supported providers. The publisher + requires an explicit Spark session for UC I/O; the job or Bundle selects its + compatible compute. No SQL warehouse is required for this tested path. +- [x] Record a durable publication receipt and compare rows by key after commit. A filesystem delta-rs test alone does not prove UC managed-table behavior. Acceptance: pandas and Polars local predictions reach the monthly UC target @@ -208,7 +208,9 @@ with tested replay/concurrency semantics on the chosen Databricks runtime. Spark performs only bounded source/result I/O in this first path; it does not apply FE or run the model. The output equals local gold predictions by row key, and a second monthly run does not recompute the first month. -The first Bundle cannot advertise a monthly UC output until this gate passes. +This gate passed in the isolated serverless jobs documented in the +[SM-15L live report](11-sm15l-live-validation-report.md). The first Bundle can +now use this path, subject to its own generated-project validation. ## SM-24b - Optional Databricks Jobs API operations diff --git a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md index c38b951c1..5e67d9283 100644 --- a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md +++ b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md @@ -1,7 +1,7 @@ # SM-20: local-first Databricks Bundle, then Spark enhancement -Updated: 2026-09-22. Planning only; no generated project or Databricks job has -been created by this plan. Current baseline is the scoped SM-16 serverless probe. +Updated: 2026-09-23. Planning only; no generated project has been created +by this plan. The SM-15L local monthly writer passed its separate live gate. The [open queue](OPEN_QUEUE.md) owns status and task order. ## Outcome and engine boundary @@ -52,9 +52,9 @@ of a particular schedule or period-publication policy. This separates the prediction engine from table I/O. Databricks documents [`spark.createDataFrame` from local data on serverless](https://docs.databricks.com/aws/en/compute/serverless/limitations) and [atomic selective Delta overwrite](https://docs.databricks.com/aws/en/delta/selective-overwrite). -That makes a Spark write bridge feasible, but its schema, conversion and -publication guarantees still need a live Skyulf test. The SQL Connector is an -alternative, not a required part of the first Bundle. +The [SM-15L live test](11-sm15l-live-validation-report.md) passed the +Skyulf bridge, explicit schema, replay and monthly publication checks. +The SQL Connector is an alternative, not a required part of the first Bundle. ## SM-20a prerequisites and generated project @@ -62,11 +62,12 @@ alternative, not a required part of the first Bundle. 2. SM-25 selects pandas or Polars, a pinned model version, bounded source, output table and publication mode before the job starts. 3. SM-24a exposes a local training and batch prediction entry point. -4. SM-15L proves local prediction -> UC Delta publication, including replay, - stale requests and concurrent writers. The current `run_batch` performs +4. [SM-15L](11-sm15l-live-validation-report.md) proves local prediction -> UC + Delta publication, including replay, stale requests and reuse of the + previously tested shared admission. The current `run_batch` performs Spark inference and cannot be called as if it performed local prediction. - Its `publish_replace_period` logic can be reused only with a truthful local - request contract and explicit final-result conversion. + Its `publish_replace_period` logic is reused by `run_local_batch` with a + truthful local request contract and explicit final-result conversion. The custom template should generate a project with these responsibilities: diff --git a/initiatives/spark_and_mlflow/11-sm15l-live-validation-report.md b/initiatives/spark_and_mlflow/11-sm15l-live-validation-report.md new file mode 100644 index 000000000..9d732f40f --- /dev/null +++ b/initiatives/spark_and_mlflow/11-sm15l-live-validation-report.md @@ -0,0 +1,72 @@ +# SM-15L local-engine monthly UC Delta publication + +Status: completed for the documented small-data scope on 2026-09-23. +This report records the specific tested runtime and data; it does not claim +arbitrary local artifacts are Spark-compatible. + +## Contract + +`run_local_batch` reads one pinned source Delta snapshot and month under +`LocalSourceSpec` row/byte limits. It applies the saved pandas or Polars fitted +pipeline in one Python process. Only final keyed predictions become a Spark +DataFrame, with the precreated target's explicit output types. The existing +`publish_replace_period` transaction writes exactly the requested period +using `BatchSpec(mode="local_pipeline")`, source/model digest, expected target +version and shared admission. Spark handles UC I/O only; it does not perform +feature engineering or model inference in this path. No SQL Connector is used. + +## Local evidence + +- Focused SDK/reader tests: 32 passed, 1 optional Spark skip; batch-contract + tests: 25 passed. +- Real local Spark/Delta test in Linux: 6 passed in 49.92 seconds, including + admission denial, invalid target schema, and stale model/source pins with + unchanged target. +- The direct local reader rejects null/duplicate keys, source or final-result + memory over-budget, and accidental empty periods. The publisher rejects + mismatched source/model/period/code/target identities before writing. +- The shared SM-15 writer's real Delta tests separately cover invalid rows, + held admission and denied publication without target mutation. + [SM-16 platform evidence](PLATFORM_VALIDATION.md) records live independent + writer contention and target-write permission denial for this same writer + and admission implementation. SM-15L reuses those components unchanged. + The uploaded wheel predates a later type-only empty-frame constructor change + and SDK docstring correction; both live months exercised the unchanged + nonempty scoring and publication path. + +## Isolated Databricks resources + +- Profile: `skyulf`; schema: `workspace.skyulf_sm24a_20260923`. +- Existing source fixture: `skyulf_sm24a_score_source` at Delta version 0, + with 80 January and 80 February rows. +- Test-owned source: `skyulf_sm15l_source_r1`; test-owned output: + `skyulf_sm15l_predictions_r1`; test-owned control: + `skyulf_sm15l_admission_r1`. +- Test notebook and wheel: + `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm15l_r1`. + Uploaded wheel SHA-256: + `d6b38c52f3a52ebf7f15336561abea850c667acc90253d68ac13b47e2e1ac952`. + Both one-time jobs declare a 900-second timeout and zero retries. +- January pandas LinearRegression model: pinned UC + `workspace.skyulf_sm24a_20260923.skyulf_sm24a_metrics_r1` version 1, + digest `e4281f2feb9349b2dd745bcdd894128c47d434f0bd8779eb42d474adb8aed662`. +- February Polars RandomForestRegressor model: pinned UC + `workspace.skyulf_sm24a_20260923.skyulf_sm24a_metrics_r2` version 1, + digest `efb2174b158d5702be9cc741be3f790721cc43b419f6bc3d0fe3891413f40490`. + +## Monthly job observations + +| Stage | Parent/task run | Source version | Target version | Result | +| --- | --- | ---: | ---: | --- | +| January | `1055645331479835` / `486320682365717` | 0 | 1 | SUCCESS: 80 keyed output rows equal direct local gold; no replay | +| February | `105734608770943` / `850744412284306` | 1 | 2 | SUCCESS: 80 keyed output rows equal direct Polars gold; 80 January rows and metadata unchanged; exact replay kept version 2; stale request rejected | + +The February job appended 80 source rows to version 1 and published only +those predictions. Its live assertions compared all persisted values to direct +local gold by key, checked the 80 January rows and metadata for exact equality, +verified 160 total target rows, replayed without another target version, and +rejected a new logical request with the old expected version. The two-month +scenario intentionally uses two already registered local models to exercise +both pandas and Polars publication. SM-20a will separately test one fixed +pinned model across its generated Bundle's two monthly jobs. No Bundle was +generated or deployed in SM-15L. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index f9ce3e83e..f06a24f4b 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,23 +1,20 @@ # Session handoff - 2026-09-23 -SM-00 through SM-16 are complete for their documented scopes. The selected -Databricks serverless regression workflow passed. Latest user direction: -**Build a small-data pandas/Polars training and local batch path, then its first -working Databricks Bundle. Spark may handle table I/O in that first path; -Spark FE/model execution and its Bundle option follow. -SM-15L is reopened for monthly UC output; SM-18 remains parked. SM-26 local -MLflow packaging, SM-25 SDK preflight and SM-24a live local batch are complete; -start with SM-15L. After the first Bundle, SM-27 adds -explicit full-history rescore and SM-22/SM-28 add optional monthly retraining -with controlled candidate/champion promotion.** -Target release: 0.9.0. Branch: `090`. +SM-00 through SM-16, SM-15L and SM-24a/25/26 are complete for their +documented scopes. The selected Databricks serverless local monthly UC +publication passed with 80 pandas January and 80 Polars February predictions. +Latest user direction: **Build the first small-data pandas/Polars Databricks +Bundle next (SM-20a). Spark handles table I/O; Spark FE/model execution follows +the first working local Bundle. SM-18 and streaming remain parked.** +After the first Bundle, SM-27 adds explicit full-history rescore and +SM-22/SM-28 add optional monthly retraining with controlled candidate/champion +promotion. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-16, SM-24a, SM-25 and SM-26 are complete. Start SM-15L from - [04-databricks-integration-plan.md](04-databricks-integration-plan.md). - The first Bundle and its two-month table rehearsal are specified in - [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). +- SM-00 through SM-16, SM-15L, SM-24a, SM-25 and SM-26 are complete. Start + SM-20a from [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md), including + its two-month table rehearsal. SM-26 added local artifact and MLflow packaging without cloud execution. The SM-25 SDK adds immutable local workflow configuration, local/remote preflight, explicit path or pinned registry artifact selection and caller-frame limits. @@ -28,7 +25,7 @@ Target release: 0.9.0. Branch: `090`. [live report](08-sm24a-live-validation-report.md) records two isolated UC source tables in `workspace.skyulf_sm24a_20260923`, five cross-job models, replay/negative checks and the 62-ID preprocessing matrix. Local-result - Delta writes remain SM-15L; no prediction table or Bundle was created. + Delta writes were subsequently proven in SM-15L; no Bundle was created. The current `max_bytes` limit measures decoded payload and local frame memory, not exact Spark wire bytes; SM-24d tracks a hard transport budget. previous Spark-first direction is superseded. Preserve the later @@ -74,13 +71,13 @@ Target release: 0.9.0. Branch: `090`. remains documented, not relabeled. The aggregate report was generated from actual results and checked against the r3 wheel; all 225 current package files match that wheel. See the platform evidence file for retained resources. -- Local-engine pandas/Polars UC Delta writing is tracked as SM-15L after SM-24a. +- Local-engine pandas/Polars UC Delta writing passed SM-15L after SM-24a. The current Spark `run_batch` performs inference itself and cannot be used for local predictions unchanged. Prefer a bounded local-result -> Spark DataFrame bridge into guarded Delta publication; SQL Connector is optional. The later local-first Bundle request supersedes the earlier one-day deferral. - Start with explicit local source/target, memory/provenance and transaction - contracts. A delta-rs filesystem test + See the [SM-15L report](11-sm15l-live-validation-report.md) for pinned + models, monthly UC rows, replay, stale rejection and local negative tests. A delta-rs filesystem test must not be presented as UC managed-table writer support; see the current platform document's external-client constraints. - SM-15 baseline: `4a613cb5`. Its implementation and verification are in the diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 87322fb35..d6fd49658 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,15 +1,16 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00–SM-16 and SM-24a/25/26 complete; SM-15L next. Target: 0.9.0.** +Updated: 2026-09-23. **SM-00–SM-16 and SM-15L/24a/25/26 complete; SM-20a next. Target: 0.9.0.** First deliverable: pandas/Polars training and local batch on Databricks, then a -working local-engine Bundle. Spark expansion follows that Bundle. SM-15L is -reopened for monthly UC output; SM-18 and continuous streaming remain parked. +working local-engine Bundle. Spark expansion follows that Bundle. SM-15L now +provides monthly UC output; SM-18 and continuous streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-15L. +and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-20a. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). -SM-26 added a local MLflow package; no Bundle was generated or cloud job started. +SM-26 added a local MLflow package; SM-15L validated a UC writer. +No Bundle has been generated. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -35,13 +36,13 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | | SM-16 | Gerçek Databricks kapısı | SM-15 | DONE | Selected serverless workflow passed; live evidence below | -| SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | READY | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | +| SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | DONE | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | | SM-17 | Complete existing Spark node/model coverage | SM-20a | LATER | Resume only after the first local Bundle; preserve all inventoried gaps | | SM-18 | Backend/Canvas and legacy artifact bridge | SM-17 | PARKED | Capability UI/API, DAG contracts and existing deployment compatibility | | SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | | SM-25 | Local-first config / SDK preflight | SM-26 | DONE | Immutable local config; pinned artifact load, bounded frame and actionable preflight; no node/model allowlist | | SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | -| SM-20a | First local-engine Bundle/template | SM-24a, verified SM-15L | WAIT | Generate, validate, deploy and run pandas/Polars train/monthly batch with pinned MLflow/UC model | +| SM-20a | First local-engine Bundle/template | SM-24a, verified SM-15L | READY | Generate, validate, deploy and run pandas/Polars train/monthly batch with pinned MLflow/UC model | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | | SM-22 | Optional model validation and controlled promotion | SM-20a, current evaluation/registry | LATER | Pinned candidate/champion comparison, explicit version promotion and rollback | @@ -143,6 +144,26 @@ SM-17 requires the full tracked scope above. Some algorithms may need an explici alternative backend rather than an equivalent native Spark implementation; that decision must not hide missing support. SM-19 streaming remains optional and parked. +## SM-15L - 2026-09-23 monthly local UC Delta publication, DONE + +- Added `run_local_batch` with truthful `local_pipeline` publication mode. + It loads one pinned UC source month under row/byte limits, scores through + fitted pandas or Polars FE/model code, converts only final keyed results to + an explicitly typed Spark DataFrame, and reuses guarded Delta period writes. + The target and admission control table are provisioned separately. +- Focused SDK/reader tests: **32 passed, 1 optional Spark skip**; batch + contracts: **25 passed**. Real local Spark/Delta: **6 passed**, including + two months, exact replay, stale version, accidental empty period, admission + denial, invalid target schema and stale model/source pins without mutation. Ruff, Ty and strict + MkDocs passed for the changed scope. +- Two isolated Databricks serverless jobs completed **SUCCESS**. January + published 80 pandas predictions to target version 1. February appended 80 + source rows, published 80 Polars predictions to target version 2, preserved + all January rows/metadata, replayed without a new commit, and rejected a + stale logical request. Both periods matched direct local gold by key. + See the [SM-15L live report](11-sm15l-live-validation-report.md) for run IDs, + model digests, test resources and scope limits. Next: SM-20a Bundle. + ## SM-24a — 2026-09-23 local and Databricks validation, DONE - Added explicit bounded pandas/Polars training and a pinned UC Delta monthly @@ -174,7 +195,7 @@ decision must not hide missing support. SM-19 streaming remains optional and par - The Spark iterator does not expose actual wire-byte counts. `max_bytes` bounds accepted decoded rows and local-frame memory; a very wide row can arrive before rejection. [SM-24d](OPEN_QUEUE.md) retains the stronger - transport-budget option for wider or larger workloads. Next: SM-15L. + transport-budget option for wider or larger workloads. Next: SM-20a. ## SM-25 — 2026-09-23 local SDK validation, DONE diff --git a/skyulf-core/examples/databricks_local_sm15l_job.py b/skyulf-core/examples/databricks_local_sm15l_job.py new file mode 100644 index 000000000..c756a988c --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm15l_job.py @@ -0,0 +1,268 @@ +# Databricks notebook source +"""Isolated SM-15L UC Delta two-job publication rehearsal.""" + +from __future__ import annotations + +import json +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from importlib.metadata import version +from typing import Any, Literal + +import numpy as np + +from skyulf.integrations.databricks import ( + BatchSpec, + InputSource, + LocalSourceSpec, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + prepare_local_workflow, + run_local_batch, + score_local_source, +) +from skyulf.integrations.databricks.admission import BatchConflictError +from skyulf.integrations.databricks.delta import history, table_identity +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + +SCHEMA = "workspace.skyulf_sm24a_20260923" +BASE_SOURCE = f"{SCHEMA}.skyulf_sm24a_score_source" +SOURCE = f"{SCHEMA}.skyulf_sm15l_source_r1" +TARGET = f"{SCHEMA}.skyulf_sm15l_predictions_r1" +CONTROL = f"{SCHEMA}.skyulf_sm15l_admission_r1" +MODELS = { + "pandas": ("workspace.skyulf_sm24a_20260923.skyulf_sm24a_metrics_r1", "1", ("x", "z")), + "polars": ("workspace.skyulf_sm24a_20260923.skyulf_sm24a_metrics_r2", "1", ("x", "z", "city")), +} +PERIODS = { + "january": (datetime(2026, 1, 1, tzinfo=UTC), datetime(2026, 2, 1, tzinfo=UTC)), + "february": (datetime(2026, 2, 1, tzinfo=UTC), datetime(2026, 3, 1, tzinfo=UTC)), +} + + +def _source_spec(month: str, source_version: int, columns: tuple[str, ...]) -> LocalSourceSpec: + """Bind a narrow, finite read to one existing Delta snapshot.""" + start, end = PERIODS[month] + return LocalSourceSpec( + table=SOURCE, + version=source_version, + period_start=start, + period_end=end, + row_keys=("entity_id",), + input_columns=columns, + max_rows=100, + max_bytes=4_000_000, + ) + + +def _prepared( + month: str, engine: Literal["pandas", "polars"], source_version: int +) -> tuple[Any, LocalSourceSpec]: + """Resolve a concrete UC model version and its fitted local engine.""" + name, model_version, columns = MODELS[engine] + source = _source_spec(month, source_version, columns) + config = LocalWorkflowConfig( + runtime="databricks", + engine=engine, + source=InputSource( + kind="uc_table", + table=SOURCE, + version=source_version, + max_rows=source.max_rows, + max_bytes=source.max_bytes, + ), + model=ModelSelection( + kind="local_pipeline", + name=name, + version=model_version, + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + sink=OutputSink(kind="uc_delta", table=TARGET), + ) + return prepare_local_workflow(config), source + + +def _request( + source: LocalSourceSpec, prepared: Any, *, run_id: str, expected_target_version: int +) -> BatchSpec: + """Make the source, model and expected target state explicit.""" + digest = prepared.preflight.model_digest + if not digest: + raise ValueError("Prepared model has no digest.") + name = prepared.config.model.name + model_version = prepared.preflight.model_version + if not name or not model_version: + raise ValueError("Prepared model has no concrete registry identity.") + return BatchSpec( + period_start=source.period_start, + period_end=source.period_end, + as_of=datetime.now(UTC) + timedelta(minutes=2), + row_keys=source.row_keys, + output_table=TARGET, + model_name=name, + model_version=model_version, + source_version=source.version, + code_version=version("skyulf-core"), + run_id=run_id, + model_digest=digest, + expected_target_version=expected_target_version, + mode="local_pipeline", + ) + + +def _verify_month( + spark: Any, source: LocalSourceSpec, prepared: Any, run_id: str +) -> dict[str, Any]: + """Compare every persisted prediction to the direct local score by business key.""" + gold = score_local_source(spark, source, prepared).predictions.set_index("entity_id") + from pyspark.sql import functions as F + + rows = ( + spark.table(TARGET) + .where( + (F.col("event_time") >= F.lit(source.period_start)) + & (F.col("event_time") < F.lit(source.period_end)) + ) + .select("entity_id", "prediction", "__skyulf_run_id") + .orderBy("entity_id") + .collect() + ) + actual_keys = [row["entity_id"] for row in rows] + expected_keys = sorted(gold.index.tolist()) + if actual_keys != expected_keys or any(row["__skyulf_run_id"] != run_id for row in rows): + raise AssertionError("Persisted keys or run metadata differ from the local gold rows.") + np.testing.assert_allclose( + [row["prediction"] for row in rows], + gold.loc[actual_keys, "prediction"].to_numpy(), + rtol=0, + atol=1e-9, + ) + return {"rows": len(rows), "keys": actual_keys, "run_id": run_id} + + +def january(spark: Any) -> dict[str, Any]: + """Create only test-owned tables and publish January with the pandas model.""" + for table in (SOURCE, TARGET, CONTROL): + if spark.catalog.tableExists(table): + raise ValueError(f"Test table already exists: {table}") + from pyspark.sql import functions as F + + base = spark.read.format("delta").option("versionAsOf", 0).table(BASE_SOURCE) + month_start, month_end = PERIODS["january"] + base.where( + (F.col("event_time") >= F.lit(month_start)) & (F.col("event_time") < F.lit(month_end)) + ).write.format("delta").saveAsTable(SOURCE) + spark.sql( + f"CREATE TABLE {TARGET} (entity_id STRING, event_time TIMESTAMP, prediction DOUBLE, " + "__skyulf_run_id STRING, __skyulf_model_name STRING, __skyulf_model_version STRING) USING DELTA" + ) + spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") + target_id = table_identity(spark, TARGET) + spark.sql( + f"INSERT INTO {CONTROL} SELECT :target_id, CAST(NULL AS STRING)", + args={"target_id": target_id}, + ).collect() + prepared, source = _prepared("january", "pandas", 0) + request = _request(source, prepared, run_id="sm15l-january-r1", expected_target_version=0) + result = run_local_batch( + spark, source, prepared, request, admission=DeltaTableAdmission(spark, CONTROL) + ) + verified = _verify_month(spark, source, prepared, request.run_id) + if result.output_count != 80 or verified["rows"] != 80: + raise AssertionError("January must publish exactly 80 keyed predictions.") + return { + "stage": "january", + "source_version": 0, + "target_version": result.commit_version, + "model_name": request.model_name, + "model_version": request.model_version, + "model_digest": request.model_digest, + "verified_rows": verified["rows"], + "replayed": result.replayed, + } + + +def february(spark: Any) -> dict[str, Any]: + """Append February source rows and publish only February with the Polars model.""" + from pyspark.sql import functions as F + + latest = int(history(spark, SOURCE).select("version").first()["version"]) + if latest != 0: + raise ValueError("February stage requires the original January-only source.") + january_before = ( + spark.table(TARGET) + .where( + (F.col("event_time") >= F.lit(PERIODS["january"][0])) + & (F.col("event_time") < F.lit(PERIODS["january"][1])) + ) + .orderBy("entity_id") + .collect() + ) + if len(january_before) != 80: + raise ValueError("January must be committed before February starts.") + base = spark.read.format("delta").option("versionAsOf", 0).table(BASE_SOURCE) + month_start, month_end = PERIODS["february"] + base.where( + (F.col("event_time") >= F.lit(month_start)) & (F.col("event_time") < F.lit(month_end)) + ).write.format("delta").mode("append").saveAsTable(SOURCE) + prepared, source = _prepared("february", "polars", 1) + request = _request(source, prepared, run_id="sm15l-february-r1", expected_target_version=1) + admission = DeltaTableAdmission(spark, CONTROL) + result = run_local_batch(spark, source, prepared, request, admission=admission) + verified = _verify_month(spark, source, prepared, request.run_id) + replay = run_local_batch(spark, source, prepared, request, admission=admission) + january_after = ( + spark.table(TARGET) + .where( + (F.col("event_time") >= F.lit(PERIODS["january"][0])) + & (F.col("event_time") < F.lit(PERIODS["january"][1])) + ) + .orderBy("entity_id") + .collect() + ) + if january_after != january_before: + raise AssertionError("February publication changed January predictions or metadata.") + if not replay.replayed or replay.commit_version != result.commit_version: + raise AssertionError("Replay must reuse the committed February receipt.") + try: + run_local_batch( + spark, + source, + prepared, + replace(request, run_id="sm15l-stale-r1", expected_target_version=1), + admission=admission, + ) + except BatchConflictError: + stale_rejected = True + else: + stale_rejected = False + if not stale_rejected or spark.table(TARGET).count() != 160: + raise AssertionError("Stale publication changed the target or was not rejected.") + return { + "stage": "february", + "source_version": 1, + "target_version": result.commit_version, + "model_name": request.model_name, + "model_version": request.model_version, + "model_digest": request.model_digest, + "verified_rows": verified["rows"], + "january_preserved": len(january_after), + "replay_version": replay.commit_version, + "stale_rejected": stale_rejected, + } + + +runtime_dbutils: Any = globals().get("dbutils") +runtime_spark: Any = globals().get("spark") +if runtime_dbutils is not None and runtime_spark is not None: + runtime_dbutils.widgets.text("stage", "january") + stage = runtime_dbutils.widgets.get("stage") + if stage == "january": + result = january(runtime_spark) + elif stage == "february": + result = february(runtime_spark) + else: + raise ValueError(f"Unknown SM-15L stage: {stage}") + runtime_dbutils.notebook.exit(json.dumps(result)) diff --git a/skyulf-core/skyulf/integrations/databricks/__init__.py b/skyulf-core/skyulf/integrations/databricks/__init__.py index 510f2cb56..5ba096b60 100644 --- a/skyulf-core/skyulf/integrations/databricks/__init__.py +++ b/skyulf-core/skyulf/integrations/databricks/__init__.py @@ -9,6 +9,7 @@ read_local_source, score_local_source, ) +from .local_publish import run_local_batch from .local_sdk import ( InputSource, LocalWorkflowConfig, @@ -41,5 +42,6 @@ "prepare_local_workflow", "read_local_source", "run_batch", + "run_local_batch", "score_local_source", ] diff --git a/skyulf-core/skyulf/integrations/databricks/_contracts.py b/skyulf-core/skyulf/integrations/databricks/_contracts.py index ca2f2d99f..422945631 100644 --- a/skyulf-core/skyulf/integrations/databricks/_contracts.py +++ b/skyulf-core/skyulf/integrations/databricks/_contracts.py @@ -91,8 +91,8 @@ def __post_init__(self) -> None: r"[0-9a-f]{64}", self.model_digest ): raise ValueError("model_digest must be a SHA-256 bundle digest.") - if self.mode not in ("native_features", "python_pipeline"): - raise ValueError("mode must be native_features or python_pipeline.") + if self.mode not in ("native_features", "python_pipeline", "local_pipeline"): + raise ValueError("mode must be native_features, python_pipeline or local_pipeline.") if self.publish_mode != "replace_period": raise ValueError("Only replace_period publication is supported.") if type(self.allow_empty) is not bool: diff --git a/skyulf-core/skyulf/integrations/databricks/batch.py b/skyulf-core/skyulf/integrations/databricks/batch.py index f4786ebcf..2d7fd0c81 100644 --- a/skyulf-core/skyulf/integrations/databricks/batch.py +++ b/skyulf-core/skyulf/integrations/databricks/batch.py @@ -40,6 +40,8 @@ def run_batch( raise ValueError("run_batch requires ExecutionOptions(engine='spark').") if not isinstance(spec, BatchSpec): raise TypeError("spec must be BatchSpec.") + if spec.mode == "local_pipeline": + raise ValueError("run_batch requires a Spark inference mode.") admission = validate_admission(spark, admission) table_name(source) _validate_bundle(bundle, options) diff --git a/skyulf-core/skyulf/integrations/databricks/local_batch.py b/skyulf-core/skyulf/integrations/databricks/local_batch.py index 791990612..710800998 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_batch.py +++ b/skyulf-core/skyulf/integrations/databricks/local_batch.py @@ -204,6 +204,8 @@ def read_local_source(spark: Any, spec: LocalSourceSpec) -> pd.DataFrame: frame = pd.DataFrame.from_records(records, columns=names) if _frame_bytes(frame) > spec.max_bytes: raise ValueError("Source local frame exceeds max_bytes.") + if frame.loc[:, list(spec.row_keys)].isna().any().any(): + raise ValueError("Source row keys must not be null.") if frame.duplicated(subset=list(spec.row_keys)).any(): raise ValueError("Source row keys must be unique within the requested period.") return frame @@ -228,7 +230,11 @@ def score_local_source( if spec.input_columns != expected: raise ValueError("Source inputs must match the saved model's raw column order.") frame = read_local_source(spark, spec) - predictions = prepared.predict(frame.loc[:, list(spec.input_columns)]) + predictions = ( + pd.DataFrame(columns=pd.Index(prepared.preflight.output_columns)) + if frame.empty + else prepared.predict(frame.loc[:, list(spec.input_columns)]) + ) if len(predictions) != len(frame): raise ValueError("Prediction changed source row membership.") result = pd.concat( @@ -238,6 +244,8 @@ def score_local_source( ], axis=1, ) + if _frame_bytes(result) > spec.max_bytes: + raise ValueError("Prediction result exceeds max_bytes.") diagnostics: dict[str, str | int] = { "source_table": spec.table, "source_version": spec.version, diff --git a/skyulf-core/skyulf/integrations/databricks/local_publish.py b/skyulf-core/skyulf/integrations/databricks/local_publish.py new file mode 100644 index 000000000..11a638fb0 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_publish.py @@ -0,0 +1,193 @@ +"""Publish bounded local predictions through the existing guarded Delta writer.""" + +from __future__ import annotations + +import importlib +import math +from importlib.metadata import version +from typing import Any + +import numpy as np +import pandas as pd + +from ...inference.local_pipeline import LocalPipelineArtifact +from ._contracts import BatchResult, BatchSpec +from .admission import PublishAdmission, validate_admission +from .batch import _manifest +from .delta import history, publish_replace_period, table_identity +from .local_batch import LocalSourceSpec, score_local_source +from .local_sdk import PreparedLocalWorkflow + +_OUTPUT_TYPES = {"float64": "double", "int64": "long", "string": "string", "bool": "boolean"} +_METADATA = ("__skyulf_run_id", "__skyulf_model_name", "__skyulf_model_version") + + +def _validate_request( + spark: Any, + source: LocalSourceSpec, + prepared: PreparedLocalWorkflow, + spec: BatchSpec, + admission: PublishAdmission | None, +) -> PublishAdmission: + """Reject mismatched model, source and target identities before scoring.""" + if not isinstance(source, LocalSourceSpec) or not isinstance(prepared, PreparedLocalWorkflow): + raise TypeError("Local publication requires a source spec and prepared workflow.") + if not isinstance(spec, BatchSpec) or spec.mode != "local_pipeline": + raise ValueError("Local publication requires BatchSpec(mode='local_pipeline').") + admission = validate_admission(spark, admission) + if not prepared.preflight.ready or not isinstance(prepared.artifact, LocalPipelineArtifact): + raise ValueError("Local publication requires a ready fitted local pipeline.") + config = prepared.config + if config.runtime != "databricks" or config.sink.kind != "uc_delta": + raise ValueError("Local publication requires a Databricks UC Delta sink.") + if config.sink.table != spec.output_table or config.source.kind != "uc_table": + raise ValueError("Configured UC source or target differs from the publication request.") + if config.source.table != source.table or config.source.version != source.version: + raise ValueError("Prepared source differs from the pinned Delta snapshot.") + if source.max_rows > config.source.max_rows or source.max_bytes > config.source.max_bytes: + raise ValueError("Source budget exceeds the prepared workflow budget.") + if config.model.kind != "local_pipeline" or config.model.name != spec.model_name: + raise ValueError("Publication model name differs from the prepared registry model.") + if prepared.preflight.model_version != spec.model_version: + raise ValueError("Publication model version differs from the pinned model.") + if prepared.preflight.model_digest != spec.model_digest: + raise ValueError("Publication model digest differs from the fitted artifact.") + if spec.code_version != version("skyulf-core"): + raise ValueError("Publication code version differs from the installed runtime.") + if ( + spec.source_version != source.version + or spec.row_keys != source.row_keys + or spec.period_column != source.period_column + or spec.period_start_utc != source.period_start.astimezone(spec.period_start_utc.tzinfo) + or spec.period_end_utc != source.period_end.astimezone(spec.period_end_utc.tzinfo) + or spec.business_timezone != source.business_timezone + ): + raise ValueError("Publication period and source contract must match exactly.") + if source.table == spec.output_table: + raise ValueError("Source and prediction target must be different tables.") + return admission + + +def _check_target( + spark: Any, + source_frame: Any, + target: Any, + source: LocalSourceSpec, + prepared: PreparedLocalWorkflow, +) -> tuple[str, ...]: + """Require a precreated target with exact key, output and metadata types.""" + outputs = prepared.preflight.output_schema + names = tuple(column.name for column in outputs) + expected = {*source.row_keys, source.period_column, *names, *_METADATA} + if len(expected) != len(source.row_keys) + len(names) + 4 or set(target.columns) != expected: + raise ValueError("Prediction target columns differ from the explicit local output schema.") + if target.schema[source.period_column].dataType.typeName() != "timestamp": + raise ValueError("Prediction target period must be a Spark timestamp.") + if source_frame.schema[source.period_column].dataType.typeName() != "timestamp": + raise ValueError("Source period must be a Spark timestamp.") + for name in source.row_keys: + target_type = target.schema[name].dataType + if target_type != source_frame.schema[name].dataType or target_type.typeName() not in ( + "long", + "string", + ): + raise ValueError("Source and target row-key types must match and be long or string.") + for column in outputs: + expected_type = _OUTPUT_TYPES.get(column.dtype) + if expected_type is None or target.schema[column.name].dataType.typeName() != expected_type: + raise ValueError(f"Target output type differs from saved model output {column.name!r}.") + if any(target.schema[name].dataType.typeName() != "string" for name in _METADATA): + raise ValueError("Prediction target metadata columns must be strings.") + return names + + +def _scalar(value: Any) -> Any: + """Convert bounded pandas/NumPy scalars without changing their logical type.""" + if value is None or value is pd.NA: + return None + if isinstance(value, np.generic): + value = value.item() + if isinstance(value, float) and (math.isnan(value) or math.isinf(value)): + raise ValueError("Prediction output contains a nonfinite number.") + return value + + +def run_local_batch( + spark: Any, + source: LocalSourceSpec, + prepared: PreparedLocalWorkflow, + spec: BatchSpec, + *, + admission: PublishAdmission | None, +) -> BatchResult: + """Score one pinned month locally and publish only its final rows to Delta.""" + admission = _validate_request(spark, source, prepared, spec, admission) + source_id = table_identity(spark, source.table) + if source_id == table_identity(spark, spec.output_table): + raise ValueError("Source and prediction target must be different Delta tables.") + functions = importlib.import_module("pyspark.sql.functions") + snapshot = ( + history(spark, source.table) + .where(functions.col("version") == source.version) + .select(functions.unix_micros("timestamp").alias("committed_us")) + .first() + ) + if snapshot is None or snapshot.committed_us > int(spec.as_of_utc.timestamp() * 1_000_000): + raise ValueError("Source snapshot was not available at as_of or its history expired.") + scored = score_local_source(spark, source, prepared) + count = len(scored.predictions) + if count == 0 and not spec.allow_empty: + raise ValueError("Empty period replacement requires allow_empty=True.") + if count != scored.diagnostics["row_count"]: + raise ValueError("Scored row count differs from the pinned source.") + if table_identity(spark, source.table) != source_id: + raise ValueError("Source table was replaced while scoring the pinned snapshot.") + source_frame = ( + spark.read.format("delta").option("versionAsOf", source.version).table(source.table) + ) + target = spark.table(spec.output_table) + output_names = _check_target(spark, source_frame, target, source, prepared) + bridge_names = (*source.row_keys, *output_names) + if list(scored.predictions.columns) != list(bridge_names): + raise ValueError("Local prediction columns differ from the saved model output.") + if scored.predictions.loc[:, list(source.row_keys)].isna().any().any(): + raise ValueError("Local prediction row keys must not be null.") + if scored.predictions.duplicated(subset=list(source.row_keys)).any(): + raise ValueError("Local prediction row keys must be unique.") + bridge_schema = target.select(*bridge_names).schema + records = [ + tuple(_scalar(value) for value in row) + for row in scored.predictions.itertuples(index=False, name=None) + ] + bridge = spark.createDataFrame(records, schema=bridge_schema) + period = source_frame[source.period_column] + source_period = source_frame.where( + (period >= functions.lit(spec.period_start_utc)) + & (period < functions.lit(spec.period_end_utc)) + ).select(*source.row_keys, source.period_column) + output = bridge.join(source_period, on=list(source.row_keys), how="inner") + for name, value in ( + ("__skyulf_run_id", spec.run_id), + ("__skyulf_model_name", spec.model_name), + ("__skyulf_model_version", spec.model_version), + ): + output = output.withColumn(name, functions.lit(value)) + if {field.name: field.dataType for field in output.schema} != { + field.name: field.dataType for field in target.schema + }: + raise ValueError("Prediction output schema must match the Delta target exactly.") + output = output.select(*target.columns) + if output.count() != count: + raise ValueError("Prediction keys do not match the pinned source rows.") + manifest = _manifest(spec, source_id, source.table, snapshot.committed_us, count, count) + committed_version, recorded, replayed = publish_replace_period( + spark, output, spec, manifest=manifest, admission=admission + ) + return BatchResult( + spec, + recorded["input_count"], + recorded["output_count"], + committed_version, + recorded, + replayed, + ) diff --git a/skyulf-core/skyulf/integrations/databricks/local_sdk.py b/skyulf-core/skyulf/integrations/databricks/local_sdk.py index ab2e96e67..a11c1cf9f 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_sdk.py +++ b/skyulf-core/skyulf/integrations/databricks/local_sdk.py @@ -29,6 +29,7 @@ RegistryModelNotFoundError, ResolvedModel, ) +from ._contracts import table_name class InputSource(BaseModel): @@ -103,7 +104,7 @@ def validate_selector(self) -> ModelSelection: class OutputSink(BaseModel): - """Select returned predictions or a declared future UC Delta target.""" + """Select returned predictions or a precreated UC Delta target.""" model_config = ConfigDict(frozen=True, extra="forbid", strict=True) kind: Literal["return_frame", "uc_delta"] @@ -205,14 +206,46 @@ def _config_issues(config: LocalWorkflowConfig) -> list[PreflightIssue]: ) ) if config.sink.kind == "uc_delta": - issues.append( - PreflightIssue( - "sink_unavailable", - "sink", - "Local-result UC Delta publication is scheduled for SM-15L.", - "Use return_frame until the guarded local-result sink is available.", + if config.runtime != "databricks": + issues.append( + PreflightIssue( + "sink_runtime_mismatch", + "sink", + "UC Delta publication requires the Databricks runtime.", + "Choose runtime='databricks' for this sink.", + ) + ) + if config.source.kind != "uc_table": + issues.append( + PreflightIssue( + "sink_source_mismatch", + "sink", + "UC Delta publication requires a pinned UC source.", + "Choose an existing UC source table and concrete Delta version.", + ) + ) + try: + if config.sink.table is None or len(config.sink.table.split(".")) != 3: + raise ValueError("A three-part UC target is required.") + table_name(config.sink.table) + except ValueError: + issues.append( + PreflightIssue( + "sink_invalid_target", + "sink", + "UC Delta publication requires a three-part target table.", + "Specify an existing catalog.schema.table target.", + ) + ) + if config.sink.table and config.sink.table.lower() == (config.source.table or "").lower(): + issues.append( + PreflightIssue( + "sink_source_conflict", + "sink", + "Source and target tables must be different.", + "Choose a separate prediction target table.", + ) ) - ) elif config.sink.table is not None: issues.append( PreflightIssue( diff --git a/skyulf-core/tests/integrations/test_batch_contract.py b/skyulf-core/tests/integrations/test_batch_contract.py index e3fee4eb2..a7d7d33ae 100644 --- a/skyulf-core/tests/integrations/test_batch_contract.py +++ b/skyulf-core/tests/integrations/test_batch_contract.py @@ -122,3 +122,17 @@ def test_direct_sink_rejects_local_admission_on_distributed_runtime(spec, tmp_pa publish_replace_period( spark, object(), spec, manifest={}, admission=LocalTableLock(tmp_path) ) + + +def test_local_publication_mode_is_distinct_from_spark_inference(spec) -> None: + """Local model output must declare its actual execution mode.""" + local = replace(spec, mode="local_pipeline") + assert local.mode == "local_pipeline" + with pytest.raises(ValueError, match="Spark inference mode"): + run_batch( + None, + local, + source="default.source", + bundle=cast(Any, object()), + options=ExecutionOptions("spark"), + ) diff --git a/skyulf-core/tests/integrations/test_databricks_local_batch.py b/skyulf-core/tests/integrations/test_databricks_local_batch.py index c3c5d840a..394f5a0a3 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_batch.py +++ b/skyulf-core/tests/integrations/test_databricks_local_batch.py @@ -305,3 +305,43 @@ def table(self, name): assert result.to_dict("records") == [{"entity_id": "jan", "x": 1.0}] finally: spark.stop() + + +def test_reader_rejects_null_row_keys_before_scoring() -> None: + """A missing business key cannot be repaired after local prediction.""" + with pytest.raises(ValueError, match="row keys must not be null"): + read_local_source(_Spark([{"entity_id": None, "x": 2.0}], []), _spec()) + + +def test_scoring_rejects_output_that_exceeds_local_byte_budget(tmp_path) -> None: + """Probability columns must stay inside the declared local memory cap.""" + frame = pd.DataFrame( + {"x": [-4.0, -3.0, -2.0, -1.0, 1.0, 2.0, 3.0, 4.0], "target": [0, 0, 0, 0, 1, 1, 1, 1]} + ) + path = tmp_path / "classifier" + fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "logistic_regression"}}, + SplitDataset(train=frame.iloc[[0, 1, 2, 4, 5, 6]], test=frame.iloc[[3, 7]]), + target_column="target", + artifact_path=path, + max_rows=8, + max_bytes=4096, + ) + prepared = prepare_local_workflow( + LocalWorkflowConfig( + runtime="databricks", + engine="pandas", + source=InputSource( + kind="uc_table", + table="workspace.test.score_source", + version=2, + max_rows=3, + max_bytes=180, + ), + model=ModelSelection(kind="local_pipeline", path=str(path)), + sink=OutputSink(kind="return_frame"), + ) + ) + rows = [{"entity_id": 1, "x": 2.0}, {"entity_id": 2, "x": 4.0}] + with pytest.raises(ValueError, match="Prediction result exceeds max_bytes"): + score_local_source(_Spark(rows, []), _spec(max_bytes=180), prepared) diff --git a/skyulf-core/tests/integrations/test_databricks_local_sdk.py b/skyulf-core/tests/integrations/test_databricks_local_sdk.py index dafcbdf0c..3c6652015 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_sdk.py +++ b/skyulf-core/tests/integrations/test_databricks_local_sdk.py @@ -79,7 +79,7 @@ def test_preflight_selects_local_predictor_and_metadata(tmp_path) -> None: ("changes", "code"), [ ({"engine": "polars"}, "engine_mismatch"), - ({"sink": OutputSink(kind="uc_delta", table="c.s.predictions")}, "sink_unavailable"), + ({"sink": OutputSink(kind="uc_delta", table="c.s.predictions")}, "sink_source_mismatch"), ({"source": InputSource(kind="uc_table", table="c.s.source")}, "source_unbounded"), ({"runtime": "spark"}, "runtime_unsupported"), ], @@ -286,3 +286,15 @@ def test_existing_library_node_and_model_need_no_sdk_allowlist(engine, tmp_path) prepared = prepare_local_workflow(_config(path, engine=engine)) assert prepared.preflight.ready np.testing.assert_allclose(prepared.predict(query)["prediction"], expected) + + +def test_preflight_accepts_bounded_uc_delta_sink(tmp_path) -> None: + """A pinned UC source and explicit target can pass local publish preflight.""" + path, artifact = _artifact(tmp_path) + config = _config( + path, + source=InputSource(kind="uc_table", table="c.s.source", version=2), + sink=OutputSink(kind="uc_delta", table="c.s.predictions"), + ) + result = preflight_local(config, artifact=artifact) + assert result.ready diff --git a/skyulf-core/tests/integrations/test_local_delta_publish.py b/skyulf-core/tests/integrations/test_local_delta_publish.py new file mode 100644 index 000000000..a94c6b43a --- /dev/null +++ b/skyulf-core/tests/integrations/test_local_delta_publish.py @@ -0,0 +1,253 @@ +"""Publish bounded local predictions to a real period-scoped Delta target.""" + +from contextlib import contextmanager +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from importlib.metadata import version +from uuid import uuid4 + +import numpy as np +import pandas as pd +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference._manifest import ColumnSpec +from skyulf.integrations.databricks._contracts import BatchSpec +from skyulf.integrations.databricks.admission import BatchConflictError, LocalTableLock +from skyulf.integrations.databricks.local_batch import LocalSourceSpec, fit_local_workflow +from skyulf.integrations.databricks.local_sdk import ( + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + PreflightResult, + PreparedLocalWorkflow, +) + + +@pytest.fixture +def local_delta_case(delta_spark, tmp_path): + """Provision isolated source, target and a fitted local model for two periods.""" + spark = delta_spark + suffix = uuid4().hex + source = f"spark_catalog.default.local_source_{suffix}" + target = f"spark_catalog.default.local_predictions_{suffix}" + spark.createDataFrame( + [(1, datetime(2026, 1, 5, tzinfo=UTC), 2.0), (2, datetime(2026, 1, 7, tzinfo=UTC), 4.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").saveAsTable(source) + spark.createDataFrame( + [(9, datetime(2025, 12, 1, tzinfo=UTC), 99.0, "prior", "risk", "1")], + "id long, event_time timestamp, prediction double, __skyulf_run_id string, " + "__skyulf_model_name string, __skyulf_model_version string", + ).write.format("delta").saveAsTable(target) + values = np.arange(20, dtype="float64") + data = pd.DataFrame({"x": values, "target": 2.0 * values}) + artifact = fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=data.iloc[:16], test=data.iloc[16:]), + target_column="target", + artifact_path=tmp_path / "fitted", + max_rows=20, + max_bytes=10_000, + ) + config = LocalWorkflowConfig( + runtime="databricks", + engine="pandas", + source=InputSource(kind="uc_table", table=source, version=0, max_rows=10, max_bytes=10_000), + model=ModelSelection(kind="local_pipeline", name="workspace.test.local_model", version="1"), + sink=OutputSink(kind="uc_delta", table=target), + ) + preflight = PreflightResult( + issues=(), + remote_checked=True, + model_version="1", + model_digest=artifact.manifest.pipeline_sha256, + output_schema=(ColumnSpec(name="prediction", dtype="float64"),), + ) + prepared = PreparedLocalWorkflow(config, artifact, preflight) + january = LocalSourceSpec( + table=source, + version=0, + period_start=datetime(2026, 1, 1, tzinfo=UTC), + period_end=datetime(2026, 2, 1, tzinfo=UTC), + row_keys=("id",), + input_columns=("x",), + max_rows=10, + max_bytes=10_000, + ) + request = BatchSpec( + period_start=january.period_start, + period_end=january.period_end, + as_of=datetime.now(UTC) + timedelta(minutes=10), + row_keys=("id",), + output_table=target, + model_name="workspace.test.local_model", + model_version="1", + source_version=0, + code_version=version("skyulf-core"), + run_id="january-local", + model_digest=artifact.manifest.pipeline_sha256, + expected_target_version=0, + mode="local_pipeline", + ) + try: + yield spark, source, target, prepared, january, request, LocalTableLock(tmp_path / "locks") + finally: + spark.sql(f"DROP TABLE IF EXISTS {source}") + spark.sql(f"DROP TABLE IF EXISTS {target}") + + +def test_local_predictions_publish_two_months_and_replay(local_delta_case): + """A second month adds only its rows and replay cannot rewrite either month.""" + from skyulf.integrations.databricks import run_local_batch + + spark, source, target, prepared, january, request, admission = local_delta_case + first = run_local_batch(spark, january, prepared, request, admission=admission) + spark.createDataFrame( + [(3, datetime(2026, 2, 5, tzinfo=UTC), 6.0), (4, datetime(2026, 2, 7, tzinfo=UTC), 8.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + february = replace( + january, + version=1, + period_start=datetime(2026, 2, 1, tzinfo=UTC), + period_end=datetime(2026, 3, 1, tzinfo=UTC), + ) + config = prepared.config.model_copy( + update={ + "source": InputSource( + kind="uc_table", table=source, version=1, max_rows=10, max_bytes=10_000 + ) + } + ) + prepared_february = replace(prepared, config=config) + next_request = replace( + request, + period_start=february.period_start, + period_end=february.period_end, + source_version=1, + run_id="february-local", + expected_target_version=first.commit_version, + ) + second = run_local_batch(spark, february, prepared_february, next_request, admission=admission) + replay = run_local_batch(spark, february, prepared_february, next_request, admission=admission) + rows = spark.table(target).orderBy("id").collect() + assert [(row.id, round(row.prediction), row["__skyulf_run_id"]) for row in rows] == [ + (1, 4, "january-local"), + (2, 8, "january-local"), + (3, 12, "february-local"), + (4, 16, "february-local"), + (9, 99, "prior"), + ] + assert first.input_count == second.input_count == replay.input_count == 2 + assert replay.replayed and replay.commit_version == second.commit_version + with pytest.raises(BatchConflictError): + run_local_batch( + spark, + february, + prepared_february, + replace( + next_request, run_id="stale-local", expected_target_version=first.commit_version + ), + admission=admission, + ) + assert spark.table(target).count() == 5 + + +def test_local_publisher_is_available() -> None: + """Local publication needs its own entry point separate from Spark scoring.""" + from skyulf.integrations.databricks import run_local_batch + + assert callable(run_local_batch) + + +def test_empty_local_month_rejects_without_changing_target(local_delta_case): + """An accidental empty monthly source must not erase an existing Delta period.""" + from skyulf.integrations.databricks import run_local_batch + + spark, _, target, prepared, january, request, admission = local_delta_case + empty = replace( + january, + period_start=datetime(2026, 3, 1, tzinfo=UTC), + period_end=datetime(2026, 4, 1, tzinfo=UTC), + ) + empty_request = replace( + request, + period_start=empty.period_start, + period_end=empty.period_end, + run_id="empty-local", + ) + with pytest.raises(ValueError, match="Empty period replacement requires allow_empty=True"): + run_local_batch(spark, empty, prepared, empty_request, admission=admission) + assert spark.table(target).count() == 1 + allowed = run_local_batch( + spark, empty, prepared, replace(empty_request, allow_empty=True), admission=admission + ) + assert allowed.output_count == 0 + assert spark.table(target).count() == 1 + + +def test_local_publisher_denied_admission_preserves_target(local_delta_case): + """An admission denial must propagate without changing the prediction table.""" + from skyulf.integrations.databricks import run_local_batch + + class DeniedAdmission: + """Simulate a distributed authority that denies this writer.""" + + local_only = False + + @contextmanager + def hold(self, table_id): + """Raise before granting publication authority.""" + raise PermissionError("publish access denied") + yield # pragma: no cover - context manager contract + + spark, _, target, prepared, january, request, _ = local_delta_case + before_version = spark.sql(f"DESCRIBE HISTORY {target}").first().version + with pytest.raises(PermissionError, match="access denied"): + run_local_batch(spark, january, prepared, request, admission=DeniedAdmission()) + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before_version + assert [row.id for row in spark.table(target).collect()] == [9] + + +def test_local_publisher_rejects_target_schema_before_commit(local_delta_case): + """A target/output dtype mismatch must not stage a Delta period replacement.""" + from skyulf.integrations.databricks import run_local_batch + + spark, _, target, prepared, january, request, admission = local_delta_case + invalid = replace( + prepared, + preflight=replace( + prepared.preflight, + output_schema=(ColumnSpec(name="prediction", dtype="string"),), + ), + ) + before_version = spark.sql(f"DESCRIBE HISTORY {target}").first().version + with pytest.raises(ValueError, match="Target output type"): + run_local_batch(spark, january, invalid, request, admission=admission) + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before_version + assert [row.id for row in spark.table(target).collect()] == [9] + + +def test_local_publisher_rejects_stale_model_and_source_identity(local_delta_case): + """Changed model or source pins must fail before touching the Delta target.""" + from skyulf.integrations.databricks import run_local_batch + + spark, _, target, prepared, january, request, admission = local_delta_case + before_version = spark.sql(f"DESCRIBE HISTORY {target}").first().version + for field, value, message in ( + ("model_version", "2", "model version"), + ("model_digest", "0" * 64, "model digest"), + ("source_version", 1, "source contract"), + ): + with pytest.raises(ValueError, match=message): + run_local_batch( + spark, + january, + prepared, + replace(request, **{field: value}), + admission=admission, + ) + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before_version + assert [row.id for row in spark.table(target).collect()] == [9] From b597fddae5faf404186b10adc731a72d0034c38e Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 19:07:32 +0300 Subject: [PATCH 34/85] feat: score new Delta records automatically with local models Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 8 + docs/user_guide/databricks_local_sdk.md | 68 +++- .../04-databricks-integration-plan.md | 60 +-- .../spark_and_mlflow/05-sm20-bundle-plan.md | 90 ++--- .../12-sm15i-incremental-scoring-plan.md | 82 ++++ .../13-sm15i-live-validation-report.md | 62 +++ initiatives/spark_and_mlflow/HANDOFF.md | 20 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 59 ++- .../examples/databricks_local_sm15i_job.py | 161 ++++++++ .../integrations/databricks/__init__.py | 3 + .../databricks/local_incremental.py | 333 ++++++++++++++++ .../integrations/databricks/local_publish.py | 28 +- .../integrations/databricks/local_sdk.py | 20 +- .../integrations/test_databricks_local_sdk.py | 17 + .../integrations/test_local_delta_publish.py | 369 ++++++++++++++++++ 15 files changed, 1272 insertions(+), 108 deletions(-) create mode 100644 initiatives/spark_and_mlflow/12-sm15i-incremental-scoring-plan.md create mode 100644 initiatives/spark_and_mlflow/13-sm15i-live-validation-report.md create mode 100644 skyulf-core/examples/databricks_local_sm15i_job.py create mode 100644 skyulf-core/skyulf/integrations/databricks/local_incremental.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 3253e79ed..4b21d5789 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -39,6 +39,14 @@ execution, MLflow registry and Databricks delivery remain under development. accidental empty or stale writes. Isolated serverless jobs verified 80 predictions for each of two months, preserved prior rows and replayed without another commit. No SQL Connector or Spark FE/model execution is required. +- Automatic incremental local batch scoring reads an initial bounded Delta + snapshot, then only new inserts from Change Data Feed. It appends keyed + predictions and the source-version receipt in one guarded Delta commit; + scheduled runs need no manual dates or source versions. A source timestamp + is optional, and updates/deletes or duplicate keys fail explicitly. + Real local Delta tests cover pandas, Polars and retry/no-op behavior. Two + isolated serverless jobs validated initial 80-row scoring, automatic scoring + of 80 later inserts, unchanged prior predictions and a no-op replay. - Versioned local pandas/Polars pipeline artifact and MLflow pyfunc packaging preserve fitted encoding/binning, model state, input order, class probabilities and explicit tuned thresholds without refitting. The fit engine and exact diff --git a/docs/user_guide/databricks_local_sdk.md b/docs/user_guide/databricks_local_sdk.md index 51a895286..b95da5e03 100644 --- a/docs/user_guide/databricks_local_sdk.md +++ b/docs/user_guide/databricks_local_sdk.md @@ -8,9 +8,9 @@ The same code also runs with `runtime="local"`. No Bundle project or SM-25 provides configuration, artifact selection and preflight. It accepts a caller-owned, bounded pandas/Polars frame and returns predictions. SM-24a adds -an explicit, versioned UC Delta source reader for monthly local batches. -Guarded UC Delta publication remains SM-15L; choosing that sink still produces -a `PreflightError` before a job is submitted. +an explicit, versioned UC Delta source reader for selected-period local batches. +SM-15L publishes an explicitly selected period to UC Delta. The separate +incremental runner below discovers new source inserts automatically. ## Fit and score a small batch @@ -338,3 +338,65 @@ result both enforce the configured local row and memory budgets; this does not measure Spark's private wire bytes. The control-row admission protocol protects participating writers only; do not let other jobs bypass it or manually clear an owner while a writer may still be active. + + +## Score newly inserted rows automatically + +`run_incremental_local_batch` selects records by **Delta source commits**, not +by calendar date. On the first run it scores the existing bounded snapshot. On +later runs it reads only inserts after the source version recorded in the last +prediction-table commit. It appends predictions without replacing an older +period. A source `event_time` column is optional; if you want to carry it into +the target, set `period_column="event_time"` in the stable job configuration. +It never filters rows by that column, including late arrivals. + +Provision a distinct, initially empty Delta prediction table with the +globally unique key, saved model output columns and +`__skyulf_run_id`, `__skyulf_model_name`, `__skyulf_model_version` string +columns. If carrying an event timestamp, add a matching Spark `timestamp` +column to both tables. Enable Delta Change Data Feed on the source **before** +any changes that the job must consume. Provision the same shared admission +control table used by the explicit-period writer; all target writers must use +that admission authority. The job identity needs source, model, target and +control-table permissions. + +```python +from skyulf.integrations.databricks import ( + InputSource, LocalWorkflowConfig, ModelSelection, OutputSink, + prepare_local_workflow, run_incremental_local_batch, +) +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + +config = LocalWorkflowConfig( + runtime="databricks", + engine="polars", + source=InputSource( + kind="uc_table", table="catalog.schema.new_records", + read_mode="incremental", max_rows=10_000, max_bytes=32_000_000, + ), + model=ModelSelection( + kind="local_pipeline", name="catalog.schema.customer_model", version="7", + tracking_uri="databricks", registry_uri="databricks-uc", + ), + sink=OutputSink(kind="uc_delta", table="catalog.schema.predictions"), +) +prepared = prepare_local_workflow(config) +result = run_incremental_local_batch( + spark, prepared, row_keys=("event_id",), + admission=DeltaTableAdmission(spark, "catalog.schema.prediction_admission"), +) +print(result.input_count, result.commit_version, result.noop) +``` + +Keep this configuration for scheduled runs; do not supply a period or source +version on each invocation. A repeat run with no new source inserts makes no +target write. If an append succeeds but its acknowledgement is lost, the next +run reads its committed receipt and continues after that source version. +Source updates and deletes, duplicate keys, a missing or expired change feed, +and an unrecognized target commit fail without advancing the watermark. +Key uniqueness must hold across all runs, not only within one batch. Oversized +increments fail under the same local row/decoded-memory limits; increase the +budget deliberately or handle such a source with a separate distributed path. +The target receipt is in the same Delta commit as the predictions. This +protects participating writers only; changes outside the admission protocol +must be handled explicitly. diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md index 0fa362cfe..af8f4bb80 100644 --- a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -1,7 +1,7 @@ # Local-first Databricks integration and Bundle plan -Updated: 2026-09-23. SM-26, SM-25, SM-24a and SM-15L are implemented and -validated; the first Bundle remains planned. +Updated: 2026-09-23. SM-26, SM-25, SM-24a, SM-15L and SM-15I are implemented +and validated for their documented scopes; the first Bundle remains planned. Baseline: `63dd3e21` and the completed, scoped SM-16 evidence. ## Current direction @@ -11,8 +11,8 @@ for fitted FE and a Python model. Local means one Python process, which may run inside a Databricks job; it does not mean the user's laptop. A bounded Spark bridge may handle UC table I/O after local prediction; native Spark FE/model execution remains a later task. Build and validate that project before extending -its prediction jobs with Spark. The latest direction reopens -SM-15L as a prerequisite for monthly UC table output in the first Bundle. +its prediction jobs with Spark. SM-15L handles explicit-period backfills; +SM-15I provides automatic new-row scoring required by the first Bundle. SM-18 Backend/Canvas work and continuous streaming remain parked. Full SM-17 node/model expansion waits until the first local Bundle works. @@ -22,8 +22,8 @@ first bounded local-engine Databricks training and scoring path; see its [live report](08-sm24a-live-validation-report.md). The first scenario is pandas/Polars FE and Python-model training, followed by -local Python batch prediction in a Databricks job and monthly publication to a -UC Delta table. Existing Spark support is limited: +local Python batch prediction in a Databricks job and automatic incremental +publication to a UC Delta table. Existing Spark support is limited: native portable FE covers mean/constant SimpleImputer, StandardScaler and an empty chain; model bundles support the documented sklearn regression/classification contract. The worker Python-pipeline mode is also capability-gated, not a generic @@ -43,16 +43,16 @@ UC publication and Bundle claims need their own cloud evidence. ## Boundaries and reuse - Reuse existing `predict_local` and MLflow tracking/model/registry adapters for - the first Bundle. Evaluate a bounded local-result -> Spark DataFrame bridge - to reuse guarded Delta publication, with a distinct local batch contract. + the first Bundle. SM-15L and SM-15I provide bounded local-result -> Spark + DataFrame bridges with separate period-replacement and append contracts. Later Spark inference variants reuse `predict_spark` and `run_batch`. - Keep platform, FE engine, model execution, sink and optional tracking/registry independent. Local execution can run inside a Databricks job. - No implicit Spark-to-pandas collection, node substitution, refitting or alias promotion. Known artifact schema/order/digests should be derived once. -- Keep `as_of`, period, source snapshot, target version and logical retry identity - explicit. The local publication path needs its own verified retry/transaction - guard before the template advertises monthly UC output. +- Keep explicit period and `as_of` pins for backfills. Scheduled SM-15I jobs + derive source versions and retry identity from committed Delta receipts; + both writers use the verified shared admission. - Config parsing and validation have no remote mutation. Resource provisioning, submission, endpoint updates, promotions and cleanup are explicit operations. - Databricks optional dependencies belong in integration modules, not core nodes. @@ -70,15 +70,16 @@ UC publication and Bundle claims need their own cloud evidence. | 2 | SM-25: local-first SDK configuration and preflight | SM-26 | DONE | | 3 | SM-24a: local training and bounded batch prediction | SM-25 | DONE | | 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | DONE | -| 5 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; verified SM-15L | READY | +| 5 | SM-15I: automatic incremental local scoring | SM-15L | DONE | +| 6 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; SM-15I | READY | | After first Bundle | SM-27: bounded full-history rescore and selectable Bundle mode | SM-20a; SM-15L | LATER | | After first Bundle | SM-22 then SM-28: validation/promotion and optional monthly retraining | SM-20a; SM-22 for SM-28 | LATER | | Later | SM-24b, SM-19, SM-21, SM-23: optional Jobs API, serving, feature lookup and monitoring | Relevant local adapters | LATER | | After local Bundle | SM-24c and SM-17: Spark workflow then broader Spark coverage | SM-20a | LATER | | After selected Spark gates | SM-20b: add tested Spark option to the Bundle | SM-24c; relevant SM-17 slices | LATER | -The first Bundle needs a working, bounded local input and a verified monthly -UC output; it does not need model promotion, online lookup, HTTP, SQL, A/B, +The first Bundle needs a working, bounded local input and verified +automatic new-row UC output; it does not need model promotion, online lookup, HTTP, SQL, A/B, Canvas, or Spark FE/model execution. Spark may handle UC table I/O only. The local-first follow-ups add full-history rescore and optional monthly retraining before broad Spark inference expansion. @@ -212,6 +213,19 @@ This gate passed in the isolated serverless jobs documented in the [SM-15L live report](11-sm15l-live-validation-report.md). The first Bundle can now use this path, subject to its own generated-project validation. +## SM-15I - Automatic incremental local scoring + +The explicit-period SM-15L job and its live rehearsal supplied period/source +version values in code. They do not satisfy the user's no-manual-input +requirement. The separate +[SM-15I live report](13-sm15i-live-validation-report.md) validates the implementation: +first +bounded snapshot, later only newly inserted source rows, an append-safe Delta +writer, and a source watermark in the same committed output receipt. Do not +feed an insert-only change batch into `replaceWhere`, which would delete +earlier predictions in an overlapping event-time period. Reject update/delete +events until a separate policy is tested. + ## SM-24b - Optional Databricks Jobs API operations Reference: developer resource scope and cleanup patterns. The first Bundle @@ -259,14 +273,14 @@ evaluation remains parked and does not block current compatible bundles. ## SM-27 - Full-history local rescore and selectable Bundle mode -Keep `period_update` as the first Bundle's default: score only the requested -closed month and replace that period idempotently. Add an explicit +Keep `incremental_append` as the first Bundle's scheduled default. Retain +SM-15L's `period_update` for explicit backfills. Add an explicit `full_rebuild` choice after SM-20a; it reads one pinned, bounded source snapshot and scores the requested historical scope with one pinned model version. Publish to a new prediction generation or table, validate counts, keys, parity and provenance, then activate it explicitly. Preserve the previous generation for rollback and keep original decision-time forecasts auditable. An ordinary -monthly run must never trigger a full rescore because an alias moved. +scheduled run must never trigger a full rescore because an alias moved. - [ ] Define generation identity, source/model/version receipt, active-view cutover and rollback; reject unbounded reads and overlapping writes. @@ -357,7 +371,8 @@ no requirement to move existing core metrics into Databricks-specific code. ## SM-20a - First local Databricks Bundle and project template -This is the first deployable milestone after SM-26, SM-25, SM-24a and SM-15L. +This is the first deployable milestone after SM-26, SM-25, SM-24a, +SM-15L and SM-15I. Generate a project using tested local services, with a `databricks.yml` in the generated project root, job resources, thin Python entry points, pinned package dependencies, dev/prod targets and a short README. Do not add a YAML file to @@ -367,8 +382,9 @@ source/target, schedule and limits; credentials remain in Databricks authentication or secrets, never generated source. Tracking-off or registry-off Bundle variants require a separately tested durable artifact handoff. -- [ ] Generate local training and monthly local batch jobs. Pass data period, - timezone, source snapshot and model version as explicit job parameters. +- [ ] Generate local training and automatic incremental batch jobs. Pin + model selection in configuration; derive source versions from committed + receipts. Scheduled runs require no manual period or source-version input. Serverless Python script/wheel tasks declare their required environment key and installed package dependencies in the generated job resources. - [ ] Generate tests for config/imports, `databricks bundle validate`, a @@ -382,10 +398,10 @@ Bundle variants require a separately tested durable artifact handoff. Acceptance: a fresh generated project can be validated, deployed and run on the chosen Databricks environment; its pandas/Polars model produces the -expected pinned monthly table rows. Generated-file checks alone are not runtime +expected pinned incremental table rows. Generated-file checks alone are not runtime evidence. A supported no-UC-output variant may be offered separately; it does not satisfy the monthly table gate. -See [the dedicated SM-20 plan](05-sm20-bundle-plan.md) for the two-month +See [the dedicated SM-20 plan](05-sm20-bundle-plan.md) for the two-run incremental source/output-table rehearsal and the later Spark inference variant. ## SM-24c / SM-17 / SM-20b - Spark enhancement after the first Bundle diff --git a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md index 5e67d9283..ab5f6ed69 100644 --- a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md +++ b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md @@ -1,7 +1,8 @@ # SM-20: local-first Databricks Bundle, then Spark enhancement Updated: 2026-09-23. Planning only; no generated project has been created -by this plan. The SM-15L local monthly writer passed its separate live gate. +by this plan. SM-15L proved explicit-period writes and SM-15I proved +automatic new-row scoring. The generated Bundle still needs validation. The [open queue](OPEN_QUEUE.md) owns status and task order. ## Outcome and engine boundary @@ -62,12 +63,12 @@ The SQL Connector is an alternative, not a required part of the first Bundle. 2. SM-25 selects pandas or Polars, a pinned model version, bounded source, output table and publication mode before the job starts. 3. SM-24a exposes a local training and batch prediction entry point. -4. [SM-15L](11-sm15l-live-validation-report.md) proves local prediction -> UC - Delta publication, including replay, stale requests and reuse of the - previously tested shared admission. The current `run_batch` performs - Spark inference and cannot be called as if it performed local prediction. - Its `publish_replace_period` logic is reused by `run_local_batch` with a - truthful local request contract and explicit final-result conversion. +4. [SM-15L](11-sm15l-live-validation-report.md) proves explicit-period local + prediction -> UC Delta publication, replay and shared admission. +5. [SM-15I](12-sm15i-incremental-scoring-plan.md) adds automatic first-snapshot + and subsequent new-row scoring with an append-safe, committed source + watermark. The current `replaceWhere` path cannot accept only new rows + when they overlap a previously written period. The custom template should generate a project with these responsibilities: @@ -85,58 +86,57 @@ The generated Python files call Skyulf services; they do not copy FE, model, MLflow or Delta publication implementations. The first verified cross-job artifact path uses MLflow and a concrete UC model version. Tracking-off and registry-off variants need their own durable artifact-handoff test before they -are offered. Configuration includes source/target table names, row keys, -period column, business timezone, maximum local rows/bytes, model version, -compute environment and optional schedule. Credentials are resolved by the -platform, not generated into files. Serverless Python job tasks declare the +are offered. Configuration includes source/target table names, a globally +unique row key, maximum local rows/bytes, a pinned model version, compute +environment and schedule. The job derives source versions from committed +receipts; scheduled runs need no period or source-version input. Credentials +are resolved by the platform, not generated into files. Serverless Python job tasks declare the required environment and package dependencies. -## Two-month UC table rehearsal +## Two-run incremental UC table rehearsal -Use an isolated test catalog.schema. Provision the input and prediction tables -explicitly; keep training data separate from the scoring rows. Train one fixed -model and pin its UC version for both scoring runs so this test isolates -publication behavior. Let `M1` and `M2` be consecutive business months, and -`S1`/`S2` the source Delta versions after each month's data arrives. Each -scoring job runs after the corresponding month closes. +Use an isolated test catalog.schema and a source Delta table with compatible +Change Data Feed available before the test inserts. Provision an empty prediction +table and shared admission authority. Train one fixed model and pin its UC +version for both runs. The job configuration contains source/model/target and +local size limits once; it does not contain dates or changing source versions. | Step | Action | Required observation | | --- | --- | --- | -| Setup | Put two keyed `M1` rows in the source table; create an empty prediction table | Source version `S1`; output schema and initial target version recorded | -| First monthly run | After `M1` closes, filter and score only `M1` at `S1` with pinned model version and run ID `R1` | Exactly two persisted `M1` predictions; values equal direct pandas/Polars gold results; receipt names `S1`, model and target version | -| Next month's data | Append two keyed `M2` rows to the same source table | New source version `S2`; original `M1` source rows remain | -| Second monthly run | After `M2` closes, filter and score only `M2` at `S2` with run ID `R2` and expected target version from `R1` | Two new `M2` predictions; target now has four rows across two months; both `M1` prediction values and run metadata remain unchanged | -| Replay | Repeat the exact `R2` request | Return the recorded receipt without another target commit or changed rows | -| Stale conflict | Submit a new logical request with the old expected target version | Reject it without changing the prediction table | - -The output is a persisted UC Delta table, but the second job computes only -`M2`; it does not materialize or re-score both months. The period-scoped Delta -write behaves like an append for a new month and replaces only that month on -an explicit rerun. A late-arriving row in `M1` requires a separate `M1` -backfill request; it must not be picked up silently by the `M2` job. Require -unique row keys within each month, stable column order, explicit null/dtype -conversion and a bounded month-filtered local read. Capture source versions -and `as_of` after their commits rather than guessing availability. No -production table is used. +| Setup | Put two keyed rows in the source; create an empty target | Source table identity and current version visible to the job | +| First run | Start the generated scoring job with no period/version parameters | Both existing rows predicted, values equal local gold; committed receipt records source high version and target version | +| New data | Append two new keyed rows to the source | New source version; both inserted keys were absent from first run | +| Second run | Start the same job, again without period/version parameters | Only the two new rows scored; target now has four rows; both first-run predictions and metadata unchanged | +| Replay/no-op | Retry the same work or run again with no source inserts | No duplicate predictions or new target commit | +| Failure | Force an output failure before commit, then retry | Committed source watermark stays unchanged until predictions commit | + +A source with no date column must work. When an event timestamp exists, also +test a late-arriving row with an older timestamp. The source change-version +range, not the job start date or event timestamp, determines which rows are +new. The output may retain event timestamps for analysis. An +explicit `period_update` remains available for controlled backfills, but it +is not the scheduled default. Source updates/deletes are rejected until their +policy is defined and tested. ## Selectable scoring and retraining extensions -The first Bundle implements `period_update` only. SM-27 later adds an explicit -`full_rebuild` mode to the generated local-engine project. The selection is a -job parameter with preflight, not an automatic reaction to new data or a moved -model alias. +The first Bundle implements automatic `incremental_append` as its scheduled +default. SM-15L's `period_update` remains an explicit backfill operation. +SM-27 later adds an explicit `full_rebuild` mode; neither is triggered by +the schedule or a moved model alias. | Mode | Input and publication | Typical use | | --- | --- | --- | -| `period_update` (default) | Score one requested month from a pinned source version; idempotently replace that month's output; retain all other periods and their model versions | Monthly forecasts and auditable past decisions | -| `full_rebuild` (explicit) | Score a pinned, bounded historical scope with one model version; publish a new validated prediction generation and explicitly activate it | Recompute a current-state view, corrected data, or a model migration | +| `incremental_append` (scheduled default) | Initial bounded snapshot, then only new source inserts since the last committed source version; append predictions with an atomic receipt | Routine jobs when new records arrive | +| `period_update` (explicit) | Score one selected period from a pinned source version and replace exactly that period | Controlled backfill or correction | +| `full_rebuild` (later SM-27) | Recompute a pinned, bounded historical scope into a new validated generation and explicitly activate it | Model migration or revised historical view | The full rebuild must keep its source snapshot, model version, `as_of`, row scope, generation ID and activation receipt. Its failure must leave the old generation active. Historical decision-time predictions remain available; rescores using later information must be labeled as current-state results. -The rehearsal adds a third run only after SM-27: score `M1` and `M2` at `S2` -into a new generation, compare four rows, activate it, and verify rollback. +SM-27 adds a separate rehearsal: rescore all four rows into a new +generation, activate it, and verify rollback. SM-28 separately adds optional monthly retraining after labels are available. It trains a candidate, uses SM-22 to compare against a pinned champion, and @@ -148,13 +148,13 @@ months; `full_rebuild` remains a separate request. Offline checks cover template generation, imports, config preflight and `databricks bundle validate`. A separate live check deploys the generated dev -target, runs training and both monthly scoring steps, then compares rows by -key and month, model/version metadata and Delta history. The Bundle is complete only when +target, runs training and two automatic incremental scoring steps, then +compares rows by key, model/version metadata and Delta history. The Bundle is complete only when the generated project itself passes those checks; an SDK-only smoke is not sufficient. The first generated project does not need endpoints, `ai_query`, online feature lookup, monitoring or dynamic Jobs API helpers. SM-20b follows the accepted local Bundle. It adds a Spark inference choice only for artifact, FE, model and runtime combinations verified by SM-24c and -the relevant SM-17 slices. The same two-month rehearsal then runs against +the relevant SM-17 slices. The same two-run incremental rehearsal then runs against that Spark variant. The pandas/Polars choice remains available. diff --git a/initiatives/spark_and_mlflow/12-sm15i-incremental-scoring-plan.md b/initiatives/spark_and_mlflow/12-sm15i-incremental-scoring-plan.md new file mode 100644 index 000000000..370f27d74 --- /dev/null +++ b/initiatives/spark_and_mlflow/12-sm15i-incremental-scoring-plan.md @@ -0,0 +1,82 @@ +# SM-15I: automatic incremental local scoring before the first Bundle + +Status: complete for the documented bounded insert-only scope on 2026-09-23. +See the [local and live validation report](13-sm15i-live-validation-report.md). +This task corrects the first Bundle contract: +operators cannot enter a period or source version for every scheduled run. +SM-15L remains the verified explicit-period/backfill writer; its two live jobs +used scripted January/February boundaries and source versions. It did not +automatically discover newly appended source rows. + +## Required behavior + +A scheduled job receives stable configuration (UC source/target, globally +unique row key, pinned model selection, local engine and row/byte budgets), not +a manually selected date interval. The target must start empty. A timestamp +column is optional and is never used to select which rows to score. + +1. On first run, capture the current source Delta table ID and version. Score + the existing bounded snapshot pinned to that version and publish its + predictions. If no rows exist, + leave the target unchanged and retry the bootstrap on the next run. +2. On later runs, derive the last *committed* source version from the target's + durable publication receipt. Capture the current source version as the upper + bound. Read only source inserts in the inclusive change-version range + `last_committed + 1 .. current`; do not rescore earlier rows. +3. Apply the saved pandas or Polars pipeline to only those bounded new rows. + If an event timestamp exists, retain it; neither it nor the schedule time + determines row membership. Late arrivals and undated rows are source inserts + and must be scored. +4. Publish only those final keyed predictions using an append-safe Delta path + under the existing shared admission. The current `replaceWhere` period + writer cannot receive only new rows in an overlapping period: it would + remove earlier predictions in that period. +5. Record source table ID, committed source-version range, pinned model + name/version/digest, code version, run ID and counts in the *same target + Delta commit* as the predictions. Read the resulting target version from + Delta history after commit. Derive the next watermark from the committed + receipt, avoiding a separate non-atomic checkpoint. +6. If no new inserts exist, return a no-op without a target write. If a job + fails before commit, the watermark stays put. If the commit succeeds but + the caller loses its acknowledgement, the next run recognizes the receipt + and does not duplicate predictions. + +The first increment is append-only. Reject source updates and deletes +explicitly; their desired prediction policy is a separate decision. Reject +duplicate source keys within an increment and keys already present in the +target. Require an explicit globally unique prediction key (for example an +`event_id`, or a verified composite key), since an entity can appear in +multiple periods. Never silently skip a duplicate or reinterpret an update as +an insert. The initial snapshot and each change range obey the same local +row/byte ceilings; oversized ranges fail without advancing the watermark. + +## Source-change requirement + +Use Delta Change Data Feed (CDF) for bounded batch reads between source +versions. Provisioning must enable a compatible feed before the changes to be +consumed, or prove that the source already supports it. Do not assume future +automatic CDF rollout is available in the selected workspace/runtime. +Fail if the required change version has expired from retention; do not silently +fall back to a full scan or a date filter. A repair/bootstrap workflow must be +explicit and independently verified. + +Databricks reference: +[Change Data Feed](https://docs.databricks.com/aws/en/tables/features/change-data-feed) +and [`table_changes`](https://docs.databricks.com/aws/en/sql/language-manual/functions/table_changes). +CDF change ranges are inclusive, so the next read begins at +`last_committed + 1`. + +## Acceptance + +- Local real-Delta tests: initial existing rows; a second source append whose + `event_time` overlaps the first run; only new keys scored/published; old + predictions unchanged; no-op; exact retry; lost acknowledgement; competing + writers; duplicate key; update/delete; expired feed; and a failed write + leaving the source watermark unchanged. +- Isolated Databricks two-job proof: configure source/model/target once, run + without manual period/version parameters, append new source rows, run again, + and compare exact predictions, target rows and committed version receipts. + Include at least one late-arriving row in an earlier calendar month. +- The generated SM-20a Bundle calls this tested service on a schedule. An + explicit period replacement remains available for controlled backfills; + SM-27's `full_rebuild` remains a later, separate operation. diff --git a/initiatives/spark_and_mlflow/13-sm15i-live-validation-report.md b/initiatives/spark_and_mlflow/13-sm15i-live-validation-report.md new file mode 100644 index 000000000..0784a21c7 --- /dev/null +++ b/initiatives/spark_and_mlflow/13-sm15i-live-validation-report.md @@ -0,0 +1,62 @@ +# SM-15I automatic incremental local scoring: validation record + +Status: the two-stage Databricks rehearsal passed on 2026-09-23 for the +documented small-data, insert-only pandas model path. The first generated +Bundle remains SM-20a. + +## Contract demonstrated + +A scheduled scorer receives stable source, target, model, row-key and budget +configuration. It takes no period or source-version parameter. The first job +scores the bounded source snapshot. The next job reads Delta Change Data Feed +inserts after the source version recorded with the previous target append. +The source and target in this proof have **no date column**. Spark performs +Delta I/O, pandas runs the fitted FE and model, and a shared admission protects +the target. Predictions and the source watermark share one Delta commit. + +## Local evidence + +- The real-Delta local publication suite passed 17 tests. It covers pandas, + Polars, a source with no date column, an older event timestamp on a new row, + update rejection, duplicate-key rejection, missing CDF, target-reset + rejection, failed-write retry, lost-ack replay, shared admission, and an + injected expired-CDF read failure. +- The SDK/reader suites passed 33 tests with one optional skip. +- Ruff, ty, `git diff --check` and `mkdocs build --strict` passed. +- A fresh wheel was built from the modified source. SHA-256: + `97918179a0708dde3ce710083829f75a4e83a910df117a0068b20fa52e3265d6`. + Its packaged `local_incremental.py` bytes matched the workspace source. + +## Isolated Databricks resources + +- Authenticated CLI profile: `skyulf`. +- Existing test schema: `workspace.skyulf_sm24a_20260923`. +- New test-owned tables: `skyulf_sm15i_source_r1`, + `skyulf_sm15i_predictions_r1`, `skyulf_sm15i_admission_r1`. +- Uploaded notebook and wheel folder: + `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm15i_r1`. +- Existing pinned UC model: + `workspace.skyulf_sm24a_20260923.skyulf_sm24a_metrics_r1` version 1, + digest `e4281f2feb9349b2dd745bcdd894128c47d434f0bd8779eb42d474adb8aed662`. +- Both one-time serverless jobs used the `STANDARD` performance target, + a 900-second timeout and zero retries. Their environment installed the + uploaded 0.9.0 wheel and `mlflow==3.16.1`. + +| Stage | Parent/task run | Source high version | Target commit | Observation | +| --- | --- | ---: | ---: | --- | +| Initial snapshot | [483287295672086](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/778480091488220/run/483287295672086) / `709869826305307` | 1 | 1 | SUCCESS: 80 existing rows predicted; exact direct-local values | +| Source append | [742044640919376](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/900021231417258/run/742044640919376) / `16280116334355` | 2 | 2 | SUCCESS: 80 new rows predicted; 160 total; first 80 unchanged; no-op retry kept version 2 | + +The source fixture came from the earlier 160-row SM-24a test table by stable +key order, with only `entity_id`, `x` and `z` carried into the new source. +Its two halves were staged solely to test arrival between jobs; neither +scoring invocation used a date or source-version argument. Both jobs compared +every persisted prediction with the pinned local model's direct output by key. +The second job also compared the first 80 complete target rows before and +after append, then called the scorer again and observed zero new rows with no +new target commit. + +This evidence covers one pinned pandas model on serverless compute and +small bounded insert-only batches. It does not claim support for source +updates/deletes, expired CDF ranges, large driver-side data or a generated +Bundle. Those boundaries remain explicit in the code and queue. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index f06a24f4b..f5dcf67f6 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,20 +1,23 @@ # Session handoff - 2026-09-23 -SM-00 through SM-16, SM-15L and SM-24a/25/26 are complete for their +SM-00 through SM-16, SM-15L/15I and SM-24a/25/26 are complete for their documented scopes. The selected Databricks serverless local monthly UC publication passed with 80 pandas January and 80 Polars February predictions. -Latest user direction: **Build the first small-data pandas/Polars Databricks -Bundle next (SM-20a). Spark handles table I/O; Spark FE/model execution follows -the first working local Bundle. SM-18 and streaming remain parked.** +Latest user direction: **Do not require manual period/source-version +values for recurring jobs. SM-15I now provides automatic new-row scoring +for the first small-data pandas/Polars Databricks Bundle (SM-20a). Spark handles table +I/O; Spark FE/model execution follows the Bundle. SM-18 and streaming remain +parked.** After the first Bundle, SM-27 adds explicit full-history rescore and SM-22/SM-28 add optional monthly retraining with controlled candidate/champion promotion. Target release: 0.9.0. Branch: `090`. ## Starting point -- SM-00 through SM-16, SM-15L, SM-24a, SM-25 and SM-26 are complete. Start - SM-20a from [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md), including - its two-month table rehearsal. +- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25 and SM-26 are complete. + Start SM-20a from [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). + SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic + 80+80 insert-only scoring with no date column or per-run version input. SM-26 added local artifact and MLflow packaging without cloud execution. The SM-25 SDK adds immutable local workflow configuration, local/remote preflight, explicit path or pinned registry artifact selection and caller-frame limits. @@ -102,7 +105,8 @@ The first deliverable is: Databricks training job: pandas/Polars FE + sklearn model -> Save fitted FE, model and input contract through MLflow -> Databricks scoring job: pandas/Polars local batch on bounded data - -> Spark handles final UC Delta table publication only (SM-15L) + -> Spark reads bounded UC source changes and publishes UC Delta predictions + (SM-15I automatic incremental path) -> Generate and run the first local-engine Bundle (SM-20a) ``` diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index d6fd49658..537711a93 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,15 +1,16 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00–SM-16 and SM-15L/24a/25/26 complete; SM-20a next. Target: 0.9.0.** +Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-20a next. Target: 0.9.0.** First deliverable: pandas/Polars training and local batch on Databricks, then a -working local-engine Bundle. Spark expansion follows that Bundle. SM-15L now -provides monthly UC output; SM-18 and continuous streaming remain parked. +working local-engine Bundle. Spark expansion follows that Bundle. SM-15L +provides explicit-period UC output. SM-15I adds automatic new-row scoring +for the first Bundle; SM-18 and streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-20a. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). -SM-26 added a local MLflow package; SM-15L validated a UC writer. +SM-26 added a local MLflow package; SM-15L and SM-15I validated UC writers. No Bundle has been generated. Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; @@ -36,13 +37,14 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-14 | Registry/Unity Catalog adapter | SM-13 | DONE | Explicit publish; alias/version pinning; local evidence | | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | | SM-16 | Gerçek Databricks kapısı | SM-15 | DONE | Selected serverless workflow passed; live evidence below | -| SM-15L | Local predictions -> UC Delta monthly sink | SM-24a | DONE | Score only requested month; keep prior months; Spark only for bounded I/O; real UC replay/concurrency proof | +| SM-15L | Explicit-period local predictions -> UC Delta | SM-24a | DONE | Score requested period; preserve rows outside it; Spark only for bounded I/O | +| SM-15I | Automatic incremental local scoring | SM-15L | DONE | No date/source-version input; 80+80 live Delta rows, no-op replay; [evidence](13-sm15i-live-validation-report.md) | | SM-17 | Complete existing Spark node/model coverage | SM-20a | LATER | Resume only after the first local Bundle; preserve all inventoried gaps | | SM-18 | Backend/Canvas and legacy artifact bridge | SM-17 | PARKED | Capability UI/API, DAG contracts and existing deployment compatibility | | SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | | SM-25 | Local-first config / SDK preflight | SM-26 | DONE | Immutable local config; pinned artifact load, bounded frame and actionable preflight; no node/model allowlist | | SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | -| SM-20a | First local-engine Bundle/template | SM-24a, verified SM-15L | READY | Generate, validate, deploy and run pandas/Polars train/monthly batch with pinned MLflow/UC model | +| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I | READY | Generate, validate, deploy and run pandas/Polars train/automatic incremental batch with pinned MLflow/UC model | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | | SM-22 | Optional model validation and controlled promotion | SM-20a, current evaluation/registry | LATER | Pinned candidate/champion comparison, explicit version promotion and rollback | @@ -72,19 +74,26 @@ in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). 3. **SM-24a:** local training and bounded local batch prediction in Databricks. Its [live validation report](08-sm24a-live-validation-report.md) records two source tables, five cross-job models and every preprocessing registration ID. -4. **SM-15L:** convert only final local predictions for guarded Spark Delta publication; each new month adds results while earlier months remain unchanged. -5. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle using the [two-month rehearsal](05-sm20-bundle-plan.md). -6. **After SM-20a:** SM-27 adds explicit `full_rebuild` alongside the default - `period_update`; SM-22 then SM-28 add candidate/champion validation and +4. **SM-15L:** explicit-period local predictions reach guarded Delta. The live + test used scripted period and source-version values; it is not automatic. +5. **SM-15I:** add automatic first-snapshot and later new-row scoring with a + committed source-version receipt and append-safe output. See the + [incremental plan](12-sm15i-incremental-scoring-plan.md). +6. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle + using the [two-run rehearsal](05-sm20-bundle-plan.md) without manual dates + or source versions. +7. **After SM-20a:** SM-27 adds explicit `full_rebuild` alongside the default + `incremental_append`; SM-15L's `period_update` remains an explicit backfill. + SM-22 then SM-28 add candidate/champion validation and optional monthly retraining. These are separate from monthly scoring. -7. **Later:** optional SM-24b/24d/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. +8. **Later:** optional SM-24b/24d/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. SM-26 is the explicit packaging task added after the local-first MLflow discussion. It reuses the fitted local pipeline rather than requiring every FE node to gain a portable Spark codec first. Each advertised local pipeline/model variant needs save/load/prediction evidence. This does not make its artifact Spark-compatible. Backend joblib dictionary bridging stays in parked SM-18. Local prediction -and UC Delta publication remain separate tasks; SM-15L is now on the first +and UC Delta publication remain separate tasks; SM-15I is now on the first Bundle's critical path, with an explicit small-data memory limit. Spark can perform UC table I/O here without becoming the FE or model execution engine. @@ -126,9 +135,9 @@ Details, reference-repo comparison and parked endpoint tasks: ## Detay planlar - Completed SM-16 evidence and scope: [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). -- SM-15 currently provides the Spark writer only. SM-15L is now required for - SM-20a's local monthly UC output and must establish its own transaction and - runtime evidence. The first template precedes Spark expansion. +- SM-15 and SM-15L provide Spark and explicit-period local UC writers. + SM-15I is required for automatic new-row output in SM-20a. The first + template precedes Spark expansion. - Latest user direction supersedes the prior Spark-first and template-last order: deliver a local pandas/Polars Bundle, then expand Spark and add a tested Spark option. SM-18 and continuous streaming remain parked. @@ -144,6 +153,20 @@ SM-17 requires the full tracked scope above. Some algorithms may need an explici alternative backend rather than an equivalent native Spark implementation; that decision must not hide missing support. SM-19 streaming remains optional and parked. +## SM-15I - automatic new-row scoring, DONE + +The user requires scheduled jobs to discover new source rows automatically. +The first run must score the existing bounded snapshot; later runs must score +only inserts since the last successful target commit, including late-arriving +rows in an earlier calendar period. The current `replaceWhere` writer cannot +publish only new rows in an overlapping period without deleting older +predictions. Implement a separate append-safe publisher and derive the source +watermark from the committed output receipt. See the +[SM-15I plan](12-sm15i-incremental-scoring-plan.md). This is a prerequisite +for SM-20a. The runner passed local real-Delta gates and the isolated two-job Databricks +rehearsal, including a source with no date column; see the +[SM-15I validation report](13-sm15i-live-validation-report.md). + ## SM-15L - 2026-09-23 monthly local UC Delta publication, DONE - Added `run_local_batch` with truthful `local_pipeline` publication mode. @@ -162,7 +185,8 @@ decision must not hide missing support. SM-19 streaming remains optional and par all January rows/metadata, replayed without a new commit, and rejected a stale logical request. Both periods matched direct local gold by key. See the [SM-15L live report](11-sm15l-live-validation-report.md) for run IDs, - model digests, test resources and scope limits. Next: SM-20a Bundle. + model digests, test resources and scope limits. The date/version choices + were scripted for this proof; automatic new-row scoring is SM-15I. ## SM-24a — 2026-09-23 local and Databricks validation, DONE @@ -195,7 +219,8 @@ decision must not hide missing support. SM-19 streaming remains optional and par - The Spark iterator does not expose actual wire-byte counts. `max_bytes` bounds accepted decoded rows and local-frame memory; a very wide row can arrive before rejection. [SM-24d](OPEN_QUEUE.md) retains the stronger - transport-budget option for wider or larger workloads. Next: SM-20a. + transport-budget option for wider or larger workloads. SM-15I then added + automatic new-row scoring; next is SM-20a. ## SM-25 — 2026-09-23 local SDK validation, DONE diff --git a/skyulf-core/examples/databricks_local_sm15i_job.py b/skyulf-core/examples/databricks_local_sm15i_job.py new file mode 100644 index 000000000..47facbc50 --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm15i_job.py @@ -0,0 +1,161 @@ +# Databricks notebook source +"""Isolated two-run, date-independent local incremental Delta validation.""" + +from __future__ import annotations + +import json +from typing import Any + +import numpy as np + +from skyulf.integrations.databricks import ( + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + prepare_local_workflow, + run_incremental_local_batch, +) +from skyulf.integrations.databricks.delta import table_identity +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission + +SCHEMA = "workspace.skyulf_sm24a_20260923" +BASE_SOURCE = f"{SCHEMA}.skyulf_sm24a_score_source" +SOURCE = f"{SCHEMA}.skyulf_sm15i_source_r1" +TARGET = f"{SCHEMA}.skyulf_sm15i_predictions_r1" +CONTROL = f"{SCHEMA}.skyulf_sm15i_admission_r1" +MODEL = f"{SCHEMA}.skyulf_sm24a_metrics_r1" + + +def _prepare() -> Any: + """Load the same pinned fitted pandas model for both scheduled score runs.""" + return prepare_local_workflow( + LocalWorkflowConfig( + runtime="databricks", + engine="pandas", + source=InputSource( + kind="uc_table", + table=SOURCE, + read_mode="incremental", + max_rows=200, + max_bytes=4_000_000, + ), + model=ModelSelection( + kind="local_pipeline", + name=MODEL, + version="1", + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + sink=OutputSink(kind="uc_delta", table=TARGET), + ) + ) + + +def _verify(spark: Any, prepared: Any, expected_count: int) -> None: + """Check every persisted value against direct local prediction by stable key.""" + source = spark.table(SOURCE).select("entity_id", "x", "z").orderBy("entity_id").toPandas() + expected = prepared.predict(source.loc[:, ["x", "z"]]) + actual = spark.table(TARGET).select("entity_id", "prediction").orderBy("entity_id").toPandas() + if len(source) != expected_count or len(actual) != expected_count: + raise AssertionError("Source and target counts differ from the expected stage.") + if actual["entity_id"].tolist() != source["entity_id"].tolist(): + raise AssertionError("Prediction keys differ from source keys.") + np.testing.assert_allclose( + actual["prediction"].to_numpy(), + expected["prediction"].to_numpy(), + rtol=0, + atol=1e-9, + ) + + +def bootstrap(spark: Any) -> dict[str, Any]: + """Create isolated tables and score the initial snapshot without a date filter.""" + for table in (SOURCE, TARGET, CONTROL): + if spark.catalog.tableExists(table): + raise ValueError(f"Test table already exists: {table}") + base = spark.table(BASE_SOURCE).select("entity_id", "x", "z") + base.orderBy("entity_id").limit(80).write.format("delta").saveAsTable(SOURCE) + spark.sql(f"ALTER TABLE {SOURCE} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") + spark.sql( + f"CREATE TABLE {TARGET} (entity_id STRING, prediction DOUBLE, " + "__skyulf_run_id STRING, __skyulf_model_name STRING, " + "__skyulf_model_version STRING) USING DELTA" + ) + spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") + spark.sql( + f"INSERT INTO {CONTROL} SELECT :target_id, CAST(NULL AS STRING)", + args={"target_id": table_identity(spark, TARGET)}, + ).collect() + prepared = _prepare() + result = run_incremental_local_batch( + spark, + prepared, + row_keys=("entity_id",), + admission=DeltaTableAdmission(spark, CONTROL), + ) + _verify(spark, prepared, 80) + if result.input_count != 80 or result.noop: + raise AssertionError("Initial snapshot was not scored once.") + return { + "stage": "bootstrap", + "rows": result.input_count, + "source_end_version": result.source_end_version, + "target_version": result.commit_version, + "model_digest": result.manifest["model_digest"] if result.manifest else None, + } + + +def append(spark: Any) -> dict[str, Any]: + """Append source rows, score only those inserts, then prove a no-op retry.""" + if not all(spark.catalog.tableExists(table) for table in (SOURCE, TARGET, CONTROL)): + raise ValueError("Bootstrap tables are missing.") + before = spark.table(TARGET).orderBy("entity_id").collect() + if len(before) != 80: + raise ValueError("Bootstrap must publish exactly 80 predictions.") + remaining = ( + spark.table(BASE_SOURCE) + .select("entity_id", "x", "z") + .join(spark.table(SOURCE).select("entity_id"), on="entity_id", how="left_anti") + ) + if remaining.count() != 80: + raise ValueError("Expected exactly 80 new fixture records.") + remaining.write.format("delta").mode("append").saveAsTable(SOURCE) + prepared = _prepare() + admission = DeltaTableAdmission(spark, CONTROL) + result = run_incremental_local_batch( + spark, prepared, row_keys=("entity_id",), admission=admission + ) + replay = run_incremental_local_batch( + spark, prepared, row_keys=("entity_id",), admission=admission + ) + _verify(spark, prepared, 160) + after = spark.table(TARGET).orderBy("entity_id").collect() + if [row for row in after if row.entity_id in {old.entity_id for old in before}] != before: + raise AssertionError("The first run's predictions changed.") + if result.input_count != 80 or replay.input_count != 0 or not replay.noop: + raise AssertionError("Incremental append or no-op retry changed membership.") + if result.commit_version != replay.commit_version: + raise AssertionError("No-op retry wrote another target version.") + return { + "stage": "append", + "new_rows": result.input_count, + "total_rows": len(after), + "source_end_version": result.source_end_version, + "target_version": result.commit_version, + "noop_version": replay.commit_version, + } + + +runtime_dbutils: Any = globals().get("dbutils") +runtime_spark: Any = globals().get("spark") +if runtime_dbutils is not None and runtime_spark is not None: + runtime_dbutils.widgets.text("stage", "bootstrap") + stage = runtime_dbutils.widgets.get("stage") + if stage == "bootstrap": + result = bootstrap(runtime_spark) + elif stage == "append": + result = append(runtime_spark) + else: + raise ValueError(f"Unknown SM-15I stage: {stage}") + runtime_dbutils.notebook.exit(json.dumps(result)) diff --git a/skyulf-core/skyulf/integrations/databricks/__init__.py b/skyulf-core/skyulf/integrations/databricks/__init__.py index 5ba096b60..e7ac5a6ff 100644 --- a/skyulf-core/skyulf/integrations/databricks/__init__.py +++ b/skyulf-core/skyulf/integrations/databricks/__init__.py @@ -9,6 +9,7 @@ read_local_source, score_local_source, ) +from .local_incremental import IncrementalBatchResult, run_incremental_local_batch from .local_publish import run_local_batch from .local_sdk import ( InputSource, @@ -26,6 +27,7 @@ __all__ = [ "BatchResult", "BatchSpec", + "IncrementalBatchResult", "InputSource", "LocalWorkflowConfig", "LocalScoreResult", @@ -42,6 +44,7 @@ "prepare_local_workflow", "read_local_source", "run_batch", + "run_incremental_local_batch", "run_local_batch", "score_local_source", ] diff --git a/skyulf-core/skyulf/integrations/databricks/local_incremental.py b/skyulf-core/skyulf/integrations/databricks/local_incremental.py new file mode 100644 index 000000000..99bcb5211 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_incremental.py @@ -0,0 +1,333 @@ +"""Score only new Delta inserts with a bounded local model and atomic receipt.""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import pickle +from dataclasses import dataclass +from importlib.metadata import version +from typing import Any + +import pandas as pd + +from ...inference.local_pipeline import LocalPipelineArtifact +from ._contracts import column_name, table_name +from .admission import BatchConflictError, PublishAdmission, validate_admission +from .delta import DeltaPublishError, history, table_identity +from .local_batch import _frame_bytes +from .local_publish import _check_target, _scalar +from .local_sdk import PreparedLocalWorkflow + + +@dataclass(frozen=True, slots=True) +class IncrementalBatchResult: + """Describe one committed increment or a run with no new source inserts.""" + + source_start_version: int | None + source_end_version: int + input_count: int + output_count: int + commit_version: int | None + manifest: dict[str, Any] | None + noop: bool + + +def _latest(spark: Any, table: str) -> Any: + """Read the most recent Delta commit deterministically.""" + functions = importlib.import_module("pyspark.sql.functions") + row = ( + history(spark, table) + .orderBy(functions.desc("version")) + .select("version", "userMetadata") + .first() + ) + if row is None: + raise ValueError("Delta table has no readable history.") + return row + + +def _last_receipt(latest: Any, source_id: str, target_id: str) -> dict[str, Any] | None: + """Trust a watermark only when the latest target commit contains it.""" + raw = latest["userMetadata"] + if not raw: + return None + try: + receipt = json.loads(raw) + except (TypeError, ValueError): + return None + if receipt.get("skyulf_mode") != "incremental_append": + return None + if receipt.get("source_table_id") != source_id or receipt.get("target_table_id") != target_id: + raise BatchConflictError("Incremental target is bound to another source or target ID.") + if receipt.get("source_end_version") is None: + raise BatchConflictError("Incremental target receipt has no source watermark.") + return receipt + + +def _validate_prepared( + prepared: PreparedLocalWorkflow, row_keys: tuple[str, ...], period_column: str | None +) -> tuple[str, ...]: + """Require a ready UC model and an automatic source-selection contract.""" + if not isinstance(prepared, PreparedLocalWorkflow): + raise TypeError("prepared must be a PreparedLocalWorkflow.") + config = prepared.config + if ( + config.runtime != "databricks" + or config.source.kind != "uc_table" + or config.source.read_mode != "incremental" + or config.source.version is not None + or config.sink.kind != "uc_delta" + or not config.source.table + or not config.sink.table + or config.source.table == config.sink.table + ): + raise ValueError("Incremental scoring requires unpinned UC source and UC Delta sink.") + if ( + config.model.kind != "local_pipeline" + or not config.model.name + or not config.model.version + or not prepared.preflight.ready + or not isinstance(prepared.artifact, LocalPipelineArtifact) + or prepared.preflight.model_version != config.model.version + or prepared.preflight.model_digest != prepared.artifact.manifest.pipeline_sha256 + ): + raise ValueError("Incremental scoring requires a pinned, ready local pipeline model.") + if type(row_keys) is not tuple or not row_keys: + raise ValueError("row_keys must be a nonempty tuple.") + for name in row_keys: + column_name(name) + if period_column is not None: + column_name(period_column) + names = (*row_keys, *((period_column,) if period_column is not None else ())) + if len({name.lower() for name in names}) != len(names): + raise ValueError("row_keys and period_column must be distinct.") + inputs = prepared.artifact.manifest.input_columns + if any(key in inputs for key in row_keys) or ( + period_column is not None and period_column in inputs + ): + raise ValueError("Model inputs must be distinct from keys and event time.") + if any(name in {"_change_type", "_commit_version", "_commit_timestamp"} for name in inputs): + raise ValueError("Model inputs collide with Delta change metadata.") + return inputs + + +def _bounded_frame( + selected: Any, + columns: tuple[str, ...], + row_keys: tuple[str, ...], + max_rows: int, + max_bytes: int, +) -> pd.DataFrame: + """Move only a bounded, projected set of source rows to the local model.""" + records: list[dict[str, Any]] = [] + decoded_bytes = 0 + for row in selected.select(*columns).orderBy(*row_keys).limit(max_rows + 1).toLocalIterator(): + if len(records) == max_rows: + raise ValueError("Source increment exceeds max_rows.") + record = row.asDict(recursive=True) + decoded_bytes += len(pickle.dumps(record, protocol=pickle.HIGHEST_PROTOCOL)) + if decoded_bytes > max_bytes: + raise ValueError("Source increment exceeds max_bytes.") + records.append(record) + frame = pd.DataFrame.from_records(records, columns=columns) + if _frame_bytes(frame) > max_bytes: + raise ValueError("Source local frame exceeds max_bytes.") + if frame.loc[:, list(row_keys)].isna().any().any(): + raise ValueError("Source row keys must not be null.") + if frame.duplicated(subset=list(row_keys)).any(): + raise ValueError("Source row keys must be globally unique within this increment.") + return frame + + +def run_incremental_local_batch( + spark: Any, + prepared: PreparedLocalWorkflow, + *, + row_keys: tuple[str, ...], + admission: PublishAdmission | None, + period_column: str | None = None, +) -> IncrementalBatchResult: + """Score the initial snapshot, then only inserts since the last target receipt. + + Source and target tables already exist. The source must have Delta CDF + enabled before subsequent changes. All target writers must share admission; + a target commit outside this protocol halts automatic scoring. + """ + inputs = _validate_prepared(prepared, row_keys, period_column) + admission = validate_admission(spark, admission) + config = prepared.config + source_table = config.source.table + target_table = config.sink.table + assert source_table is not None and target_table is not None + source_id = table_identity(spark, source_table) + target_id = table_identity(spark, target_table) + if source_id == target_id: + raise ValueError("Source and prediction target must be different Delta tables.") + detail = spark.sql(f"DESCRIBE DETAIL {table_name(source_table)}").first() + properties = detail["properties"] or {} + if not any( + key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" + for key, value in properties.items() + ): + raise ValueError("Source Delta Change Data Feed must be enabled before scoring.") + functions = importlib.import_module("pyspark.sql.functions") + + with admission.hold(target_id): + if ( + table_identity(spark, source_table) != source_id + or table_identity(spark, target_table) != target_id + ): + raise BatchConflictError("Source or target table identity changed during admission.") + target_latest = _latest(spark, target_table) + previous = _last_receipt(target_latest, source_id, target_id) + if previous is None: + older_receipt = ( + history(spark, target_table) + .where( + functions.get_json_object("userMetadata", "$.skyulf_mode") + == "incremental_append" + ) + .limit(1) + .count() + ) + if older_receipt: + raise BatchConflictError("Target changed outside the incremental receipt protocol.") + if spark.table(target_table).limit(1).count(): + raise BatchConflictError( + "Incremental bootstrap requires an empty target with no prior predictions." + ) + prior_version = int(previous["source_end_version"]) if previous else None + upper_version = int(_latest(spark, source_table)["version"]) + if prior_version is not None and upper_version < prior_version: + raise BatchConflictError("Source version moved behind the committed watermark.") + if prior_version == upper_version: + return IncrementalBatchResult( + prior_version, upper_version, 0, 0, int(target_latest["version"]), previous, True + ) + if prior_version is None: + selected = ( + spark.read.format("delta").option("versionAsOf", upper_version).table(source_table) + ) + else: + selected = ( + spark.read.format("delta") + .option("readChangeFeed", "true") + .option("startingVersion", prior_version + 1) + .option("endingVersion", upper_version) + .table(source_table) + ) + if selected.where(functions.col("_change_type") != "insert").limit(1).count(): + raise ValueError("Source updates and deletes require an explicit rescore policy.") + selected = selected.where(functions.col("_change_type") == "insert") + if period_column is not None: + if selected.schema[period_column].dataType.typeName() != "timestamp": + raise ValueError("Source event time must be a Spark timestamp.") + if selected.where(functions.col(period_column).isNull()).limit(1).count(): + raise ValueError("Source event time must not be null.") + frame = _bounded_frame( + selected, + (*row_keys, *inputs), + row_keys, + config.source.max_rows, + config.source.max_bytes, + ) + if frame.empty: + return IncrementalBatchResult( + prior_version, upper_version, 0, 0, int(target_latest["version"]), previous, True + ) + target = spark.table(target_table) + output_names = _check_target(spark, selected, target, row_keys, period_column, prepared) + predicted = prepared.predict(frame.loc[:, list(inputs)]) + if list(predicted.columns) != list(output_names) or len(predicted) != len(frame): + raise ValueError( + "Local prediction schema or row count differs from the model contract." + ) + bridge_frame = pd.concat( + [frame.loc[:, list(row_keys)].reset_index(drop=True), predicted.reset_index(drop=True)], + axis=1, + ) + if _frame_bytes(bridge_frame) > config.source.max_bytes: + raise ValueError("Prediction result exceeds max_bytes.") + bridge_columns = (*row_keys, *output_names) + bridge = spark.createDataFrame( + [ + tuple(_scalar(value) for value in row) + for row in bridge_frame.itertuples(index=False, name=None) + ], + schema=target.select(*bridge_columns).schema, + ) + if ( + bridge.select(*row_keys) + .join(target.select(*row_keys), on=list(row_keys), how="left_semi") + .limit(1) + .count() + ): + raise BatchConflictError("Source key already has a published prediction.") + output = ( + bridge.join(selected.select(*row_keys, period_column), on=list(row_keys), how="inner") + if period_column is not None + else bridge + ) + run_input = { + "skyulf_mode": "incremental_append", + "source_table_id": source_id, + "target_table_id": target_id, + "source_start_version": prior_version + 1 if prior_version is not None else None, + "source_end_version": upper_version, + "model_name": config.model.name, + "model_version": config.model.version, + "model_digest": prepared.preflight.model_digest, + "code_version": version("skyulf-core"), + "input_count": len(frame), + "output_count": len(frame), + } + digest = hashlib.sha256( + json.dumps(run_input, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + manifest = {**run_input, "run_id": digest, "request_digest": digest} + for name, value in ( + ("__skyulf_run_id", digest), + ("__skyulf_model_name", config.model.name), + ("__skyulf_model_version", config.model.version), + ): + output = output.withColumn(name, functions.lit(value)) + if {field.name: field.dataType for field in output.schema} != { + field.name: field.dataType for field in target.schema + }: + raise ValueError("Prediction output schema must match the Delta target exactly.") + output = output.select(*target.columns) + if output.count() != len(frame): + raise ValueError("Prediction keys do not match source rows.") + if table_identity(spark, source_table) != source_id: + raise BatchConflictError("Source table identity changed while scoring.") + if int(_latest(spark, target_table)["version"]) != int(target_latest["version"]): + raise BatchConflictError("Target changed while scoring; retry from the latest receipt.") + try: + ( + output.write.format("delta") + .mode("append") + .option("mergeSchema", "false") + .option("txnAppId", f"skyulf-incremental:{source_id}:{target_id}") + .option("txnVersion", upper_version) + .option("userMetadata", json.dumps(manifest, sort_keys=True)) + .saveAsTable(target_table) + ) + except Exception as exc: # noqa: BLE001 - preserve Delta's structured cause + if "Concurrent" in type(exc).__name__ or "DELTA_CONCURRENT" in str(exc): + raise BatchConflictError("Delta rejected a concurrent incremental write.") from exc + raise DeltaPublishError("Incremental Delta write failed.") from exc + committed = _latest(spark, target_table) + recorded = _last_receipt(committed, source_id, target_id) + if recorded is None or recorded.get("request_digest") != digest: + raise DeltaPublishError("Delta returned without a verifiable incremental receipt.") + return IncrementalBatchResult( + run_input["source_start_version"], + upper_version, + len(frame), + len(frame), + int(committed["version"]), + recorded, + False, + ) diff --git a/skyulf-core/skyulf/integrations/databricks/local_publish.py b/skyulf-core/skyulf/integrations/databricks/local_publish.py index 11a638fb0..80c8381a9 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_publish.py +++ b/skyulf-core/skyulf/integrations/databricks/local_publish.py @@ -72,20 +72,28 @@ def _check_target( spark: Any, source_frame: Any, target: Any, - source: LocalSourceSpec, + row_keys: tuple[str, ...], + period_column: str | None, prepared: PreparedLocalWorkflow, ) -> tuple[str, ...]: """Require a precreated target with exact key, output and metadata types.""" outputs = prepared.preflight.output_schema names = tuple(column.name for column in outputs) - expected = {*source.row_keys, source.period_column, *names, *_METADATA} - if len(expected) != len(source.row_keys) + len(names) + 4 or set(target.columns) != expected: + expected = {*row_keys, *names, *_METADATA} + if period_column is not None: + expected.add(period_column) + if ( + len(expected) + != len(row_keys) + len(names) + len(_METADATA) + int(period_column is not None) + or set(target.columns) != expected + ): raise ValueError("Prediction target columns differ from the explicit local output schema.") - if target.schema[source.period_column].dataType.typeName() != "timestamp": - raise ValueError("Prediction target period must be a Spark timestamp.") - if source_frame.schema[source.period_column].dataType.typeName() != "timestamp": - raise ValueError("Source period must be a Spark timestamp.") - for name in source.row_keys: + if period_column is not None: + if target.schema[period_column].dataType.typeName() != "timestamp": + raise ValueError("Prediction target period must be a Spark timestamp.") + if source_frame.schema[period_column].dataType.typeName() != "timestamp": + raise ValueError("Source period must be a Spark timestamp.") + for name in row_keys: target_type = target.schema[name].dataType if target_type != source_frame.schema[name].dataType or target_type.typeName() not in ( "long", @@ -146,7 +154,9 @@ def run_local_batch( spark.read.format("delta").option("versionAsOf", source.version).table(source.table) ) target = spark.table(spec.output_table) - output_names = _check_target(spark, source_frame, target, source, prepared) + output_names = _check_target( + spark, source_frame, target, source.row_keys, source.period_column, prepared + ) bridge_names = (*source.row_keys, *output_names) if list(scored.predictions.columns) != list(bridge_names): raise ValueError("Local prediction columns differ from the saved model output.") diff --git a/skyulf-core/skyulf/integrations/databricks/local_sdk.py b/skyulf-core/skyulf/integrations/databricks/local_sdk.py index a11c1cf9f..9908d7c26 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_sdk.py +++ b/skyulf-core/skyulf/integrations/databricks/local_sdk.py @@ -39,6 +39,7 @@ class InputSource(BaseModel): kind: Literal["caller_frame", "uc_table"] table: str | None = None version: int | None = None + read_mode: Literal["snapshot", "incremental"] = "snapshot" max_rows: int = Field(default=100_000, gt=0) max_bytes: int = Field(default=128 * 1024 * 1024, gt=0) @@ -187,16 +188,27 @@ def _config_issues(config: LocalWorkflowConfig) -> list[PreflightIssue]: ) ) if config.source.kind == "uc_table": - if not config.source.table or config.source.version is None or config.source.version < 0: + if ( + not config.source.table + or ( + config.source.read_mode == "snapshot" + and (config.source.version is None or config.source.version < 0) + ) + or (config.source.read_mode == "incremental" and config.source.version is not None) + ): issues.append( PreflightIssue( "source_unbounded", "source", - "UC source needs a table and fixed nonnegative snapshot version.", - "Specify table and version; retain explicit max_rows and max_bytes limits.", + "Snapshot reads need a fixed nonnegative version; incremental reads derive it.", + "Set a version for snapshot reads or omit it for incremental reads.", ) ) - elif config.source.table is not None or config.source.version is not None: + elif ( + config.source.table is not None + or config.source.version is not None + or config.source.read_mode != "snapshot" + ): issues.append( PreflightIssue( "source_conflict", diff --git a/skyulf-core/tests/integrations/test_databricks_local_sdk.py b/skyulf-core/tests/integrations/test_databricks_local_sdk.py index 3c6652015..a10abb401 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_sdk.py +++ b/skyulf-core/tests/integrations/test_databricks_local_sdk.py @@ -298,3 +298,20 @@ def test_preflight_accepts_bounded_uc_delta_sink(tmp_path) -> None: ) result = preflight_local(config, artifact=artifact) assert result.ready + + +def test_incremental_source_config_omits_manual_snapshot_version(tmp_path) -> None: + """Scheduled local scoring can preflight without a user-supplied source version.""" + path, artifact = _artifact(tmp_path) + source = InputSource(kind="uc_table", table="c.s.source", read_mode="incremental") + config = _config(path, source=source, sink=OutputSink(kind="uc_delta", table="c.s.predictions")) + ready = preflight_local(config, artifact=artifact) + pinned = config.model_copy( + update={ + "source": InputSource( + kind="uc_table", table="c.s.source", read_mode="incremental", version=1 + ) + } + ) + invalid = preflight_local(pinned, artifact=artifact) + assert ready.ready and "source_unbounded" in {issue.code for issue in invalid.issues} diff --git a/skyulf-core/tests/integrations/test_local_delta_publish.py b/skyulf-core/tests/integrations/test_local_delta_publish.py index a94c6b43a..49a29efdb 100644 --- a/skyulf-core/tests/integrations/test_local_delta_publish.py +++ b/skyulf-core/tests/integrations/test_local_delta_publish.py @@ -3,11 +3,13 @@ from contextlib import contextmanager from dataclasses import replace from datetime import UTC, datetime, timedelta +from importlib import import_module from importlib.metadata import version from uuid import uuid4 import numpy as np import pandas as pd +import polars as pl import pytest from skyulf.data.dataset import SplitDataset @@ -251,3 +253,370 @@ def test_local_publisher_rejects_stale_model_and_source_identity(local_delta_cas ) assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before_version assert [row.id for row in spark.table(target).collect()] == [9] + + +def test_incremental_local_batch_discovers_appends_without_period_inputs(local_delta_case): + """A second run scores only a late-arriving insert and preserves old predictions.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, source, target, prepared, _, _, admission = local_delta_case + spark.sql(f"DELETE FROM {target} WHERE id = 9") + spark.sql(f"ALTER TABLE {source} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") + config = prepared.config.model_copy( + update={ + "source": InputSource( + kind="uc_table", + table=source, + read_mode="incremental", + max_rows=10, + max_bytes=10_000, + ) + } + ) + prepared = replace(prepared, config=config) + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 6, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + second = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + replay = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + rows = spark.table(target).orderBy("id").collect() + assert [(row.id, round(row.prediction)) for row in rows] == [(1, 4), (2, 8), (3, 12)] + assert first.input_count == 2 and second.input_count == 1 + assert replay.input_count == 0 and replay.noop + assert rows[0]["__skyulf_run_id"] == rows[1]["__skyulf_run_id"] + assert rows[2]["__skyulf_run_id"] != rows[1]["__skyulf_run_id"] + + +def test_incremental_local_batch_does_not_require_a_date_column(local_delta_case): + """New rows are found from Delta commits even when no event date exists.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, _, _, prepared, _, _, admission = local_delta_case + suffix = uuid4().hex + source = f"spark_catalog.default.undated_source_{suffix}" + target = f"spark_catalog.default.undated_target_{suffix}" + spark.createDataFrame([(1, 2.0), (2, 4.0)], "id long, x double").write.format("delta").option( + "delta.enableChangeDataFeed", "true" + ).saveAsTable(source) + spark.createDataFrame( + [], + "id long, prediction double, __skyulf_run_id string, " + "__skyulf_model_name string, __skyulf_model_version string", + ).write.format("delta").saveAsTable(target) + config = prepared.config.model_copy( + update={ + "source": InputSource( + kind="uc_table", + table=source, + read_mode="incremental", + max_rows=10, + max_bytes=10_000, + ), + "sink": OutputSink(kind="uc_delta", table=target), + } + ) + prepared = replace(prepared, config=config) + try: + first = run_incremental_local_batch(spark, prepared, row_keys=("id",), admission=admission) + spark.createDataFrame([(3, 6.0)], "id long, x double").write.format("delta").mode( + "append" + ).saveAsTable(source) + second = run_incremental_local_batch(spark, prepared, row_keys=("id",), admission=admission) + assert (first.input_count, second.input_count) == (2, 1) + assert [ + (row.id, round(row.prediction)) for row in spark.table(target).orderBy("id").collect() + ] == [(1, 4), (2, 8), (3, 12)] + finally: + spark.sql(f"DROP TABLE IF EXISTS {source}") + spark.sql(f"DROP TABLE IF EXISTS {target}") + + +def _prepared_incremental_case(local_delta_case): + """Create an empty target and enable source change tracking for safety checks.""" + spark, source, target, prepared, _, _, admission = local_delta_case + spark.sql(f"DELETE FROM {target} WHERE id = 9") + spark.sql(f"ALTER TABLE {source} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") + config = prepared.config.model_copy( + update={ + "source": InputSource( + kind="uc_table", + table=source, + read_mode="incremental", + max_rows=10, + max_bytes=10_000, + ) + } + ) + return spark, source, target, replace(prepared, config=config), admission + + +def test_incremental_local_batch_rejects_source_updates(local_delta_case): + """Changed source rows cannot silently keep stale predictions or advance the watermark.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, source, target, prepared, admission = _prepared_incremental_case(local_delta_case) + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + original = spark.table(target).orderBy("id").collect() + spark.sql(f"UPDATE {source} SET x = 100.0 WHERE id = 1") + with pytest.raises(ValueError, match="updates and deletes"): + run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert spark.table(target).orderBy("id").collect() == original + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == first.commit_version + + +def test_incremental_local_batch_rejects_existing_prediction_key(local_delta_case): + """A repeated source key must fail without appending a second prediction.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, source, target, prepared, admission = _prepared_incremental_case(local_delta_case) + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(1, datetime(2026, 2, 8, tzinfo=UTC), 40.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + with pytest.raises(BatchConflictError, match="already has"): + run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert spark.table(target).count() == 2 + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == first.commit_version + + +def test_incremental_local_batch_requires_change_feed_before_bootstrap(local_delta_case): + """A source without CDF must fail before writing a target that cannot resume safely.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, source, target, prepared, _, _, admission = local_delta_case + spark.sql(f"DELETE FROM {target} WHERE id = 9") + config = prepared.config.model_copy( + update={ + "source": InputSource( + kind="uc_table", + table=source, + read_mode="incremental", + max_rows=10, + max_bytes=10_000, + ) + } + ) + prepared = replace(prepared, config=config) + before = spark.sql(f"DESCRIBE HISTORY {target}").first().version + with pytest.raises(ValueError, match="Change Data Feed"): + run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before + assert spark.table(target).count() == 0 + + +def test_incremental_local_batch_rejects_target_reset_without_watermark(local_delta_case): + """An empty external rewrite must not erase the committed source watermark.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, _, target, prepared, admission = _prepared_incremental_case(local_delta_case) + run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.sql(f"DELETE FROM {target} WHERE id IN (1, 2)") + before = spark.sql(f"DESCRIBE HISTORY {target}").first().version + with pytest.raises(BatchConflictError, match="outside|receipt"): + run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert spark.table(target).count() == 0 + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before + + +def test_incremental_local_batch_scores_polars_artifact(local_delta_case, tmp_path): + """Automatic source discovery must preserve the fitted Polars engine.""" + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, source, target, prepared, admission = _prepared_incremental_case(local_delta_case) + values = np.arange(20, dtype="float64") + training = pl.DataFrame({"x": values, "target": 2.0 * values}) + artifact = fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=training[:16], test=training[16:]), + target_column="target", + artifact_path=tmp_path / "polars_fitted", + max_rows=20, + max_bytes=10_000, + ) + prepared = replace( + prepared, + config=prepared.config.model_copy(update={"engine": "polars"}), + artifact=artifact, + preflight=replace( + prepared.preflight, + model_digest=artifact.manifest.pipeline_sha256, + ), + ) + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 6, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + second = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert (first.input_count, second.input_count) == (2, 1) + assert [ + (row.id, round(row.prediction)) for row in spark.table(target).orderBy("id").collect() + ] == [(1, 4), (2, 8), (3, 12)] + + +def test_incremental_local_batch_failed_write_keeps_watermark(local_delta_case, monkeypatch): + """A failed target append must leave new source rows available for a clean retry.""" + DataFrameWriter = import_module("pyspark.sql.readwriter").DataFrameWriter + + from skyulf.integrations.databricks import run_incremental_local_batch + from skyulf.integrations.databricks.delta import DeltaPublishError + + spark, source, target, prepared, admission = _prepared_incremental_case(local_delta_case) + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 6, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + original = DataFrameWriter.saveAsTable + + def fail_target(writer, table): + """Inject one target failure after source selection but before Delta commit.""" + if table == target: + raise RuntimeError("injected target failure") + return original(writer, table) + + with monkeypatch.context() as patch: + patch.setattr(DataFrameWriter, "saveAsTable", fail_target) + with pytest.raises(DeltaPublishError, match="Incremental Delta write failed"): + run_incremental_local_batch( + spark, + prepared, + row_keys=("id",), + period_column="event_time", + admission=admission, + ) + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == first.commit_version + retried = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert retried.input_count == 1 and spark.table(target).count() == 3 + + +def test_incremental_local_batch_lost_acknowledgement_is_noop(local_delta_case, monkeypatch): + """A committed append remains visible when the caller loses its response.""" + from skyulf.integrations.databricks import local_incremental, run_incremental_local_batch + + spark, source, target, prepared, admission = _prepared_incremental_case(local_delta_case) + run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 6, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + original = local_incremental._last_receipt + calls = 0 + + def lose_reply(*args): + """Hide the receipt only after the target append has succeeded.""" + nonlocal calls + calls += 1 + if calls == 2: + raise RuntimeError("lost acknowledgement") + return original(*args) + + with monkeypatch.context() as patch: + patch.setattr(local_incremental, "_last_receipt", lose_reply) + with pytest.raises(RuntimeError, match="lost acknowledgement"): + run_incremental_local_batch( + spark, + prepared, + row_keys=("id",), + period_column="event_time", + admission=admission, + ) + committed_version = spark.sql(f"DESCRIBE HISTORY {target}").first().version + retry = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert retry.noop and retry.commit_version == committed_version + assert spark.table(target).count() == 3 + + +def test_incremental_local_batch_respects_shared_admission(local_delta_case): + """A competing publisher must not score or write while the target is owned.""" + from skyulf.integrations.databricks import run_incremental_local_batch + from skyulf.integrations.databricks.delta import table_identity + + spark, _, target, prepared, admission = _prepared_incremental_case(local_delta_case) + before = spark.sql(f"DESCRIBE HISTORY {target}").first().version + with ( + admission.hold(table_identity(spark, target)), + pytest.raises(BatchConflictError, match="holds"), + ): + run_incremental_local_batch( + spark, + prepared, + row_keys=("id",), + period_column="event_time", + admission=admission, + ) + assert spark.table(target).count() == 0 + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == before + + +def test_incremental_local_batch_expired_change_read_does_not_fallback( + local_delta_case, monkeypatch +): + """A missing CDF range must fail closed instead of rescoring the full table.""" + DataFrameReader = import_module("pyspark.sql.readwriter").DataFrameReader + + from skyulf.integrations.databricks import run_incremental_local_batch + + spark, source, target, prepared, admission = _prepared_incremental_case(local_delta_case) + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 6, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + original = DataFrameReader.table + + def expired(reader, table): + """Model an expired CDF range at the Delta read boundary.""" + if table == source: + raise RuntimeError("CDF range expired") + return original(reader, table) + + with monkeypatch.context() as patch: + patch.setattr(DataFrameReader, "table", expired) + with pytest.raises(RuntimeError, match="CDF range expired"): + run_incremental_local_batch( + spark, + prepared, + row_keys=("id",), + period_column="event_time", + admission=admission, + ) + assert spark.table(target).count() == 2 + assert spark.sql(f"DESCRIBE HISTORY {target}").first().version == first.commit_version From fc239414d7862bf9f2087ab572f52ca4717852b8 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 19:41:50 +0300 Subject: [PATCH 35/85] test: validate Skyulf incremental scoring on real taxi data Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 + docs/user_guide/databricks_local_sdk.md | 19 + .../14-sm15i-real-nyctaxi-rehearsal-plan.md | 23 ++ .../15-sm15i-real-nyctaxi-live-report.md | 37 ++ initiatives/spark_and_mlflow/HANDOFF.md | 3 + initiatives/spark_and_mlflow/OPEN_QUEUE.md | 8 +- .../databricks_local_real_taxi_job.py | 380 ++++++++++++++++++ 7 files changed, 473 insertions(+), 2 deletions(-) create mode 100644 initiatives/spark_and_mlflow/14-sm15i-real-nyctaxi-rehearsal-plan.md create mode 100644 initiatives/spark_and_mlflow/15-sm15i-real-nyctaxi-live-report.md create mode 100644 skyulf-core/examples/databricks_local_real_taxi_job.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 4b21d5789..396e2db19 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -47,6 +47,11 @@ execution, MLflow registry and Databricks delivery remain under development. Real local Delta tests cover pandas, Polars and retry/no-op behavior. Two isolated serverless jobs validated initial 80-row scoring, automatic scoring of 80 later inserts, unchanged prior predictions and a no-op replay. +- A separate real NYC taxi proof trained Skyulf preprocessing and a regression + model on 3,000 trips, logged held-out MAE/RMSE/R2 and the full artifact to + MLflow, registered UC model version 1, and scored 200 existing plus 100 + later-inserted trips without changing prior predictions. See the + [live report](../initiatives/spark_and_mlflow/15-sm15i-real-nyctaxi-live-report.md). - Versioned local pandas/Polars pipeline artifact and MLflow pyfunc packaging preserve fitted encoding/binning, model state, input order, class probabilities and explicit tuned thresholds without refitting. The fit engine and exact diff --git a/docs/user_guide/databricks_local_sdk.md b/docs/user_guide/databricks_local_sdk.md index b95da5e03..7a1739918 100644 --- a/docs/user_guide/databricks_local_sdk.md +++ b/docs/user_guide/databricks_local_sdk.md @@ -400,3 +400,22 @@ budget deliberately or handle such a source with a separate distributed path. The target receipt is in the same Delta commit as the predictions. This protects participating writers only; changes outside the admission protocol must be handled explicitly. + +## Real-data end-to-end example + +`skyulf-core/examples/databricks_local_real_taxi_job.py` is a one-time +Databricks notebook using the public `samples.nyctaxi.trips` dataset. It +materializes a bounded copy in an isolated Unity Catalog schema, trains a +Skyulf `SimpleImputer` -> `StandardScaler` -> `OneHotEncoder` -> +`random_forest_regressor` pipeline, saves its full artifact, logs held-out +MAE/RMSE/R2 in MLflow and registers a concrete UC model version. Separate +`score_initial` and `score_append` jobs then call the incremental runner on +200 existing and 100 subsequently inserted trips. Both persist keyed Delta +predictions; the second job checks prior rows and a no-op replay. See the +SM-15I real NYC taxi live report under `initiatives/spark_and_mlflow/` for +run IDs and measured results. + +The example's trip duration and dropoff ZIP are known only after a trip, so +it demonstrates retrospective batch fare estimation. Its hard-coded schema, +experiment and workspace folder are test resources; select your own names +before using it elsewhere. The example is not a scheduled Bundle job. diff --git a/initiatives/spark_and_mlflow/14-sm15i-real-nyctaxi-rehearsal-plan.md b/initiatives/spark_and_mlflow/14-sm15i-real-nyctaxi-rehearsal-plan.md new file mode 100644 index 000000000..7074e912b --- /dev/null +++ b/initiatives/spark_and_mlflow/14-sm15i-real-nyctaxi-rehearsal-plan.md @@ -0,0 +1,23 @@ +# SM-15I real NYC taxi end-to-end rehearsal + +Status: COMPLETE, 2026-09-23. See [the live report](15-sm15i-real-nyctaxi-live-report.md). This validates existing Skyulf Core contracts before SM-20a, not a Bundle implementation. + +## Scope and data + +- Use the previously selected `skyulf` Databricks CLI profile and create only `workspace.skyulf_nyctaxi_e2e_20260923` resources. +- Source is the public real `samples.nyctaxi.trips` table (21,932 rows, six original columns). Read it without modifying it. +- Keep fares $2.50-$100, distance 0.1-30 miles, duration 1-120 minutes, and complete ZIP/timestamp fields; data discovery found 21,723 eligible distinct rows. +- Materialize a deterministic bounded 3,800-row Delta copy with a stable hash key; use 3,000 train, 500 held-out test, 200 initial inference, and 100 later inserts. Fit statistics only on training rows. +- Predict completed-trip fare from distance, trip duration, pickup hour/day and pickup/dropoff ZIP, never from fare itself. Document that this is retrospective batch prediction, not pre-trip pricing. + +## Execution and evidence + +1. Create the isolated schema and MLflow experiment folder. Prepare the source/target/admission Delta tables in a one-time serverless job. Enable source Change Data Feed before the first inference run. +2. Read the bounded training table through Skyulf's UC reader. Fit a Skyulf preprocessing pipeline and regression model with `fit_local_workflow`; evaluate the saved artifact on 500 unseen labels with MAE/RMSE/R2. Log configuration, lineage, artifact and metrics to one MLflow run; register an immutable UC model version. +3. In a second job, resolve that version through `prepare_local_workflow` and call `run_incremental_local_batch` without date/version arguments. Verify exactly 200 persisted keyed predictions against direct model output. +4. Append 100 real held-back trips to the same source Delta table. In a third job, run the same inference call; verify exactly 100 new predictions, prior 200 unchanged, all persisted values match direct model output, and an immediate retry is a no-op. +5. Record schema, tables, model/run/metric identifiers, three job runs, row/version counts, and limitations in a live report. Run local lint/type/doc gates, then mark this rehearsal complete without starting SM-20a. + +## Boundaries + +The proof uses a small pandas local model, Spark for governed Delta reads/writes, insert-only CDF, stable unique keys, shared admission and explicit row/byte limits. It does not claim Spark-native model execution, online serving or production-ready model quality. Never update/delete the public source or alter existing test schemas. diff --git a/initiatives/spark_and_mlflow/15-sm15i-real-nyctaxi-live-report.md b/initiatives/spark_and_mlflow/15-sm15i-real-nyctaxi-live-report.md new file mode 100644 index 000000000..dda8869b1 --- /dev/null +++ b/initiatives/spark_and_mlflow/15-sm15i-real-nyctaxi-live-report.md @@ -0,0 +1,37 @@ +# SM-15I real NYC taxi end-to-end live validation + +Status: PASSED on 2026-09-23. This is a separate real-data rehearsal of the existing small-data Skyulf local pipeline and automatic Delta insert scoring. SM-20a (the first Bundle) remains unstarted. + +## Data and isolated resources + +- CLI profile: `skyulf`, workspace `https://dbc-45604623-c18b.cloud.databricks.com`. +- Public source: [`samples.nyctaxi.trips`](https://dbc-45604623-c18b.cloud.databricks.com/explore/data/samples/nyctaxi/trips?isDbOne=true&utm_source=one-chat&o=7474646244882000), 21,932 original rows; it was read only. +- Filters: fare $2.50-$100, trip distance 0.1-30 miles, trip duration 1-120 minutes and complete source fields. Data discovery found 21,723 eligible distinct rows. The job copied 3,800 of them, deterministically ordered by a SHA-256 key, into the new `workspace.skyulf_nyctaxi_e2e_20260923` schema. +- New managed Delta tables: `taxi_records` (3,800), `taxi_training` (3,500), `taxi_score_source` (200 initially, then 300), `taxi_predictions` (200 initially, then 300), and `taxi_admission` (one owner row). Change Data Feed was enabled on `taxi_score_source` before scoring. +- The first 3,000 training rows, next 500 held-out test rows, next 200 initial inference rows and last 100 later inserts have disjoint stable keys. Only training rows fit preprocessing/model statistics. Inference labels stayed in `taxi_records` and were joined for evaluation *after* predictions were persisted. +- The wheel and notebook are in `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_nyctaxi_e2e_20260923/r1`. Wheel SHA-256: `42ad85847e37980daf06c00fb2f0dfaabf928c62f25e968f4f1c27c73efe5a09`. + +## Skyulf and MLflow model + +The saved Skyulf pipeline fitted `SimpleImputer` (numeric median), `StandardScaler` (numeric), `OneHotEncoder` (pickup/dropoff ZIP, unknown categories ignored) and a 40-tree depth-9 `random_forest_regressor`. The inputs were trip distance, trip duration, pickup hour/day and pickup/dropoff ZIP; `fare_amount` was the label and was never an input. This is completed-trip batch fare estimation, not pre-trip pricing. + +- MLflow experiment: `/Users/edwardwolfe99@gmail.com/skyulf_nyctaxi_e2e_20260923/experiment`, ID `3707030714488006`. +- Training run: `73c53f97d2de48cb9759ed0b3e531f5d`, `FINISHED`. The saved full-pipeline artifact, pipeline configuration and data lineage were logged in this run. The UC model `workspace.skyulf_nyctaxi_e2e_20260923.taxi_fare_skyulf` version **1** is `READY` and points to that same run. Pipeline digest: `09f0f0a4be0b25f46db9442db016362fc3d8ee3784880b962e96d2bbdb3668fa`. +- Independently queried MLflow metrics on 500 held-out real trips: **MAE 0.435143**, **RMSE 1.024078**, **R2 0.988277**. The training run also records source table, row counts, model type and fit engine. +- Independent MLflow artifact listing confirmed `skyulf_pipeline_config.json`, `data_lineage.json` and the `model/` directory on the training run; both inference runs contain `delta_publication_receipt.json`. + +## Three one-time serverless jobs + +All three runs had a 900-second timeout, zero retries, `STANDARD` performance target, the uploaded Skyulf 0.9.0 wheel and `mlflow==3.16.1`. Each ended `SUCCESS`. + +| Stage | Parent run / task run | Source rows selected | Target rows / version | MLflow run and observed metrics | +| --- | --- | ---: | ---: | --- | +| Train and create data | [653952531609511](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/246102427177961/run/653952531609511) / `557281442176653` | 3,000 train + 500 held-out | 0 | `73c53f97d2de48cb9759ed0b3e531f5d`; metrics above | +| First inference | [564243921177963](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/354675847486158/run/564243921177963) / `616926090231392` | 200 snapshot rows | 200 / 1 | `ee754c66f6b34db3ab3df2d551bbaf6e`; observed MAE 0.627872, RMSE 3.374626 | +| Append and infer | [1103696172771856](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/649442154281950/run/1103696172771856) / `568639379332373` | 100 CDF inserts | 300 / 2 | `b1f9a0f27d904260926a6c90b1fc9f68`; cumulative observed MAE 0.636182, RMSE 3.062555 | + +Both inference runs loaded the same pinned UC model version through `prepare_local_workflow` and called `run_incremental_local_batch` without a date or source-version argument. Every persisted keyed prediction was compared with a fresh direct call to the registered local model. The second run checked all first 200 complete target rows were unchanged. An immediate third scoring call selected zero rows and left the target Delta version at **2**. The source high-water mark advanced from version **1** to **2** with the matching target commit. Both inference MLflow runs were independently queried and contain input/output/target row counts plus observed MAE/RMSE. + +## Interpretation and boundary + +This confirms the requested first-all-rows, later-new-rows behavior on real data. The measured scores are for one historical public sample and one held-out split; they do not establish production fitness or stability under data drift. Trip duration and dropoff ZIP are available after a trip, so this model is suitable only for retrospective/batch scoring. The incremental writer still requires insert-only changes, CDF retention, globally unique keys, bounded local batches and shared admission. The job notebook is a one-time rehearsal; a scheduled and restartable generated project is SM-20a. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index f5dcf67f6..a66c85a21 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -18,6 +18,9 @@ promotion. Target release: 0.9.0. Branch: `090`. Start SM-20a from [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. + A later [real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) + trained a Skyulf model with held-out MLflow metrics, registered UC model + version 1, then passed 200 initial + 100 new-row predictions and a no-op replay. SM-26 added local artifact and MLflow packaging without cloud execution. The SM-25 SDK adds immutable local workflow configuration, local/remote preflight, explicit path or pinned registry artifact selection and caller-frame limits. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 537711a93..2a62143ae 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -38,7 +38,7 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-15 | Monthly batch + Delta sink | SM-14 | DONE | 43 local Delta/contract/admission tests; evidence below | | SM-16 | Gerçek Databricks kapısı | SM-15 | DONE | Selected serverless workflow passed; live evidence below | | SM-15L | Explicit-period local predictions -> UC Delta | SM-24a | DONE | Score requested period; preserve rows outside it; Spark only for bounded I/O | -| SM-15I | Automatic incremental local scoring | SM-15L | DONE | No date/source-version input; 80+80 live Delta rows, no-op replay; [evidence](13-sm15i-live-validation-report.md) | +| SM-15I | Automatic incremental local scoring | SM-15L | DONE | No date/source-version input; 80+80 synthetic and 200+100 real taxi rows; no-op replay; [core evidence](13-sm15i-live-validation-report.md), [real-data proof](15-sm15i-real-nyctaxi-live-report.md) | | SM-17 | Complete existing Spark node/model coverage | SM-20a | LATER | Resume only after the first local Bundle; preserve all inventoried gaps | | SM-18 | Backend/Canvas and legacy artifact bridge | SM-17 | PARKED | Capability UI/API, DAG contracts and existing deployment compatibility | | SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | @@ -165,7 +165,11 @@ watermark from the committed output receipt. See the [SM-15I plan](12-sm15i-incremental-scoring-plan.md). This is a prerequisite for SM-20a. The runner passed local real-Delta gates and the isolated two-job Databricks rehearsal, including a source with no date column; see the -[SM-15I validation report](13-sm15i-live-validation-report.md). +[SM-15I validation report](13-sm15i-live-validation-report.md). A separate +[real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) trained a Skyulf +pipeline with MLflow metrics and registered UC model version 1, then passed +200 initial + 100 later real-row predictions with an unchanged prior batch and +no-op replay. SM-20a remains the next task. ## SM-15L - 2026-09-23 monthly local UC Delta publication, DONE diff --git a/skyulf-core/examples/databricks_local_real_taxi_job.py b/skyulf-core/examples/databricks_local_real_taxi_job.py new file mode 100644 index 000000000..72cac7149 --- /dev/null +++ b/skyulf-core/examples/databricks_local_real_taxi_job.py @@ -0,0 +1,380 @@ +# Databricks notebook source +"""Train and replay a Skyulf local model on real NYC taxi Delta rows.""" + +from __future__ import annotations + +import json +import tempfile +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import mlflow # ty: ignore[unresolved-import] +import numpy as np +from pyspark.sql import Window # ty: ignore[unresolved-import] +from pyspark.sql import functions as F # ty: ignore[unresolved-import] + +from skyulf.data.dataset import SplitDataset +from skyulf.integrations.databricks import ( + InputSource, + LocalSourceSpec, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + evaluate_local_holdout, + fit_local_workflow, + prepare_local_workflow, + read_local_source, + run_incremental_local_batch, +) +from skyulf.integrations.databricks.delta import table_identity +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission +from skyulf.integrations.mlflow.local_model import log_local_model +from skyulf.integrations.mlflow.registry import register_model + +SCHEMA = "workspace.skyulf_nyctaxi_e2e_20260923" +EXPERIMENT = "/Users/edwardwolfe99@gmail.com/skyulf_nyctaxi_e2e_20260923/experiment" +SAMPLE = "samples.nyctaxi.trips" +RECORDS = f"{SCHEMA}.taxi_records" +TRAINING = f"{SCHEMA}.taxi_training" +SOURCE = f"{SCHEMA}.taxi_score_source" +TARGET = f"{SCHEMA}.taxi_predictions" +CONTROL = f"{SCHEMA}.taxi_admission" +MODEL = f"{SCHEMA}.taxi_fare_skyulf" +FEATURES = ( + "trip_distance", + "trip_duration_minutes", + "pickup_hour", + "pickup_weekday", + "pickup_zip", + "dropoff_zip", +) +MODEL_CONFIG: dict[str, Any] = { + "preprocessing": [ + { + "name": "fill_numeric", + "transformer": "SimpleImputer", + "params": {"columns": list(FEATURES[:4]), "strategy": "median"}, + }, + { + "name": "scale_numeric", + "transformer": "StandardScaler", + "params": {"columns": list(FEATURES[:4])}, + }, + { + "name": "encode_zips", + "transformer": "OneHotEncoder", + "params": {"columns": list(FEATURES[4:]), "handle_unknown": "ignore"}, + }, + ], + "modeling": { + "type": "random_forest_regressor", + "params": {"n_estimators": 40, "max_depth": 9, "random_state": 42, "n_jobs": 1}, + }, +} + + +def _new_tables(spark: Any) -> None: + """Create isolated real-data tables once, with disjoint training and scoring keys.""" + names = (RECORDS, TRAINING, SOURCE, TARGET, CONTROL) + existing = [name for name in names if spark.catalog.tableExists(name)] + if existing: + raise ValueError(f"This test revision already has tables: {existing}") + raw_columns = ( + "tpep_pickup_datetime", + "tpep_dropoff_datetime", + "trip_distance", + "fare_amount", + "pickup_zip", + "dropoff_zip", + ) + source = spark.table(SAMPLE) + duration = ( + F.unix_timestamp("tpep_dropoff_datetime") - F.unix_timestamp("tpep_pickup_datetime") + ) / F.lit(60.0) + clean = ( + source.withColumn("trip_duration_minutes", duration) + .where(F.col("fare_amount").between(2.5, 100.0)) + .where(F.col("trip_distance").between(0.1, 30.0)) + .where(F.col("trip_duration_minutes").between(1.0, 120.0)) + .dropna(subset=list(raw_columns)) + .withColumn("entity_id", F.sha2(F.to_json(F.struct(*raw_columns)), 256)) + .withColumn("pickup_hour", F.hour("tpep_pickup_datetime").cast("double")) + .withColumn("pickup_weekday", F.dayofweek("tpep_pickup_datetime").cast("double")) + .withColumn("pickup_zip", F.col("pickup_zip").cast("string")) + .withColumn("dropoff_zip", F.col("dropoff_zip").cast("string")) + .select("entity_id", "tpep_pickup_datetime", *FEATURES, "fare_amount") + .orderBy("entity_id") + .limit(3_800) + .withColumn("split_index", F.row_number().over(Window.orderBy("entity_id"))) + ) + clean.write.format("delta").saveAsTable(RECORDS) + records = spark.table(RECORDS) + if records.count() != 3_800 or records.select("entity_id").distinct().count() != 3_800: + raise AssertionError("The real taxi copy must contain 3,800 unique trips.") + records.where(F.col("split_index") <= 3_500).drop("split_index").write.format( + "delta" + ).saveAsTable(TRAINING) + records.where(F.col("split_index").between(3_501, 3_700)).select( + "entity_id", *FEATURES + ).write.format("delta").saveAsTable(SOURCE) + spark.sql(f"ALTER TABLE {SOURCE} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") + spark.sql( + f"CREATE TABLE {TARGET} (entity_id STRING, prediction DOUBLE, " + "__skyulf_run_id STRING, __skyulf_model_name STRING, " + "__skyulf_model_version STRING) USING DELTA" + ) + spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") + spark.sql( + f"INSERT INTO {CONTROL} SELECT :target_id, CAST(NULL AS STRING)", + args={"target_id": table_identity(spark, TARGET)}, + ).collect() + + +def _training_frame(spark: Any) -> Any: + """Read an explicit bounded training snapshot through Skyulf's UC reader.""" + source_version = int(spark.sql(f"DESCRIBE HISTORY {TRAINING}").first().version) + frame = read_local_source( + spark, + LocalSourceSpec( + table=TRAINING, + version=source_version, + period_start=datetime(2016, 1, 1, tzinfo=UTC), + period_end=datetime(2016, 3, 1, tzinfo=UTC), + period_column="tpep_pickup_datetime", + row_keys=("entity_id",), + input_columns=(*FEATURES, "fare_amount"), + max_rows=3_500, + max_bytes=12_000_000, + ), + ) + if len(frame) != 3_500: + raise AssertionError("The training read did not return 3,500 real trips.") + return frame + + +def train(spark: Any) -> dict[str, Any]: + """Fit Skyulf FE/model, log held-out metrics and register one UC version.""" + _new_tables(spark) + frame = _training_frame(spark) + train_frame = frame.iloc[:3_000].loc[:, [*FEATURES, "fare_amount"]] + heldout = frame.iloc[3_000:].loc[:, [*FEATURES, "fare_amount"]] + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + mlflow.set_experiment(EXPERIMENT) + with tempfile.TemporaryDirectory(prefix="skyulf-taxi-") as directory: + artifact_path = Path(directory) / "taxi_model" + artifact = fit_local_workflow( + MODEL_CONFIG, + SplitDataset(train=train_frame, test=heldout), + target_column="fare_amount", + artifact_path=artifact_path, + max_rows=3_500, + max_bytes=12_000_000, + ) + metrics = evaluate_local_holdout(artifact, heldout, target_column="fare_amount") + if not all(np.isfinite(value) for value in metrics.values()): + raise AssertionError("Held-out model metrics are not finite.") + with mlflow.start_run(run_name="skyulf-nyctaxi-train") as run: + mlflow.set_tags({"skyulf_phase": "train", "dataset": SAMPLE, "validation": "held_out"}) + mlflow.log_params( + { + "source_table": TRAINING, + "training_rows": 3_000, + "heldout_rows": 500, + "fit_engine": "pandas", + "target_column": "fare_amount", + "model_type": "random_forest_regressor", + "model_digest": artifact.manifest.pipeline_sha256, + } + ) + mlflow.log_metrics(metrics) + mlflow.log_dict(MODEL_CONFIG, "skyulf_pipeline_config.json") + mlflow.log_dict( + { + "sample": SAMPLE, + "records": RECORDS, + "training": TRAINING, + "features": FEATURES, + "split": [3_000, 500, 200, 100], + }, + "data_lineage.json", + ) + model_uri = log_local_model( + artifact_path, + run_id=run.info.run_id, + artifact_path="model", + tracking_uri="databricks", + ) + registered = register_model( + model_uri, + MODEL, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if str(registered.version) != "1": + raise AssertionError("A fresh schema must create the first UC model version.") + return { + "stage": "train", + "sample": SAMPLE, + "records": 3_800, + "training": 3_000, + "heldout": 500, + "initial_source": int(spark.table(SOURCE).count()), + "model": MODEL, + "version": str(registered.version), + "run_id": run.info.run_id, + "digest": artifact.manifest.pipeline_sha256, + "metrics": metrics, + } + + +def _prepared() -> Any: + """Resolve the immutable first UC model version for both score jobs.""" + return prepare_local_workflow( + LocalWorkflowConfig( + runtime="databricks", + engine="pandas", + source=InputSource( + kind="uc_table", + table=SOURCE, + read_mode="incremental", + max_rows=300, + max_bytes=4_000_000, + ), + model=ModelSelection( + kind="local_pipeline", + name=MODEL, + version="1", + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + sink=OutputSink(kind="uc_delta", table=TARGET), + ) + ) + + +def _verify(spark: Any, prepared: Any, expected: int) -> dict[str, float]: + """Compare every persisted score with direct model output and unseen labels.""" + source = spark.table(SOURCE).select("entity_id", *FEATURES).orderBy("entity_id").toPandas() + actual = spark.table(TARGET).select("entity_id", "prediction").orderBy("entity_id").toPandas() + if len(source) != expected or len(actual) != expected: + raise AssertionError("Source and target counts differ from the expected stage.") + if source["entity_id"].tolist() != actual["entity_id"].tolist(): + raise AssertionError("Persisted prediction keys do not match source keys.") + direct = prepared.predict(source.loc[:, list(FEATURES)]) + np.testing.assert_allclose( + actual["prediction"].to_numpy(), + direct["prediction"].to_numpy(), + rtol=0, + atol=1e-9, + ) + labels = ( + spark.table(RECORDS) + .join(spark.table(SOURCE).select("entity_id"), on="entity_id", how="inner") + .select("entity_id", "fare_amount") + .toPandas() + ) + aligned = actual.merge(labels, on="entity_id", how="left", validate="one_to_one") + if aligned["fare_amount"].isna().any(): + raise AssertionError("An inference row lacks a held-back evaluation label.") + errors = aligned["prediction"] - aligned["fare_amount"] + return { + "observed_mae": float(np.abs(errors).mean()), + "observed_rmse": float(np.sqrt(np.mean(np.square(errors)))), + } + + +def _score(spark: Any, stage: str, expected_input: int, expected_total: int) -> dict[str, Any]: + """Record a separate MLflow inference run and validate the committed Delta rows.""" + mlflow.set_tracking_uri("databricks") + mlflow.set_experiment(EXPERIMENT) + prepared = _prepared() + admission = DeltaTableAdmission(spark, CONTROL) + with mlflow.start_run(run_name=f"skyulf-nyctaxi-{stage}") as run: + mlflow.set_tags({"skyulf_phase": stage, "dataset": SAMPLE}) + result = run_incremental_local_batch( + spark, prepared, row_keys=("entity_id",), admission=admission + ) + if result.noop or result.input_count != expected_input: + raise AssertionError("The incremental scorer selected the wrong number of trips.") + observed = _verify(spark, prepared, expected_total) + mlflow.log_params( + { + "model_name": MODEL, + "model_version": "1", + "source_table": SOURCE, + "target_table": TARGET, + "source_end_version": result.source_end_version, + } + ) + mlflow.log_metrics( + { + "input_rows": result.input_count, + "output_rows": result.output_count, + "target_rows": expected_total, + **observed, + } + ) + if result.manifest is not None: + mlflow.log_dict(result.manifest, "delta_publication_receipt.json") + return { + "stage": stage, + "input_rows": result.input_count, + "target_rows": expected_total, + "source_end_version": result.source_end_version, + "target_version": result.commit_version, + "mlflow_run_id": run.info.run_id, + **observed, + } + + +def score_initial(spark: Any) -> dict[str, Any]: + """Score the first 200 records without a date or source-version argument.""" + return _score(spark, "score_initial", 200, 200) + + +def score_append(spark: Any) -> dict[str, Any]: + """Append 100 held-back real trips, then score only those new keys.""" + before = spark.table(TARGET).orderBy("entity_id").collect() + if len(before) != 200 or spark.table(SOURCE).count() != 200: + raise ValueError("Initial 200-row scoring stage has not completed cleanly.") + pending = ( + spark.table(RECORDS) + .where(F.col("split_index").between(3_701, 3_800)) + .select("entity_id", *FEATURES) + ) + if pending.count() != 100: + raise AssertionError("Expected exactly 100 held-back real trips.") + pending.write.format("delta").mode("append").saveAsTable(SOURCE) + result = _score(spark, "score_append", 100, 300) + after = spark.table(TARGET).orderBy("entity_id").collect() + original_keys = {row.entity_id for row in before} + if [row for row in after if row.entity_id in original_keys] != before: + raise AssertionError("The first 200 persisted predictions changed after append.") + replay = run_incremental_local_batch( + spark, _prepared(), row_keys=("entity_id",), admission=DeltaTableAdmission(spark, CONTROL) + ) + if ( + not replay.noop + or replay.input_count != 0 + or replay.commit_version != result["target_version"] + ): + raise AssertionError("An immediate replay created another target commit.") + return {**result, "unchanged_initial_rows": 200, "noop_target_version": replay.commit_version} + + +runtime_dbutils: Any = globals().get("dbutils") +runtime_spark: Any = globals().get("spark") +if runtime_dbutils is not None and runtime_spark is not None: + runtime_dbutils.widgets.text("stage", "train") + stage = runtime_dbutils.widgets.get("stage") + if stage == "train": + outcome = train(runtime_spark) + elif stage == "score_initial": + outcome = score_initial(runtime_spark) + elif stage == "score_append": + outcome = score_append(runtime_spark) + else: + raise ValueError(f"Unknown taxi stage: {stage}") + runtime_dbutils.notebook.exit(json.dumps(outcome)) From 2fbafc53bbda4ba5e11dbdb31b9d46f0cbc6ee89 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 19:55:48 +0300 Subject: [PATCH 36/85] refactor: use generic prediction metadata columns Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 ++++++ docs/user_guide/databricks_batch.md | 6 +++--- docs/user_guide/databricks_local_sdk.md | 9 +++++++-- skyulf-core/examples/databricks_delta_smoke.py | 4 ++-- .../examples/databricks_local_real_taxi_job.py | 4 ++-- skyulf-core/examples/databricks_local_sm15i_job.py | 4 ++-- skyulf-core/examples/databricks_local_sm15l_job.py | 6 +++--- .../skyulf/integrations/databricks/_contracts.py | 6 ++++++ .../skyulf/integrations/databricks/batch.py | 10 ++++++---- .../skyulf/integrations/databricks/delta.py | 6 +++--- .../integrations/databricks/local_incremental.py | 10 ++++++---- .../integrations/databricks/local_publish.py | 10 +++++----- .../tests/integrations/test_batch_contract.py | 2 ++ .../tests/integrations/test_delta_publish.py | 14 +++++++------- .../tests/integrations/test_local_delta_publish.py | 13 ++++++------- 15 files changed, 66 insertions(+), 44 deletions(-) diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 396e2db19..74bb007b4 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -8,6 +8,12 @@ Target: optional Spark execution and MLflow integration for Skyulf Core. Development version: 0.9.0. This release has not been published; Spark node execution, MLflow registry and Databricks delivery remain under development. +### Changed + +- Prediction Delta targets use `run_id`, `model_name` and `model_version` + metadata columns. Existing test targets with the former `__skyulf_*` + schema require a new target; the writer does not migrate tables. + ### Fixed - Spark identifier validation tolerates Databricks serverless hiding diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md index 26ebda863..362114499 100644 --- a/docs/user_guide/databricks_batch.md +++ b/docs/user_guide/databricks_batch.md @@ -60,9 +60,9 @@ CREATE TABLE analytics.customer_predictions ( customer_id BIGINT, event_time TIMESTAMP, prediction DOUBLE, - __skyulf_run_id STRING, - __skyulf_model_name STRING, - __skyulf_model_version STRING + run_id STRING, + model_name STRING, + model_version STRING ) USING DELTA; ``` diff --git a/docs/user_guide/databricks_local_sdk.md b/docs/user_guide/databricks_local_sdk.md index 7a1739918..33d73dc9d 100644 --- a/docs/user_guide/databricks_local_sdk.md +++ b/docs/user_guide/databricks_local_sdk.md @@ -262,7 +262,12 @@ job. The source and target must be different Delta tables. The target must have the row-key columns with the same Spark types as the source (`long` or `string`), a `timestamp` period column, the saved model's output columns at their declared types, and three string columns: -`__skyulf_run_id`, `__skyulf_model_name` and `__skyulf_model_version`. +`run_id`, `model_name` and `model_version`. +Here `run_id` identifies the prediction publication, not the MLflow training run; +the incremental writer derives it from the source/model snapshot. Existing test +targets with `__skyulf_*` columns retain their historical schema; create a +new target with these names for the updated writer. + The control table has exactly one row, `target_id STRING` equal to the target Delta table ID and nullable `owner STRING` initially null. Every publisher of this target must use that same control table. The job identity needs read @@ -352,7 +357,7 @@ It never filters rows by that column, including late arrivals. Provision a distinct, initially empty Delta prediction table with the globally unique key, saved model output columns and -`__skyulf_run_id`, `__skyulf_model_name`, `__skyulf_model_version` string +`run_id`, `model_name`, `model_version` string columns. If carrying an event timestamp, add a matching Spark `timestamp` column to both tables. Enable Delta Change Data Feed on the source **before** any changes that the job must consume. Provision the same shared admission diff --git a/skyulf-core/examples/databricks_delta_smoke.py b/skyulf-core/examples/databricks_delta_smoke.py index a09af3bfa..479b9e260 100644 --- a/skyulf-core/examples/databricks_delta_smoke.py +++ b/skyulf-core/examples/databricks_delta_smoke.py @@ -85,8 +85,8 @@ def run_smoke( ).write.format("delta").saveAsTable(names["source"]) spark.createDataFrame( [(9, datetime(2025, 12, 1, tzinfo=UTC), 99.0, "prior", model_name, model_version)], - "id long, event_time timestamp, prediction double, __skyulf_run_id string, " - "__skyulf_model_name string, __skyulf_model_version string", + "id long, event_time timestamp, prediction double, run_id string, " + "model_name string, model_version string", ).write.format("delta").saveAsTable(names["target"]) prior = spark.table(names["target"]).first() spark.createDataFrame( diff --git a/skyulf-core/examples/databricks_local_real_taxi_job.py b/skyulf-core/examples/databricks_local_real_taxi_job.py index 72cac7149..69ac53305 100644 --- a/skyulf-core/examples/databricks_local_real_taxi_job.py +++ b/skyulf-core/examples/databricks_local_real_taxi_job.py @@ -121,8 +121,8 @@ def _new_tables(spark: Any) -> None: spark.sql(f"ALTER TABLE {SOURCE} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") spark.sql( f"CREATE TABLE {TARGET} (entity_id STRING, prediction DOUBLE, " - "__skyulf_run_id STRING, __skyulf_model_name STRING, " - "__skyulf_model_version STRING) USING DELTA" + "run_id STRING, model_name STRING, " + "model_version STRING) USING DELTA" ) spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") spark.sql( diff --git a/skyulf-core/examples/databricks_local_sm15i_job.py b/skyulf-core/examples/databricks_local_sm15i_job.py index 47facbc50..c0afed3b5 100644 --- a/skyulf-core/examples/databricks_local_sm15i_job.py +++ b/skyulf-core/examples/databricks_local_sm15i_job.py @@ -79,8 +79,8 @@ def bootstrap(spark: Any) -> dict[str, Any]: spark.sql(f"ALTER TABLE {SOURCE} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") spark.sql( f"CREATE TABLE {TARGET} (entity_id STRING, prediction DOUBLE, " - "__skyulf_run_id STRING, __skyulf_model_name STRING, " - "__skyulf_model_version STRING) USING DELTA" + "run_id STRING, model_name STRING, " + "model_version STRING) USING DELTA" ) spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") spark.sql( diff --git a/skyulf-core/examples/databricks_local_sm15l_job.py b/skyulf-core/examples/databricks_local_sm15l_job.py index c756a988c..0d40ba21c 100644 --- a/skyulf-core/examples/databricks_local_sm15l_job.py +++ b/skyulf-core/examples/databricks_local_sm15l_job.py @@ -125,13 +125,13 @@ def _verify_month( (F.col("event_time") >= F.lit(source.period_start)) & (F.col("event_time") < F.lit(source.period_end)) ) - .select("entity_id", "prediction", "__skyulf_run_id") + .select("entity_id", "prediction", "run_id") .orderBy("entity_id") .collect() ) actual_keys = [row["entity_id"] for row in rows] expected_keys = sorted(gold.index.tolist()) - if actual_keys != expected_keys or any(row["__skyulf_run_id"] != run_id for row in rows): + if actual_keys != expected_keys or any(row["run_id"] != run_id for row in rows): raise AssertionError("Persisted keys or run metadata differ from the local gold rows.") np.testing.assert_allclose( [row["prediction"] for row in rows], @@ -156,7 +156,7 @@ def january(spark: Any) -> dict[str, Any]: ).write.format("delta").saveAsTable(SOURCE) spark.sql( f"CREATE TABLE {TARGET} (entity_id STRING, event_time TIMESTAMP, prediction DOUBLE, " - "__skyulf_run_id STRING, __skyulf_model_name STRING, __skyulf_model_version STRING) USING DELTA" + "run_id STRING, model_name STRING, model_version STRING) USING DELTA" ) spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") target_id = table_identity(spark, TARGET) diff --git a/skyulf-core/skyulf/integrations/databricks/_contracts.py b/skyulf-core/skyulf/integrations/databricks/_contracts.py index 422945631..e2a4e1cfd 100644 --- a/skyulf-core/skyulf/integrations/databricks/_contracts.py +++ b/skyulf-core/skyulf/integrations/databricks/_contracts.py @@ -6,6 +6,8 @@ from typing import Any from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +PREDICTION_METADATA_COLUMNS = ("run_id", "model_name", "model_version") + def table_name(value: str) -> str: """Validate and quote a simple one-, two- or three-part catalog identifier.""" @@ -75,6 +77,10 @@ def __post_init__(self) -> None: names = [key.lower() for key in self.row_keys] if len(set(names)) != len(names) or self.period_column.lower() in names: raise ValueError("row_keys and period_column must be distinct.") + if any( + name in PREDICTION_METADATA_COLUMNS for name in (*names, self.period_column.lower()) + ): + raise ValueError("row_keys and period_column collide with prediction metadata.") for name in ("model_name", "code_version", "run_id"): value = getattr(self, name) if type(value) is not str or not value.strip() or len(value) > 512: diff --git a/skyulf-core/skyulf/integrations/databricks/batch.py b/skyulf-core/skyulf/integrations/databricks/batch.py index 2d7fd0c81..40340d414 100644 --- a/skyulf-core/skyulf/integrations/databricks/batch.py +++ b/skyulf-core/skyulf/integrations/databricks/batch.py @@ -10,7 +10,7 @@ from ...core.execution import ExecutionOptions, FrameSpec from ...inference.bundle import InferenceBundle, _validate_bundle from ...inference.spark import predict_spark -from ._contracts import BatchResult, BatchSpec, table_name +from ._contracts import PREDICTION_METADATA_COLUMNS, BatchResult, BatchSpec, table_name from .admission import PublishAdmission, validate_admission from .delta import history, publish_replace_period, table_identity @@ -82,6 +82,8 @@ def run_batch( output_names = {column.name.lower() for column in bundle.manifest.output_schema} if spec.period_column.lower() in output_names: raise ValueError("period_column collides with a model output column.") + if output_names.intersection(PREDICTION_METADATA_COLUMNS): + raise ValueError("Model output column collides with prediction metadata.") predictions = predict_spark( selected, bundle, @@ -93,9 +95,9 @@ def run_batch( selected.select(*spec.row_keys, spec.period_column), on=list(spec.row_keys), how="inner" ) for name, value in ( - ("__skyulf_run_id", spec.run_id), - ("__skyulf_model_name", spec.model_name), - ("__skyulf_model_version", spec.model_version), + ("run_id", spec.run_id), + ("model_name", spec.model_name), + ("model_version", spec.model_version), ): output = output.withColumn(name, functions.lit(value)) target = spark.table(spec.output_table) diff --git a/skyulf-core/skyulf/integrations/databricks/delta.py b/skyulf-core/skyulf/integrations/databricks/delta.py index 6f79e68ff..0f3045b6a 100644 --- a/skyulf-core/skyulf/integrations/databricks/delta.py +++ b/skyulf-core/skyulf/integrations/databricks/delta.py @@ -117,9 +117,9 @@ def _validate_frame(frame: Any, spec: BatchSpec, manifest: dict[str, Any]) -> No | (period >= functions.lit(spec.period_end_utc)) ) for name, expected in ( - ("__skyulf_run_id", spec.run_id), - ("__skyulf_model_name", spec.model_name), - ("__skyulf_model_version", spec.model_version), + ("run_id", spec.run_id), + ("model_name", spec.model_name), + ("model_version", spec.model_version), ): invalid = invalid | frame[name].isNull() | (frame[name] != functions.lit(expected)) if frame.where(invalid).limit(1).count(): diff --git a/skyulf-core/skyulf/integrations/databricks/local_incremental.py b/skyulf-core/skyulf/integrations/databricks/local_incremental.py index 99bcb5211..9f395c3f6 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_incremental.py +++ b/skyulf-core/skyulf/integrations/databricks/local_incremental.py @@ -13,7 +13,7 @@ import pandas as pd from ...inference.local_pipeline import LocalPipelineArtifact -from ._contracts import column_name, table_name +from ._contracts import PREDICTION_METADATA_COLUMNS, column_name, table_name from .admission import BatchConflictError, PublishAdmission, validate_admission from .delta import DeltaPublishError, history, table_identity from .local_batch import _frame_bytes @@ -103,6 +103,8 @@ def _validate_prepared( names = (*row_keys, *((period_column,) if period_column is not None else ())) if len({name.lower() for name in names}) != len(names): raise ValueError("row_keys and period_column must be distinct.") + if any(name.lower() in PREDICTION_METADATA_COLUMNS for name in names): + raise ValueError("row_keys and period_column collide with prediction metadata.") inputs = prepared.artifact.manifest.input_columns if any(key in inputs for key in row_keys) or ( period_column is not None and period_column in inputs @@ -288,9 +290,9 @@ def run_incremental_local_batch( ).hexdigest() manifest = {**run_input, "run_id": digest, "request_digest": digest} for name, value in ( - ("__skyulf_run_id", digest), - ("__skyulf_model_name", config.model.name), - ("__skyulf_model_version", config.model.version), + ("run_id", digest), + ("model_name", config.model.name), + ("model_version", config.model.version), ): output = output.withColumn(name, functions.lit(value)) if {field.name: field.dataType for field in output.schema} != { diff --git a/skyulf-core/skyulf/integrations/databricks/local_publish.py b/skyulf-core/skyulf/integrations/databricks/local_publish.py index 80c8381a9..89fec8f74 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_publish.py +++ b/skyulf-core/skyulf/integrations/databricks/local_publish.py @@ -11,7 +11,7 @@ import pandas as pd from ...inference.local_pipeline import LocalPipelineArtifact -from ._contracts import BatchResult, BatchSpec +from ._contracts import PREDICTION_METADATA_COLUMNS, BatchResult, BatchSpec from .admission import PublishAdmission, validate_admission from .batch import _manifest from .delta import history, publish_replace_period, table_identity @@ -19,7 +19,7 @@ from .local_sdk import PreparedLocalWorkflow _OUTPUT_TYPES = {"float64": "double", "int64": "long", "string": "string", "bool": "boolean"} -_METADATA = ("__skyulf_run_id", "__skyulf_model_name", "__skyulf_model_version") +_METADATA = PREDICTION_METADATA_COLUMNS def _validate_request( @@ -177,9 +177,9 @@ def run_local_batch( ).select(*source.row_keys, source.period_column) output = bridge.join(source_period, on=list(source.row_keys), how="inner") for name, value in ( - ("__skyulf_run_id", spec.run_id), - ("__skyulf_model_name", spec.model_name), - ("__skyulf_model_version", spec.model_version), + ("run_id", spec.run_id), + ("model_name", spec.model_name), + ("model_version", spec.model_version), ): output = output.withColumn(name, functions.lit(value)) if {field.name: field.dataType for field in output.schema} != { diff --git a/skyulf-core/tests/integrations/test_batch_contract.py b/skyulf-core/tests/integrations/test_batch_contract.py index a7d7d33ae..80fbfef0e 100644 --- a/skyulf-core/tests/integrations/test_batch_contract.py +++ b/skyulf-core/tests/integrations/test_batch_contract.py @@ -44,6 +44,8 @@ def test_naive_dates_fail(spec, field): {"period_end": datetime(2025, 12, 1, tzinfo=UTC)}, {"row_keys": ("id", "id")}, {"row_keys": ("__skyulf_run_id",)}, + {"row_keys": ("run_id",)}, + {"period_column": "model_name"}, {"output_table": "default.x; DROP TABLE x"}, {"model_version": "champion"}, {"model_version": "-1"}, diff --git a/skyulf-core/tests/integrations/test_delta_publish.py b/skyulf-core/tests/integrations/test_delta_publish.py index 630d7d68a..81235ca44 100644 --- a/skyulf-core/tests/integrations/test_delta_publish.py +++ b/skyulf-core/tests/integrations/test_delta_publish.py @@ -42,8 +42,8 @@ def harness(delta_spark, tmp_path): [ (9, datetime(2025, 12, 1, tzinfo=UTC), 99.0, "prior", "risk", "6"), ], - "id long, event_time timestamp, prediction double, __skyulf_run_id string, " - "__skyulf_model_name string, __skyulf_model_version string", + "id long, event_time timestamp, prediction double, run_id string, " + "model_name string, model_version string", ).write.format("delta").saveAsTable(target) spec = BatchSpec( period_start=datetime(2026, 1, 1, tzinfo=UTC), @@ -153,7 +153,7 @@ def test_old_retry_cannot_undo_explicit_recomputation(harness): old = _run(h) assert newer.commit_version == 2 assert old.commit_version == 1 and old.replayed - assert h.spark.table(h.target).where("id = 1").first()["__skyulf_run_id"] == "recompute" + assert h.spark.table(h.target).where("id = 1").first()["run_id"] == "recompute" def test_empty_replacement_is_explicit_and_records_a_commit(harness): @@ -238,11 +238,11 @@ def test_sink_rejects_invalid_rows_without_modifying_target(harness, violation): output = ( h.spark.table(h.target) .withColumn("event_time", functions.lit(instant).cast("timestamp")) - .withColumn("__skyulf_run_id", functions.lit(h.spec.run_id)) - .withColumn("__skyulf_model_version", functions.lit(h.spec.model_version)) + .withColumn("run_id", functions.lit(h.spec.run_id)) + .withColumn("model_version", functions.lit(h.spec.model_version)) ) if violation == "metadata": - output = output.withColumn("__skyulf_model_name", functions.lit(None).cast("string")) + output = output.withColumn("model_name", functions.lit(None).cast("string")) manifest = {"output_count": 2 if violation == "count" else 1, "request_digest": "unused"} with pytest.raises(ValueError, match="Output"): publish_replace_period(h.spark, output, h.spec, manifest=manifest, admission=h.lock) @@ -321,7 +321,7 @@ def reject_unpersist(frame, *args, **kwargs): rows = h.spark.table(h.target).orderBy("id").collect() assert [row.id for row in rows] == [1, 2, 9] assert [row.prediction for row in rows] == pytest.approx([2.0, 4.0, 99.0]) - assert rows[-1]["__skyulf_run_id"] == "prior" + assert rows[-1]["run_id"] == "prior" assert first.input_count == first.output_count == 2 assert first.commit_version == replay.commit_version == 1 assert first.replayed is False diff --git a/skyulf-core/tests/integrations/test_local_delta_publish.py b/skyulf-core/tests/integrations/test_local_delta_publish.py index 49a29efdb..da1630248 100644 --- a/skyulf-core/tests/integrations/test_local_delta_publish.py +++ b/skyulf-core/tests/integrations/test_local_delta_publish.py @@ -40,8 +40,8 @@ def local_delta_case(delta_spark, tmp_path): ).write.format("delta").saveAsTable(source) spark.createDataFrame( [(9, datetime(2025, 12, 1, tzinfo=UTC), 99.0, "prior", "risk", "1")], - "id long, event_time timestamp, prediction double, __skyulf_run_id string, " - "__skyulf_model_name string, __skyulf_model_version string", + "id long, event_time timestamp, prediction double, run_id string, " + "model_name string, model_version string", ).write.format("delta").saveAsTable(target) values = np.arange(20, dtype="float64") data = pd.DataFrame({"x": values, "target": 2.0 * values}) @@ -135,7 +135,7 @@ def test_local_predictions_publish_two_months_and_replay(local_delta_case): second = run_local_batch(spark, february, prepared_february, next_request, admission=admission) replay = run_local_batch(spark, february, prepared_february, next_request, admission=admission) rows = spark.table(target).orderBy("id").collect() - assert [(row.id, round(row.prediction), row["__skyulf_run_id"]) for row in rows] == [ + assert [(row.id, round(row.prediction), row["run_id"]) for row in rows] == [ (1, 4, "january-local"), (2, 8, "january-local"), (3, 12, "february-local"), @@ -291,8 +291,8 @@ def test_incremental_local_batch_discovers_appends_without_period_inputs(local_d assert [(row.id, round(row.prediction)) for row in rows] == [(1, 4), (2, 8), (3, 12)] assert first.input_count == 2 and second.input_count == 1 assert replay.input_count == 0 and replay.noop - assert rows[0]["__skyulf_run_id"] == rows[1]["__skyulf_run_id"] - assert rows[2]["__skyulf_run_id"] != rows[1]["__skyulf_run_id"] + assert rows[0]["run_id"] == rows[1]["run_id"] + assert rows[2]["run_id"] != rows[1]["run_id"] def test_incremental_local_batch_does_not_require_a_date_column(local_delta_case): @@ -308,8 +308,7 @@ def test_incremental_local_batch_does_not_require_a_date_column(local_delta_case ).saveAsTable(source) spark.createDataFrame( [], - "id long, prediction double, __skyulf_run_id string, " - "__skyulf_model_name string, __skyulf_model_version string", + "id long, prediction double, run_id string, model_name string, model_version string", ).write.format("delta").saveAsTable(target) config = prepared.config.model_copy( update={ From 326e1e358aecf95919f24792cfb4668df6059084 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 20:28:38 +0300 Subject: [PATCH 37/85] feat: compare pinned MLflow candidate and champion models Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 4 + docs/user_guide/mlflow_registry.md | 44 ++ .../03-mlflow-batch-delivery-plan.md | 4 + .../04-databricks-integration-plan.md | 42 +- .../spark_and_mlflow/05-sm20-bundle-plan.md | 20 +- .../06-prebundle-model-lifecycle-plan.md | 78 ++++ .../16-sm22a-local-validation-report.md | 40 ++ initiatives/spark_and_mlflow/HANDOFF.md | 15 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 346 ++-------------- .../OPEN_QUEUE_tamamlanmakaydi.md | 299 ++++++++++++++ .../skyulf/inference/local_evaluation.py | 60 +++ .../integrations/databricks/local_batch.py | 55 +-- .../skyulf/integrations/mlflow/validation.py | 247 ++++++++++++ .../integrations/test_mlflow_validation.py | 380 ++++++++++++++++++ 14 files changed, 1237 insertions(+), 397 deletions(-) create mode 100644 initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md create mode 100644 initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md create mode 100644 skyulf-core/skyulf/inference/local_evaluation.py create mode 100644 skyulf-core/skyulf/integrations/mlflow/validation.py create mode 100644 skyulf-core/tests/integrations/test_mlflow_validation.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 74bb007b4..3682cfd02 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -28,6 +28,10 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added +- Read-only local MLflow candidate/champion comparison on one bounded labeled holdout + reports pinned model/data identities, held-out metrics, improvement and a + directional quality gate. It never moves an alias; controlled promotion and + label-aware retraining remain separate pre-Bundle tasks. - Local-engine Databricks SDK configuration and preflight for bounded pandas/Polars batches. It selects trusted local or portable artifacts, resolves MLflow aliases once to concrete versions, checks metadata and diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 35dcd8212..6cd8a7d3c 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -91,6 +91,50 @@ bundle = load_registered_bundle( assert bundle.semantic_digest == resolved.digest ``` +## Compare a local challenger before promotion + +For a fitted pandas/Polars pipeline, resolve both registered versions to +concrete identities and evaluate them on the **same held-out labeled rows**. +Pin the source snapshot and split in the caller; `dataset_id` records that +identity in the report but does not verify the underlying table by itself. +The report also records the running Skyulf Core version and both model digests. +The comparison uses the saved FE, model, class order and tuned thresholds. +It accepts a row/memory budget and rejects incompatible tasks or class labels. + +```python +from skyulf.integrations.mlflow.registry import resolve_model +from skyulf.integrations.mlflow.validation import compare_registered_local_models + +candidate = resolve_model( + "catalog.schema.customer_risk", version="2", registry_uri="databricks-uc" +) +champion = resolve_model( + "catalog.schema.customer_risk", alias="champion", registry_uri="databricks-uc" +) +report = compare_registered_local_models( + candidate, + champion, + heldout, # bounded pandas or Polars frame with raw inputs and true labels + target_column="target", + dataset_id="catalog.schema.labels@version=42/split=holdout-v1", + metric="heldout_rmse", + min_improvement=0.1, + quality_threshold=5.0, # maximum acceptable RMSE + max_rows=10_000, + max_bytes=20_000_000, + registry_uri="databricks-uc", +) +print(report.eligible, report.reason, report.candidate_metrics) +``` + +For MAE/RMSE a lower value wins; for R2, accuracy and F1 a higher value +wins. `quality_threshold` is an upper limit for error metrics and a lower +limit for score metrics. A tie does not qualify. If no champion exists, pass +`None` and inspect the candidate report; this never creates a champion. +Evaluation does not move aliases, publish predictions or deploy endpoints. +Explicit version-checked promotion and rollback are the next SM-22b task; +monthly candidate training follows in SM-28a before Bundle generation. + Only load trusted registry artifacts: bundle loading deserializes pickle, and digest matching is an identity check, not authentication of an unknown producer. Missing bundle metadata/artifacts or mismatched digests fail explicitly. A later diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index 3870668b7..d5c0b949a 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -408,6 +408,10 @@ follow the first working local Bundle. This planning update starts no deployment ### SM-22 - Validation and controlled promotion +Current order: SM-22a comparison and SM-22b promotion/rollback precede +SM-28a candidate retraining and the first local Bundle. SM-28b later wires +an optional schedule. See [the lifecycle plan](06-prebundle-model-lifecycle-plan.md). + - [ ] Candidate/champion evaluation reports using existing Skyulf metrics and model output contracts; configured minimum quality and regression thresholds. - [ ] Explicit version-pinned promotion, rollback and audit metadata. Evaluating diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md index af8f4bb80..110d96b93 100644 --- a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -71,16 +71,19 @@ UC publication and Bundle claims need their own cloud evidence. | 3 | SM-24a: local training and bounded batch prediction | SM-25 | DONE | | 4 | SM-15L: local prediction -> UC Delta monthly publication | SM-24a | DONE | | 5 | SM-15I: automatic incremental local scoring | SM-15L | DONE | -| 6 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; SM-15I | READY | +| 6 | SM-22a/b: candidate/champion comparison and controlled promotion | Current evaluation/registry | ACTIVE | +| 7 | SM-28a: label-aware candidate retraining service | SM-22a/b; SM-24a | WAIT | +| 8 | SM-20a: first pandas/Polars Databricks Bundle/template | SM-24a; SM-15I; SM-22b; SM-28a | WAIT | +| After first Bundle | SM-28b: optional monthly schedule wiring | SM-20a; SM-28a | LATER | | After first Bundle | SM-27: bounded full-history rescore and selectable Bundle mode | SM-20a; SM-15L | LATER | -| After first Bundle | SM-22 then SM-28: validation/promotion and optional monthly retraining | SM-20a; SM-22 for SM-28 | LATER | | Later | SM-24b, SM-19, SM-21, SM-23: optional Jobs API, serving, feature lookup and monitoring | Relevant local adapters | LATER | | After local Bundle | SM-24c and SM-17: Spark workflow then broader Spark coverage | SM-20a | LATER | | After selected Spark gates | SM-20b: add tested Spark option to the Bundle | SM-24c; relevant SM-17 slices | LATER | -The first Bundle needs a working, bounded local input and verified -automatic new-row UC output; it does not need model promotion, online lookup, HTTP, SQL, A/B, -Canvas, or Spark FE/model execution. Spark may handle UC table I/O only. +The first Bundle needs bounded local input, verified automatic new-row UC +output and the already-tested lifecycle services. Its promotion job is an +explicit operation, never an automatic result of evaluation. Online lookup, +HTTP, SQL, A/B, Canvas and Spark FE/model execution remain outside SM-20a. Spark may handle UC table I/O only. The local-first follow-ups add full-history rescore and optional monthly retraining before broad Spark inference expansion. @@ -245,11 +248,12 @@ Acceptance: request generation is offline; scoped live tests validate submitted parameters, runtime dependencies and identity. No notifications are sent by merely configuring them. This task is not a gate for SM-20a. -## Optional local/platform additions after the first Bundle +## Model lifecycle before the first Bundle -SM-22, SM-19, SM-21 and SM-23 can extend a generated project after SM-20a. -They are not prerequisites for the first local training and monthly batch -Bundle. Endpoint and `ai_query` work do not require Spark; feature-table +SM-22a/b and SM-28a are prerequisites for SM-20a. They implement validation, +explicit promotion/rollback and label-aware candidate training as reusable +services. SM-28b wires an optional schedule after the Bundle exists. SM-19, +SM-21 and SM-23 remain later platform additions. Endpoint and `ai_query` work do not require Spark; feature-table adapters must declare any Spark dependency rather than pulling it into the first local path. The tasks below remain open with their own acceptance gates. @@ -264,7 +268,10 @@ reuse Skyulf evaluation and explicit MLflow clients rather than duplicate metric - [ ] Produce a comparison report with model/data/code identities and reasons; evaluation alone must not mutate aliases or endpoints. - [ ] SM-22b: separate explicit promotion/rollback operations, recording prior and - requested versions. Detect conflicting state instead of overwriting silently. + requested versions. Require shared alias admission and restricted registry writers; re-read + the expected prior version under admission before mutation. The MLflow/UC + alias APIs do not expose compare-and-swap, so external bypass writers + remain outside this guarantee. - [ ] Test first-model behavior without automatic first-champion promotion. Acceptance: deterministic report fixture, real registry alias/version tests, @@ -291,12 +298,13 @@ scheduled run must never trigger a full rescore because an alias moved. runs leave month one unchanged; an explicit full rebuild creates a complete second generation; failed validation leaves the first active. -## SM-28 - Monthly retraining and challenger workflow +## SM-28a/b - Monthly retraining and challenger workflow The reference project wires feature engineering, training, validation and -inference jobs, but its sample inference schedule is commented out. Monthly -retraining is therefore an explicit Skyulf follow-up, not inherited behavior. -It is independent of `period_update` and `full_rebuild` scoring choices. +inference jobs, but its sample inference schedule is commented out. SM-28a +implements the label-aware training and challenger comparison before the +Bundle. SM-28b later wires an opt-in schedule. Both are independent of +`period_update` and `full_rebuild` scoring choices. - [ ] Provide an opt-in monthly schedule with business timezone, label availability cutoff, pinned training snapshot and reproducible temporal @@ -372,7 +380,7 @@ no requirement to move existing core metrics into Databricks-specific code. ## SM-20a - First local Databricks Bundle and project template This is the first deployable milestone after SM-26, SM-25, SM-24a, -SM-15L and SM-15I. +SM-15L, SM-15I, SM-22a/b and SM-28a. Generate a project using tested local services, with a `databricks.yml` in the generated project root, job resources, thin Python entry points, pinned package dependencies, dev/prod targets and a short README. Do not add a YAML file to @@ -382,7 +390,9 @@ source/target, schedule and limits; credentials remain in Databricks authentication or secrets, never generated source. Tracking-off or registry-off Bundle variants require a separately tested durable artifact handoff. -- [ ] Generate local training and automatic incremental batch jobs. Pin +- [ ] Package separate local training, comparison, explicit promotion and + automatic incremental batch jobs. Promotion remains opt-in and cannot + follow evaluation automatically. Pin model selection in configuration; derive source versions from committed receipts. Scheduled runs require no manual period or source-version input. Serverless Python script/wheel tasks declare their required environment key diff --git a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md index ab5f6ed69..0315b28a9 100644 --- a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md +++ b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md @@ -70,20 +70,32 @@ The SQL Connector is an alternative, not a required part of the first Bundle. watermark. The current `replaceWhere` path cannot accept only new rows when they overlap a previously written period. +6. SM-22a/b produce a read-only candidate/champion comparison and separate, + version-checked promotion/rollback operations. +7. SM-28a trains and registers a label-aware candidate from a pinned snapshot, + then compares it without automatic promotion. The optional monthly schedule + is wired in SM-28b after the Bundle exists. + The custom template should generate a project with these responsibilities: ```text templates/databricks/databricks_template_schema.json templates/databricks/template/{{.project_name}}/databricks.yml.tmpl templates/databricks/template/{{.project_name}}/resources/train_job.yml.tmpl +templates/databricks/template/{{.project_name}}/resources/compare_job.yml.tmpl +templates/databricks/template/{{.project_name}}/resources/promote_job.yml.tmpl templates/databricks/template/{{.project_name}}/resources/batch_job.yml.tmpl templates/databricks/template/{{.project_name}}/src/train.py.tmpl +templates/databricks/template/{{.project_name}}/src/compare.py.tmpl +templates/databricks/template/{{.project_name}}/src/promote.py.tmpl templates/databricks/template/{{.project_name}}/src/score_month.py.tmpl templates/databricks/template/{{.project_name}}/README.md.tmpl ``` The generated Python files call Skyulf services; they do not copy FE, model, -MLflow or Delta publication implementations. The first verified cross-job +MLflow, comparison, promotion or Delta publication implementations. Separate +train, compare, explicit-promote and score jobs preserve the decision boundary. +The first verified cross-job artifact path uses MLflow and a concrete UC model version. Tracking-off and registry-off variants need their own durable artifact-handoff test before they are offered. Configuration includes source/target table names, a globally @@ -138,9 +150,9 @@ rescores using later information must be labeled as current-state results. SM-27 adds a separate rehearsal: rescore all four rows into a new generation, activate it, and verify rollback. -SM-28 separately adds optional monthly retraining after labels are available. -It trains a candidate, uses SM-22 to compare against a pinned champion, and -requires explicit promotion. The scoring job pins the chosen concrete model +SM-28a adds label-aware candidate training and uses SM-22a/b before the +Bundle is generated. SM-28b later wires its optional monthly schedule. +Comparison never promotes implicitly. The scoring job pins the chosen concrete model version once per run. A new champion does not retroactively alter previous months; `full_rebuild` remains a separate request. diff --git a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md new file mode 100644 index 000000000..b2b57e4f9 --- /dev/null +++ b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md @@ -0,0 +1,78 @@ +# Pre-Bundle Model Lifecycle Implementation Plan + +> For agentic workers: execute the tasks in order, using a failing test before each behavior change. + +**Goal:** Complete candidate/champion validation, explicit promotion, and a reproducible local-engine retraining workflow before generating the first Databricks Bundle. + +**Architecture:** Skyulf Core owns engine-neutral held-out metrics; the optional MLflow adapter owns registered-version loading and the comparison policy. Alias changes remain a separate operation. Databricks jobs later call these services; the Bundle packages and schedules them without copying model lifecycle logic. + +**Tech stack:** Python, pandas/Polars, Skyulf fitted local pipeline, MLflow registry, pytest. No new frontend/backend dependency. + +**Spec:** [Databricks integration plan](04-databricks-integration-plan.md), SM-22 and SM-28 sections. + +## Global constraints + +- Compare concrete candidate and champion versions on the same bounded, labeled evaluation frame and record its caller-pinned source/split identity. +- Preserve the model's saved feature engineering, class order and tuned thresholds. Reject incompatible task or class contracts. +- Report evaluation only; never move an alias, deploy an endpoint, or write predictions as a side effect. +- Promotion and rollback are explicit, version-checked operations with a durable prior/new-version receipt. A missing champion is not auto-initialized. +- Monthly retraining must pin source version, label cutoff and temporal holdout before fit. Bundle scheduling is a later integration step. + +### Task 1: SM-22a comparison report + +**Files:** `skyulf-core/skyulf/integrations/mlflow/validation.py`; focused integration tests; MLflow user guide. + +**Interface:** Compare two `ResolvedModel` references with a bounded pandas/Polars holdout, a target column, source/split identity, chosen metric and minimum improvement. Return model identities, both metric maps, comparison decision and reason. + +- [x] Write failing tests for same-frame candidate/champion parity, regression and classification metric direction, pandas/Polars, missing champion, incompatible models and invalid inputs. +- [x] Load concrete registered local artifacts through the existing registry adapter and reuse `evaluate_local_holdout`. +- [x] Keep report creation read-only and deterministic; test that no MLflow alias changes. +- [x] Run focused tests, Ruff, ty and the existing local MLflow/holdout suites. + +Local implementation and tests are complete; the isolated Unity Catalog gate is still pending. + +## Alias concurrency decision + +The [MLflow alias client](https://mlflow.org/docs/latest/api_reference/python_api/mlflow.client.html) +accepts model name, alias and new version, while the +[Unity Catalog alias PUT API](https://docs.databricks.com/api/uc-registered-models/v1/model-alias) +takes a new version number without an expected prior version. **Inference from +those API contracts:** read-then-set alone is not compare-and-swap and cannot +prevent a concurrent alias overwrite. SM-22b therefore requires one shared +non-expiring admission authority for every participating alias writer, plus +registry write permissions restricted to that controlled path. Re-read the +alias under admission, verify the expected prior version, mutate explicitly, +then verify and record the result. Writers bypassing that authority remain an +operational limitation and must not be described as race-safe. + +### Task 2: SM-22b controlled promotion and rollback + +**Files:** MLflow registry adapter; focused registry tests; registry guide. + +**Interface:** Accept an approved comparison report, expected champion version and candidate version. Re-read the alias immediately before mutation, reject conflicts, set the alias explicitly and return a prior/new-version receipt. Rollback uses that receipt and an expected current version. + +The promotion path must revalidate the pinned model identities and decision; an in-memory comparison report is not an authorization token and its metric dictionaries can be changed by a caller. + +- [ ] Write failing tests for normal promotion, stale alias, missing champion, access denial, no implicit first champion and rollback conflicts. +- [ ] Implement explicit version-checked operations without changing the tracking run or inference code path. +- [ ] Verify with a disposable local MLflow registry; perform isolated UC permission/conflict validation before marking SM-22b done. + +### Task 3: SM-28a label-aware retraining workflow + +**Files:** local Databricks workflow adapter; focused temporal-split tests; MLflow guide. + +**Interface:** Consume a caller-pinned bounded source snapshot, label availability cutoff and temporal holdout; fit with Skyulf, log metrics/artifact, register a candidate, then call SM-22a. Do not promote automatically. + +- [ ] Write failing tests for late labels, leakage across cutoff, reproducible split, failed candidate and unchanged champion. +- [ ] Reuse current fitted artifact packaging and registry publication; store source/code/model/evaluation identities. +- [ ] Run a small isolated Databricks validation after local tests pass, without touching production aliases. + +### Task 4: SM-20a Bundle integration + +**Files:** generated project and job resources in the SM-20 plan. + +- [ ] Package the verified train/compare/promote/score services into separate jobs with explicit dependencies and permissions. +- [ ] Keep automatic incremental scoring as the default and pin the selected champion once per scoring run. +- [ ] Validate, deploy and run the two-insert rehearsal; add an opt-in retraining schedule only after the standalone SM-28a workflow passes. + +SM-27 full-history rescore, Spark expansion, live endpoints and `ai_query` remain later independent work. diff --git a/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md b/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md new file mode 100644 index 000000000..ef0f01e41 --- /dev/null +++ b/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md @@ -0,0 +1,40 @@ +# SM-22a local candidate/champion validation + +Status: LOCAL VERIFIED, 2026-09-23. Unity Catalog comparison remains to be +validated before closing the platform gate. No Bundle or alias mutation was run. + +## Delivered + +- `compare_registered_local_models` consumes concrete `ResolvedModel` + versions and their checked local pipeline digests. It scores both versions on + the same bounded pandas/Polars labeled frame and reports dataset ID, row count, + model and code identities, metrics, improvement, quality threshold and decision reason. +- RMSE/MAE minimize; R2, accuracy and F1 maximize. Ties cannot qualify. A + missing champion yields a candidate report without implicit initialization. + Task and class-label contracts must agree; non-finite metrics fail closed. +- Held-out metric calculation moved from the Databricks adapter to a shared + inference module. The old Databricks import remains available for callers. + +## Evidence + +The isolated MLflow 3.16.1 environment passed 25 focused tests with one +optional Spark skip. The tests cover pandas regression, Polars classification, +minimum-improvement and absolute quality gates, malformed references, access denial and +a real local SQLite MLflow registry with two registered local pipeline +versions. The comparison left the champion alias on version 1. Ruff, ty and +strict MkDocs passed for the changed scope. + +The caller supplies `dataset_id` after pinning the source snapshot and +evaluation split. The comparison records that identifier but does not verify +the external table snapshot or write the report to a run. It produces a +read-only report, not a promotion authorization. + +## Next + +SM-22b adds explicit alias promotion/rollback with shared admission, restricted +writer permissions, expected-version checks and durable receipts. The +[MLflow client](https://mlflow.org/docs/latest/api_reference/python_api/mlflow.client.html) +and [Unity Catalog alias API](https://docs.databricks.com/api/uc-registered-models/v1/model-alias) +do not expose an expected-prior-version parameter for alias writes; this is +why a read-then-set check alone cannot guarantee race safety. SM-28a then +adds label-aware challenger training before SM-20a packages these services. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index a66c85a21..c6265c68e 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -8,14 +8,20 @@ values for recurring jobs. SM-15I now provides automatic new-row scoring for the first small-data pandas/Polars Databricks Bundle (SM-20a). Spark handles table I/O; Spark FE/model execution follows the Bundle. SM-18 and streaming remain parked.** -After the first Bundle, SM-27 adds explicit full-history rescore and -SM-22/SM-28 add optional monthly retraining with controlled candidate/champion -promotion. Target release: 0.9.0. Branch: `090`. +The revised order completes SM-22a/b comparison and controlled promotion, +then SM-28a label-aware challenger training before SM-20a. SM-28b adds the +optional monthly schedule after the Bundle; SM-27 remains later. Target release: 0.9.0. Branch: `090`. + +SM-22a now has a locally verified, read-only comparison API; see +[its report](16-sm22a-local-validation-report.md). The isolated UC gate is +pending, and SM-22b has not started. Alias writes lack native compare-and-swap, +so SM-22b needs shared admission and restricted writers before promotion. ## Starting point - SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25 and SM-26 are complete. - Start SM-20a from [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md). + Start SM-22a from [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). + SM-20a follows the verified SM-22a/b and SM-28a services. SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. A later [real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) @@ -110,6 +116,7 @@ Databricks training job: pandas/Polars FE + sklearn model -> Databricks scoring job: pandas/Polars local batch on bounded data -> Spark reads bounded UC source changes and publishes UC Delta predictions (SM-15I automatic incremental path) + -> Compare candidate/champion, promote explicitly, train challenger (SM-22a/b, SM-28a) -> Generate and run the first local-engine Bundle (SM-20a) ``` diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 2a62143ae..0236a6bda 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,13 +1,15 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-20a next. Target: 0.9.0.** -First deliverable: pandas/Polars training and local batch on Databricks, then a -working local-engine Bundle. Spark expansion follows that Bundle. SM-15L +Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a active before SM-20a. Target: 0.9.0.** +Next deliverable: candidate/champion validation, controlled promotion and +label-aware retraining services, then a working local-engine Bundle. Spark +expansion follows that Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the separate SM-20 Bundle plan](05-sm20-bundle-plan.md) before starting SM-20a. +and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-22a. +The [SM-20 Bundle plan](05-sm20-bundle-plan.md) remains the packaging gate. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). SM-26 added a local MLflow package; SM-15L and SM-15I validated UC writers. @@ -44,28 +46,30 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | | SM-25 | Local-first config / SDK preflight | SM-26 | DONE | Immutable local config; pinned artifact load, bounded frame and actionable preflight; no node/model allowlist | | SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | -| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I | READY | Generate, validate, deploy and run pandas/Polars train/automatic incremental batch with pinned MLflow/UC model | +| SM-22a | Pinned candidate/champion validation | Current evaluation/registry | ACTIVE | Local comparison/report passed; isolated UC gate pending; [evidence](16-sm22a-local-validation-report.md) | +| SM-22b | Explicit promotion and rollback | SM-22a | WAIT | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests | +| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-24a | WAIT | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | +| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-28a | WAIT | Package tested train/compare/promote/incremental-score services; validate, deploy and run | +| SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | WAIT | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | -| SM-22 | Optional model validation and controlled promotion | SM-20a, current evaluation/registry | LATER | Pinned candidate/champion comparison, explicit version promotion and rollback | | SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | LATER | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | -| SM-28 | Monthly retraining and challenger workflow | SM-20a, SM-22 | LATER | Label-aware schedule, leakage-safe training, candidate/champion report, explicit promotion, and independent pinned scoring job | | SM-19 | Optional live HTTP / SQL ai_query / endpoint operations | SM-20a, compatible pyfunc package | LATER | Add only after serving parity; streaming remains parked | | SM-21 | Optional Databricks feature tables / online lookup | SM-20a; SM-19a for online serving | LATER | Point-in-time lookups and optional online freshness; declare any Spark dependency | | SM-23 | Optional monitoring and inference observability | SM-20a, relevant batch/serving adapter | LATER | Existing Skyulf metrics + optional Databricks monitoring/inference tables | | SM-24c | Spark batch workflow adapter | SM-20a, existing Spark sink | LATER | Expose tested Spark runner after first local Bundle | | SM-20b | Spark Bundle enhancement | SM-24c, selected SM-17 slices | LATER | Add tested Spark engine choice while preserving local variant | -IDs remain stable; suffixes distinguish the first local Bundle from its later -Spark extension. SM-27 and SM-28 add the selectable full-rescore and scheduled -retraining workflows after the first Bundle; neither blocks SM-20a. Endpoint, -feature lookup and monitoring work also remain optional. Prefer completing the -local Bundle extensions before broad Spark expansion. +SM-22a/b and SM-28a are now prerequisites for the first Bundle. SM-28b only +wires their optional monthly schedule after the Bundle exists. SM-27 remains +post-Bundle and independent. Endpoint, feature lookup and monitoring remain +optional; broad Spark expansion follows the local Bundle. ## Local-first path to the first Bundle These tasks were identified in the reference review; the latest user direction -moves the first local Bundle before Spark and other optional integrations. +moves the model lifecycle services before the first local Bundle. Spark and +other optional integrations follow the Bundle. Full task scope, proposed code areas, reference sources and acceptance checks are in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). @@ -79,14 +83,17 @@ in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). 5. **SM-15I:** add automatic first-snapshot and later new-row scoring with a committed source-version receipt and append-safe output. See the [incremental plan](12-sm15i-incremental-scoring-plan.md). -6. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle +6. **SM-22a/b:** compare concrete candidate/champion versions on one labeled + holdout, then provide separate explicit promotion and rollback. +7. **SM-28a:** train a candidate from a pinned, label-aware snapshot and + temporal holdout; compare it without automatic promotion. +8. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle using the [two-run rehearsal](05-sm20-bundle-plan.md) without manual dates - or source versions. -7. **After SM-20a:** SM-27 adds explicit `full_rebuild` alongside the default - `incremental_append`; SM-15L's `period_update` remains an explicit backfill. - SM-22 then SM-28 add candidate/champion validation and - optional monthly retraining. These are separate from monthly scoring. -8. **Later:** optional SM-24b/24d/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. + or source versions. Package the already-tested lifecycle services. +9. **After SM-20a:** SM-28b wires optional monthly retraining; SM-27 adds + explicit `full_rebuild` alongside default `incremental_append`. SM-15L's + `period_update` remains an explicit backfill. +10. **Later:** optional SM-24b/24d/19/21/23 adapters; Spark SM-24c/SM-17, then SM-20b Bundle enhancement. SM-26 is the explicit packaging task added after the local-first MLflow discussion. It reuses the fitted local pipeline rather than requiring every FE node to gain a @@ -153,305 +160,6 @@ SM-17 requires the full tracked scope above. Some algorithms may need an explici alternative backend rather than an equivalent native Spark implementation; that decision must not hide missing support. SM-19 streaming remains optional and parked. -## SM-15I - automatic new-row scoring, DONE - -The user requires scheduled jobs to discover new source rows automatically. -The first run must score the existing bounded snapshot; later runs must score -only inserts since the last successful target commit, including late-arriving -rows in an earlier calendar period. The current `replaceWhere` writer cannot -publish only new rows in an overlapping period without deleting older -predictions. Implement a separate append-safe publisher and derive the source -watermark from the committed output receipt. See the -[SM-15I plan](12-sm15i-incremental-scoring-plan.md). This is a prerequisite -for SM-20a. The runner passed local real-Delta gates and the isolated two-job Databricks -rehearsal, including a source with no date column; see the -[SM-15I validation report](13-sm15i-live-validation-report.md). A separate -[real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) trained a Skyulf -pipeline with MLflow metrics and registered UC model version 1, then passed -200 initial + 100 later real-row predictions with an unchanged prior batch and -no-op replay. SM-20a remains the next task. - -## SM-15L - 2026-09-23 monthly local UC Delta publication, DONE - -- Added `run_local_batch` with truthful `local_pipeline` publication mode. - It loads one pinned UC source month under row/byte limits, scores through - fitted pandas or Polars FE/model code, converts only final keyed results to - an explicitly typed Spark DataFrame, and reuses guarded Delta period writes. - The target and admission control table are provisioned separately. -- Focused SDK/reader tests: **32 passed, 1 optional Spark skip**; batch - contracts: **25 passed**. Real local Spark/Delta: **6 passed**, including - two months, exact replay, stale version, accidental empty period, admission - denial, invalid target schema and stale model/source pins without mutation. Ruff, Ty and strict - MkDocs passed for the changed scope. -- Two isolated Databricks serverless jobs completed **SUCCESS**. January - published 80 pandas predictions to target version 1. February appended 80 - source rows, published 80 Polars predictions to target version 2, preserved - all January rows/metadata, replayed without a new commit, and rejected a - stale logical request. Both periods matched direct local gold by key. - See the [SM-15L live report](11-sm15l-live-validation-report.md) for run IDs, - model digests, test resources and scope limits. The date/version choices - were scripted for this proof; automatic new-row scoring is SM-15I. - -## SM-24a — 2026-09-23 local and Databricks validation, DONE - -- Added explicit bounded pandas/Polars training and a pinned UC Delta monthly - reader. Spark filters/projects/limits the source; saved local FE/model runs in - one Python process. This stage returns predictions and diagnostics, not a - Delta prediction table. The [local guide](../../docs/user_guide/databricks_local_sdk.md) - includes code and the decoded-byte boundary. -- Five pandas/Polars model packages trained and registered in isolated schema - `workspace.skyulf_sm24a_20260923`; an independent serverless scoring job - matched both 80-row months by key. Replay and negative cases passed. All 30 - additional inference-eligible preprocessing registrations passed on both - engines in a separate live audit, making 41 live-evidenced eligible IDs in - the [62-ID matrix](07-sm24a-node-matrix.csv). Train-only, inspection, - optional and unsupported IDs remain explicit. -- An unknown registry version failed preflight. A disposable alias moved to - R1 version 2 after preparation; the prepared predictor remained on version 1 - and returned the expected 80 rows. The alias was deleted. The full - [report](08-sm24a-live-validation-report.md) lists runs, versions, resources - and test results. -- A follow-up [scaler and outlier audit](09-sm24a-scaler-outlier-audit.md) - registered 10 pandas/Polars MLflow models with held-out metrics and passed - a separate two-month scoring replay. Four filtering outlier nodes reject - shortened prediction batches; Winsorize clips and preserves rows. -- A [200-row held-out metrics audit](10-sm24a-heldout-metrics-report.md) - logged regression MAE/RMSE/R2 and classification accuracy/F1 in the same - MLflow runs as five new test models. All five registered versions passed a - separate two-month scoring replay. R2/R3 had negative held-out R2; those - example models are not approved for production promotion. -- The Spark iterator does not expose actual wire-byte counts. `max_bytes` - bounds accepted decoded rows and local-frame memory; a very wide row can - arrive before rejection. [SM-24d](OPEN_QUEUE.md) retains the stronger - transport-budget option for wider or larger workloads. SM-15I then added - automatic new-row scoring; next is SM-20a. - -## SM-25 — 2026-09-23 local SDK validation, DONE - -- Added frozen `LocalWorkflowConfig` with explicit runtime, pandas/Polars engine, - bounded caller frame or declared future UC source, local/portable artifact - selection, optional MLflow store URIs and return/declared future Delta sink. - Config parsing performs no remote call and rejects embedded URI credentials. -- Local preflight reports actionable config, source, sink, artifact, engine, - node-contract and model-contract issues. Optional read-only registry preparation - resolves an alias once, loads the concrete version, and checks package digest. - The SDK has no separate FE/model allowlist; a fitted SkyulfPipeline controls - local prediction. An optional representative-frame probe exercises that - actual path before submission. Inference input is capped by rows and bytes. -- After the allowlist correction, **20 local SDK tests passed**, including - pandas/Polars MinMaxScaler + random-forest replay. The combined isolated - MLflow SDK, local-package and registry gate passed **39/39**. - The broader Core unit run completed **3927 passed, 71 skipped** before that - narrow correction; Ruff, repository Ty and strict MkDocs passed after it. No - Databricks job, UC source adapter or Delta writer was added in SM-25. -- [Local-engine SDK guide](../../docs/user_guide/databricks_local_sdk.md). - Next: SM-24a local training and bounded batch workflow. - -## SM-26 — 2026-09-23 local packaging validation, DONE - -- Added a versioned, trusted local pipeline artifact with recorded pandas/Polars - fit engine, raw/model feature schemas, model class, exact dependency versions, - payload checksum, classification classes and explicit tuned-threshold choice. - Legacy pipeline pickles still load; those without a recorded engine require a - refit before local MLflow packaging. -- Added MLflow pyfunc packaging and a synthetic input example/signature for the - supported scalar inputs. Its pandas boundary converts back to the recorded - Polars engine when needed. Whole-frame local is the only declared execution - scope; HTTP row-local and Spark scopes are rejected. Existing explicit registry - publication and pinned-version resolution now carry the local payload digest. -- Isolated MLflow 3.16.1 integration: **16 local artifact/pyfunc tests passed** - for categorical encoding, binning, null input, classes/probabilities, tuned - thresholds, cross-engine requests, and a fresh isolated Python subprocess - load. The 0.9.0 wheel was built from the changed source and installed into the - isolated environment; `python -I` resolved the new module from site-packages. - Existing MLflow packaging and registry compatibility: **47 passed, 1 skipped**. - Pipeline unit regression: **385 passed, 2 skipped**. Focused Ruff and ty checks - passed. No Databricks job or Delta writer was added in this task. -- [MLflow model guide](../../docs/user_guide/mlflow_models.md) lists the tested - model families and the wheel, serving and Spark limits. This task handed off - to SM-25 and then SM-24a. - -## SM-16 — 2026-09-22 local and live validation, DONE - -- Baseline `d43e74ca`. Added a trusted pinned registry-bundle loader and a - templates-free `databricks_batch_smoke.py` probe with pandas/Polars training, - an independent numerical oracle and both existing Spark inference modes. -- Combined local registry/worker gate: **29 passed**, no skips, MLflow 3.16.1 / - PySpark 4.0.3 / Python 3.12.3. Base regression: **77 passed, 28 optional skips**. - Ruff/format, repository Ty and strict MkDocs passed. Wheel built locally; - checksum, exact commands and remaining gates are in - [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). -- Databricks CLI **1.17.0**, profile `skyulf`, approved isolated schema - `workspace.skyulf_sm16_20260922`. Live regression parity passed both Spark - modes in run `447606109645160`; restricted-principal model allow/deny and - 10k/50k synthetic parity passed in run `2921374308246`. -- Checkpoint `311547fc` adds serverless identifier handling and shared Delta - admission. Local gates passed 75 inference tests and 18 admission/batch tests. - The reusable monthly Delta probe passed 5 real Delta tests; live Delta/alias - run `810044894558535` reached an unsupported `REFRESH TABLE` command. - Narrow refresh/cache compatibility fixes passed 48 real Delta tests; corrected - run `783094949884769` passed monthly replacement/replay, alias pinning and - full worker package-content checks. `databricks.yml` remains absent. -- SM-16 is **DONE** for the selected serverless workflow: winner job - `973709879452231` committed only after the contender verified held-owner - rejection. Contender `404334394214907` then failed a test-only permission-code - assertion; final restricted job `977447944071613` passed actual MODIFY denial, - unchanged data/version and owner release. The failed run remains documented. -- SM-15L was deferred immediately after SM-16; the later local-first Bundle - request reopens it after SM-24a. No implementation of that local sink is - included in SM-16, and real UC access remains an acceptance requirement. - -## SM-15 — 2026-09-22 validation record - -- Baseline `4a613cb5`; branch `090`. The delivery commit containing this record - adds `skyulf.integrations.databricks`, three batch test modules and a real - Delta fixture, the optional Delta dependency profile/CI lane, and the English - [monthly batch guide](../../docs/user_guide/databricks_batch.md). -- `run_batch` pins a concrete Delta source version and verifies snapshot - availability at the explicit cutoff. Both existing Spark inference modes - feed a precreated Delta target. A committed manifest records request identity, - model digest, installed code version and counts. Source history newer than - `as_of`, mismatched bundle digest/runtime and ambiguous contracts fail. -- Atomic `replaceWhere` preserves other periods. Empty deletion requires opt-in. - Run receipts prevent duplicate publication and prevent an old retry undoing - a newer recomputation. Changed requests under one run ID and stale target - versions fail. Local OS admission locks are tested across processes; both - runner and public sink reject local locks on distributed masters. -- Final required Linux/WSL lane: **43 passed**, including **18 real Delta - integration cases** and **25 contract/admission cases**, no skips, 111.95s. - Python **3.12.3**, PySpark **4.0.3**, Delta Python/JVM **4.0.0**, Java 17; - pandas **2.3.3**, Polars **1.44.2**, Arrow **25.0.1**, sklearn **1.9.1**. - Initial exploratory tests used newer Python-package patch versions; the final - gate was rerun after aligning the environment with `requirements-delta.txt`. -- Cases include a pinned old source after a newer commit, a non-UTC Spark - session, exact period boundaries, null/wrong metadata/count rejection with - target version unchanged, stale/new/old retries and committed empty deletion. - Admission permission denial uses fault injection; it is not live UC evidence. -- Base regression: **105 passed, 26 skipped** with MLflow/Delta absent, plus - existing sklearn interchange and Windows physical-core warnings. Final narrow - Windows contract/admission run: **25 passed**. Ruff check/format, repository - Ty and strict MkDocs passed; the guide's Mermaid parsed with the real parser. - Repository pre-commit hooks passed, including the synchronized optional - dependency lock. GitHub Actions was added but has not run remotely. -- Windows Hadoop filesystem support could not run real Delta I/O, so the - required transaction gate used an isolated Linux/WSL environment. No runtime - authentication or Databricks job was performed. Preserve pre-existing temp - folders and editor-created Databricks configuration outside this commit. -- Remaining scope: the cutoff proves snapshot availability only, not upstream - point-in-time feature joins. Model registry identity is bound by the caller; - bundle digest is checked. Receipt/history retention bounds the retry window. - A shared local lock directory protects cooperative local writers on one host; - distributed admission requires a separate implementation with ownership held - throughout the commit. Expiring leases without sink fencing are unsupported. - These platform concerns and the carried registry-to-Spark gate belong to SM-16. - -Reproducible commands (Linux with Java 17 and an isolated environment): - -```bash -uv venv .venv-delta -uv pip install --python .venv-delta/bin/python -r requirements-delta.txt -SKYULF_REQUIRE_DELTA=1 .venv-delta/bin/python -m pytest \ - skyulf-core/tests/integrations/test_batch_contract.py \ - skyulf-core/tests/integrations/test_batch_admission.py \ - skyulf-core/tests/integrations/test_delta_publish.py -q -o addopts= -``` - -Exact local invocation used the prepared WSL environment and cached official jars: - -```powershell -wsl -d Ubuntu -- bash .cache/sm15-linux-run.sh -m pytest skyulf-core/tests/integrations/test_batch_contract.py skyulf-core/tests/integrations/test_batch_admission.py skyulf-core/tests/integrations/test_delta_publish.py -q -p no:cacheprovider -o addopts= --basetemp /tmp/sm15-delta-pinned-final --tb=short -.venv/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_inference_bundle.py skyulf-core/tests/unit/test_pipeline_inference_schema.py skyulf-core/tests/integrations -q -o addopts= --basetemp .cache/sm15-base-final --tb=short -.venv/Scripts/ty.exe check backend skyulf-core/skyulf skyulf-core/tests run_skyulf.py celery_worker.py -.venv/Scripts/python.exe -m mkdocs build --strict --site-dir .cache/sm15-docs -``` - -The local shell wrapper exports Java 17, its Python worker executable is selected -by the fixture, and `SKYULF_DELTA_JARS` points to the cached Delta 4.0.0 jars. -The portable command above downloads those jars through Delta's normal helper. - -## SM-13 — 2026-09-22 validation record - -- Added optional MLflow `pyfunc` packaging in - `skyulf/integrations/mlflow/model.py`. `log_model` serializes the existing - `InferenceBundle`, records a manifest-derived named signature and synthetic - input example, and uploads the model directory to the explicitly supplied - run ID through `MlflowClient`. `tracking_uri` can be passed when the run was - created by a client-bound tracker; no global active run is used to select the - destination. -- Raw and features bundles preserve local prediction results after MLflow - save/load for pandas and Polars-trained pipelines. Classification tests cover - class order, probabilities and tuned thresholds. Positional NumPy/list input - is rejected. Dtypes without an exact MLflow column representation are rejected - during signature creation rather than silently widened. -- Baseline `67315253`; this delivery commit includes implementation, tests, - English guide and validation records. Python 3.12.10 / MLflow 3.16.1: - **31 passed** (23 model, 8 tracking) with the wheel subprocess gate enabled. - Base bundle/schema/integration regression: **80 passed, 7 skipped** with - existing numeric/protocol warnings. Base tracking/model alone: **4 passed, - 5 skipped**; MLflow is absent. Ruff, repository Ty/pre-commit and strict - MkDocs passed. Only MLflow 3.16.1 was exercised. -- The isolated consumer environment reused installed dependencies and replaced - editable Skyulf with the final 0.9.0 wheel. Python `-I` loaded the model from - a temporary working directory, asserted imports from site-packages and - matched producer predictions. This verifies independent package imports, - not a fresh network dependency install. -- MLflow aligns named columns, ignores extras and safely casts compatible - request types before bundle validation; direct `predict_local` still requires - exact names/order/dtypes. This transport boundary has an explicit regression. - Tests also exclude the producer's uv project and temporary source paths and - preserve an unrelated active run on a different tracking store. -- Scope boundary: registry/Unity Catalog resolution, G2 runner evidence, - Databricks jobs, Spark UDF/endpoint adapters and Delta batch publication stay - in SM-14–SM-16. SM-14 is now the next task. - -Reproducible verification (consumer Python must contain the final built wheel): - -```powershell -$env:SKYULF_MLFLOW_WHEEL_PYTHON = (Resolve-Path .cache/sm13-clean-env/Scripts/python.exe).Path -.cache/sm12-mlflow-env/Scripts/python.exe -m pytest skyulf-core/tests/integrations/test_mlflow_tracking.py skyulf-core/tests/integrations/test_mlflow_model.py -q -o addopts= --basetemp .cache/sm13-delivery --tb=short -.venv/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_inference_bundle.py skyulf-core/tests/unit/test_pipeline_inference_schema.py skyulf-core/tests/integrations -q -o addopts= --basetemp .cache/sm13-base-regression --tb=short -``` - -## SM-12 — 2026-09-22 validation record - -- Added the optional `skyulf.integrations.mlflow` adapter, the `mlflow` package - extra, `requirements-mlflow.txt`, and the English tracking guide. Importing - the adapter does not import MLflow; disabled tracking is a no-op with no - client construction or network access. -- `TrackingConfig` and `track_run` use an explicit `MlflowClient` and run ID. - They do not mutate MLflow's process-global active run, so concurrent contexts - remain isolated and a caller-owned run stays open. Explicit metrics, params, - tags, and an opt-in config artifact/digest are supported. -- Successful contexts terminate `FINISHED`; body exceptions terminate `FAILED`. - The default `raise` policy propagates tracking failures. `warn` preserves the - body result and exposes `run.tracking_error`; an outer runner may propagate - that value into its own result metadata. -- Base verification (`.venv`): **4 passed, 4 skipped** for the integration - tests; MLflow is absent in that environment. Optional verification in an - isolated MLflow 3.16.1 environment: **8 passed**. Ruff and ty checks passed - for the new Python files. -- Scope boundary: this task adds run tracking only. MLflow model packaging, - registry/Unity Catalog, Databricks batch delivery, endpoints, and templates - remain SM-13 onward. - -## SM-14 — 2026-09-22 validation record - -- Added `skyulf/integrations/mlflow/registry.py` and - `tests/integrations/test_mlflow_registry.py`. Publication accepts only the - `runs:/...` URI produced by the packaging adapter, uses explicit tracking and - registry clients, and leaves alias promotion to the caller. -- Resolution requires exactly one alias or version, pins an alias to a concrete - `models:/name/version` URI, and returns the packaged signature and bundle - digest. The version's recorded source URI is used for artifact metadata so - separate tracking and registry stores work without process-global MLflow state. -- The isolated MLflow 3.16.1 lane passed **10 tests**. It covers local SQLite - registration, alias movement, separate stores, missing model, access and - dependency failures, non-run publication rejection, and Unity Catalog - three-part-name validation. The base environment skips the optional module - because MLflow is absent. -- Scope boundary: live Unity Catalog/Databricks validation and the G2 Spark - runner remain SM-16 carry-forward work. SM-15 is now READY. - ## Bir görevi kapatma kaydı Her DONE satırına aynı dosyada aşağıdaki bilgileri içeren tarihli kayıt ekle: diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md b/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md index c0e1f5a9c..2bbfb7669 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE_tamamlanmakaydi.md @@ -490,3 +490,302 @@ performance guarantee. - Next task: SM-12 optional MLflow tracking, with tracking disabled remaining a valid local/Spark workflow. + +## SM-15I - automatic new-row scoring, DONE + +The user requires scheduled jobs to discover new source rows automatically. +The first run must score the existing bounded snapshot; later runs must score +only inserts since the last successful target commit, including late-arriving +rows in an earlier calendar period. The current `replaceWhere` writer cannot +publish only new rows in an overlapping period without deleting older +predictions. Implement a separate append-safe publisher and derive the source +watermark from the committed output receipt. See the +[SM-15I plan](12-sm15i-incremental-scoring-plan.md). This is a prerequisite +for SM-20a. The runner passed local real-Delta gates and the isolated two-job Databricks +rehearsal, including a source with no date column; see the +[SM-15I validation report](13-sm15i-live-validation-report.md). A separate +[real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) trained a Skyulf +pipeline with MLflow metrics and registered UC model version 1, then passed +200 initial + 100 later real-row predictions with an unchanged prior batch and +no-op replay. SM-20a remains the next task. + +## SM-15L - 2026-09-23 monthly local UC Delta publication, DONE + +- Added `run_local_batch` with truthful `local_pipeline` publication mode. + It loads one pinned UC source month under row/byte limits, scores through + fitted pandas or Polars FE/model code, converts only final keyed results to + an explicitly typed Spark DataFrame, and reuses guarded Delta period writes. + The target and admission control table are provisioned separately. +- Focused SDK/reader tests: **32 passed, 1 optional Spark skip**; batch + contracts: **25 passed**. Real local Spark/Delta: **6 passed**, including + two months, exact replay, stale version, accidental empty period, admission + denial, invalid target schema and stale model/source pins without mutation. Ruff, Ty and strict + MkDocs passed for the changed scope. +- Two isolated Databricks serverless jobs completed **SUCCESS**. January + published 80 pandas predictions to target version 1. February appended 80 + source rows, published 80 Polars predictions to target version 2, preserved + all January rows/metadata, replayed without a new commit, and rejected a + stale logical request. Both periods matched direct local gold by key. + See the [SM-15L live report](11-sm15l-live-validation-report.md) for run IDs, + model digests, test resources and scope limits. The date/version choices + were scripted for this proof; automatic new-row scoring is SM-15I. + +## SM-24a — 2026-09-23 local and Databricks validation, DONE + +- Added explicit bounded pandas/Polars training and a pinned UC Delta monthly + reader. Spark filters/projects/limits the source; saved local FE/model runs in + one Python process. This stage returns predictions and diagnostics, not a + Delta prediction table. The [local guide](../../docs/user_guide/databricks_local_sdk.md) + includes code and the decoded-byte boundary. +- Five pandas/Polars model packages trained and registered in isolated schema + `workspace.skyulf_sm24a_20260923`; an independent serverless scoring job + matched both 80-row months by key. Replay and negative cases passed. All 30 + additional inference-eligible preprocessing registrations passed on both + engines in a separate live audit, making 41 live-evidenced eligible IDs in + the [62-ID matrix](07-sm24a-node-matrix.csv). Train-only, inspection, + optional and unsupported IDs remain explicit. +- An unknown registry version failed preflight. A disposable alias moved to + R1 version 2 after preparation; the prepared predictor remained on version 1 + and returned the expected 80 rows. The alias was deleted. The full + [report](08-sm24a-live-validation-report.md) lists runs, versions, resources + and test results. +- A follow-up [scaler and outlier audit](09-sm24a-scaler-outlier-audit.md) + registered 10 pandas/Polars MLflow models with held-out metrics and passed + a separate two-month scoring replay. Four filtering outlier nodes reject + shortened prediction batches; Winsorize clips and preserves rows. +- A [200-row held-out metrics audit](10-sm24a-heldout-metrics-report.md) + logged regression MAE/RMSE/R2 and classification accuracy/F1 in the same + MLflow runs as five new test models. All five registered versions passed a + separate two-month scoring replay. R2/R3 had negative held-out R2; those + example models are not approved for production promotion. +- The Spark iterator does not expose actual wire-byte counts. `max_bytes` + bounds accepted decoded rows and local-frame memory; a very wide row can + arrive before rejection. [SM-24d](OPEN_QUEUE.md) retains the stronger + transport-budget option for wider or larger workloads. SM-15I then added + automatic new-row scoring; next is SM-20a. + +## SM-25 — 2026-09-23 local SDK validation, DONE + +- Added frozen `LocalWorkflowConfig` with explicit runtime, pandas/Polars engine, + bounded caller frame or declared future UC source, local/portable artifact + selection, optional MLflow store URIs and return/declared future Delta sink. + Config parsing performs no remote call and rejects embedded URI credentials. +- Local preflight reports actionable config, source, sink, artifact, engine, + node-contract and model-contract issues. Optional read-only registry preparation + resolves an alias once, loads the concrete version, and checks package digest. + The SDK has no separate FE/model allowlist; a fitted SkyulfPipeline controls + local prediction. An optional representative-frame probe exercises that + actual path before submission. Inference input is capped by rows and bytes. +- After the allowlist correction, **20 local SDK tests passed**, including + pandas/Polars MinMaxScaler + random-forest replay. The combined isolated + MLflow SDK, local-package and registry gate passed **39/39**. + The broader Core unit run completed **3927 passed, 71 skipped** before that + narrow correction; Ruff, repository Ty and strict MkDocs passed after it. No + Databricks job, UC source adapter or Delta writer was added in SM-25. +- [Local-engine SDK guide](../../docs/user_guide/databricks_local_sdk.md). + Next: SM-24a local training and bounded batch workflow. + +## SM-26 — 2026-09-23 local packaging validation, DONE + +- Added a versioned, trusted local pipeline artifact with recorded pandas/Polars + fit engine, raw/model feature schemas, model class, exact dependency versions, + payload checksum, classification classes and explicit tuned-threshold choice. + Legacy pipeline pickles still load; those without a recorded engine require a + refit before local MLflow packaging. +- Added MLflow pyfunc packaging and a synthetic input example/signature for the + supported scalar inputs. Its pandas boundary converts back to the recorded + Polars engine when needed. Whole-frame local is the only declared execution + scope; HTTP row-local and Spark scopes are rejected. Existing explicit registry + publication and pinned-version resolution now carry the local payload digest. +- Isolated MLflow 3.16.1 integration: **16 local artifact/pyfunc tests passed** + for categorical encoding, binning, null input, classes/probabilities, tuned + thresholds, cross-engine requests, and a fresh isolated Python subprocess + load. The 0.9.0 wheel was built from the changed source and installed into the + isolated environment; `python -I` resolved the new module from site-packages. + Existing MLflow packaging and registry compatibility: **47 passed, 1 skipped**. + Pipeline unit regression: **385 passed, 2 skipped**. Focused Ruff and ty checks + passed. No Databricks job or Delta writer was added in this task. +- [MLflow model guide](../../docs/user_guide/mlflow_models.md) lists the tested + model families and the wheel, serving and Spark limits. This task handed off + to SM-25 and then SM-24a. + +## SM-16 — 2026-09-22 local and live validation, DONE + +- Baseline `d43e74ca`. Added a trusted pinned registry-bundle loader and a + templates-free `databricks_batch_smoke.py` probe with pandas/Polars training, + an independent numerical oracle and both existing Spark inference modes. +- Combined local registry/worker gate: **29 passed**, no skips, MLflow 3.16.1 / + PySpark 4.0.3 / Python 3.12.3. Base regression: **77 passed, 28 optional skips**. + Ruff/format, repository Ty and strict MkDocs passed. Wheel built locally; + checksum, exact commands and remaining gates are in + [PLATFORM_VALIDATION.md](PLATFORM_VALIDATION.md). +- Databricks CLI **1.17.0**, profile `skyulf`, approved isolated schema + `workspace.skyulf_sm16_20260922`. Live regression parity passed both Spark + modes in run `447606109645160`; restricted-principal model allow/deny and + 10k/50k synthetic parity passed in run `2921374308246`. +- Checkpoint `311547fc` adds serverless identifier handling and shared Delta + admission. Local gates passed 75 inference tests and 18 admission/batch tests. + The reusable monthly Delta probe passed 5 real Delta tests; live Delta/alias + run `810044894558535` reached an unsupported `REFRESH TABLE` command. + Narrow refresh/cache compatibility fixes passed 48 real Delta tests; corrected + run `783094949884769` passed monthly replacement/replay, alias pinning and + full worker package-content checks. `databricks.yml` remains absent. +- SM-16 is **DONE** for the selected serverless workflow: winner job + `973709879452231` committed only after the contender verified held-owner + rejection. Contender `404334394214907` then failed a test-only permission-code + assertion; final restricted job `977447944071613` passed actual MODIFY denial, + unchanged data/version and owner release. The failed run remains documented. +- SM-15L was deferred immediately after SM-16; the later local-first Bundle + request reopens it after SM-24a. No implementation of that local sink is + included in SM-16, and real UC access remains an acceptance requirement. + +## SM-15 — 2026-09-22 validation record + +- Baseline `4a613cb5`; branch `090`. The delivery commit containing this record + adds `skyulf.integrations.databricks`, three batch test modules and a real + Delta fixture, the optional Delta dependency profile/CI lane, and the English + [monthly batch guide](../../docs/user_guide/databricks_batch.md). +- `run_batch` pins a concrete Delta source version and verifies snapshot + availability at the explicit cutoff. Both existing Spark inference modes + feed a precreated Delta target. A committed manifest records request identity, + model digest, installed code version and counts. Source history newer than + `as_of`, mismatched bundle digest/runtime and ambiguous contracts fail. +- Atomic `replaceWhere` preserves other periods. Empty deletion requires opt-in. + Run receipts prevent duplicate publication and prevent an old retry undoing + a newer recomputation. Changed requests under one run ID and stale target + versions fail. Local OS admission locks are tested across processes; both + runner and public sink reject local locks on distributed masters. +- Final required Linux/WSL lane: **43 passed**, including **18 real Delta + integration cases** and **25 contract/admission cases**, no skips, 111.95s. + Python **3.12.3**, PySpark **4.0.3**, Delta Python/JVM **4.0.0**, Java 17; + pandas **2.3.3**, Polars **1.44.2**, Arrow **25.0.1**, sklearn **1.9.1**. + Initial exploratory tests used newer Python-package patch versions; the final + gate was rerun after aligning the environment with `requirements-delta.txt`. +- Cases include a pinned old source after a newer commit, a non-UTC Spark + session, exact period boundaries, null/wrong metadata/count rejection with + target version unchanged, stale/new/old retries and committed empty deletion. + Admission permission denial uses fault injection; it is not live UC evidence. +- Base regression: **105 passed, 26 skipped** with MLflow/Delta absent, plus + existing sklearn interchange and Windows physical-core warnings. Final narrow + Windows contract/admission run: **25 passed**. Ruff check/format, repository + Ty and strict MkDocs passed; the guide's Mermaid parsed with the real parser. + Repository pre-commit hooks passed, including the synchronized optional + dependency lock. GitHub Actions was added but has not run remotely. +- Windows Hadoop filesystem support could not run real Delta I/O, so the + required transaction gate used an isolated Linux/WSL environment. No runtime + authentication or Databricks job was performed. Preserve pre-existing temp + folders and editor-created Databricks configuration outside this commit. +- Remaining scope: the cutoff proves snapshot availability only, not upstream + point-in-time feature joins. Model registry identity is bound by the caller; + bundle digest is checked. Receipt/history retention bounds the retry window. + A shared local lock directory protects cooperative local writers on one host; + distributed admission requires a separate implementation with ownership held + throughout the commit. Expiring leases without sink fencing are unsupported. + These platform concerns and the carried registry-to-Spark gate belong to SM-16. + +Reproducible commands (Linux with Java 17 and an isolated environment): + +```bash +uv venv .venv-delta +uv pip install --python .venv-delta/bin/python -r requirements-delta.txt +SKYULF_REQUIRE_DELTA=1 .venv-delta/bin/python -m pytest \ + skyulf-core/tests/integrations/test_batch_contract.py \ + skyulf-core/tests/integrations/test_batch_admission.py \ + skyulf-core/tests/integrations/test_delta_publish.py -q -o addopts= +``` + +Exact local invocation used the prepared WSL environment and cached official jars: + +```powershell +wsl -d Ubuntu -- bash .cache/sm15-linux-run.sh -m pytest skyulf-core/tests/integrations/test_batch_contract.py skyulf-core/tests/integrations/test_batch_admission.py skyulf-core/tests/integrations/test_delta_publish.py -q -p no:cacheprovider -o addopts= --basetemp /tmp/sm15-delta-pinned-final --tb=short +.venv/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_inference_bundle.py skyulf-core/tests/unit/test_pipeline_inference_schema.py skyulf-core/tests/integrations -q -o addopts= --basetemp .cache/sm15-base-final --tb=short +.venv/Scripts/ty.exe check backend skyulf-core/skyulf skyulf-core/tests run_skyulf.py celery_worker.py +.venv/Scripts/python.exe -m mkdocs build --strict --site-dir .cache/sm15-docs +``` + +The local shell wrapper exports Java 17, its Python worker executable is selected +by the fixture, and `SKYULF_DELTA_JARS` points to the cached Delta 4.0.0 jars. +The portable command above downloads those jars through Delta's normal helper. + +## SM-13 — 2026-09-22 validation record + +- Added optional MLflow `pyfunc` packaging in + `skyulf/integrations/mlflow/model.py`. `log_model` serializes the existing + `InferenceBundle`, records a manifest-derived named signature and synthetic + input example, and uploads the model directory to the explicitly supplied + run ID through `MlflowClient`. `tracking_uri` can be passed when the run was + created by a client-bound tracker; no global active run is used to select the + destination. +- Raw and features bundles preserve local prediction results after MLflow + save/load for pandas and Polars-trained pipelines. Classification tests cover + class order, probabilities and tuned thresholds. Positional NumPy/list input + is rejected. Dtypes without an exact MLflow column representation are rejected + during signature creation rather than silently widened. +- Baseline `67315253`; this delivery commit includes implementation, tests, + English guide and validation records. Python 3.12.10 / MLflow 3.16.1: + **31 passed** (23 model, 8 tracking) with the wheel subprocess gate enabled. + Base bundle/schema/integration regression: **80 passed, 7 skipped** with + existing numeric/protocol warnings. Base tracking/model alone: **4 passed, + 5 skipped**; MLflow is absent. Ruff, repository Ty/pre-commit and strict + MkDocs passed. Only MLflow 3.16.1 was exercised. +- The isolated consumer environment reused installed dependencies and replaced + editable Skyulf with the final 0.9.0 wheel. Python `-I` loaded the model from + a temporary working directory, asserted imports from site-packages and + matched producer predictions. This verifies independent package imports, + not a fresh network dependency install. +- MLflow aligns named columns, ignores extras and safely casts compatible + request types before bundle validation; direct `predict_local` still requires + exact names/order/dtypes. This transport boundary has an explicit regression. + Tests also exclude the producer's uv project and temporary source paths and + preserve an unrelated active run on a different tracking store. +- Scope boundary: registry/Unity Catalog resolution, G2 runner evidence, + Databricks jobs, Spark UDF/endpoint adapters and Delta batch publication stay + in SM-14–SM-16. SM-14 is now the next task. + +Reproducible verification (consumer Python must contain the final built wheel): + +```powershell +$env:SKYULF_MLFLOW_WHEEL_PYTHON = (Resolve-Path .cache/sm13-clean-env/Scripts/python.exe).Path +.cache/sm12-mlflow-env/Scripts/python.exe -m pytest skyulf-core/tests/integrations/test_mlflow_tracking.py skyulf-core/tests/integrations/test_mlflow_model.py -q -o addopts= --basetemp .cache/sm13-delivery --tb=short +.venv/Scripts/python.exe -m pytest skyulf-core/tests/spark/test_inference_bundle.py skyulf-core/tests/unit/test_pipeline_inference_schema.py skyulf-core/tests/integrations -q -o addopts= --basetemp .cache/sm13-base-regression --tb=short +``` + +## SM-12 — 2026-09-22 validation record + +- Added the optional `skyulf.integrations.mlflow` adapter, the `mlflow` package + extra, `requirements-mlflow.txt`, and the English tracking guide. Importing + the adapter does not import MLflow; disabled tracking is a no-op with no + client construction or network access. +- `TrackingConfig` and `track_run` use an explicit `MlflowClient` and run ID. + They do not mutate MLflow's process-global active run, so concurrent contexts + remain isolated and a caller-owned run stays open. Explicit metrics, params, + tags, and an opt-in config artifact/digest are supported. +- Successful contexts terminate `FINISHED`; body exceptions terminate `FAILED`. + The default `raise` policy propagates tracking failures. `warn` preserves the + body result and exposes `run.tracking_error`; an outer runner may propagate + that value into its own result metadata. +- Base verification (`.venv`): **4 passed, 4 skipped** for the integration + tests; MLflow is absent in that environment. Optional verification in an + isolated MLflow 3.16.1 environment: **8 passed**. Ruff and ty checks passed + for the new Python files. +- Scope boundary: this task adds run tracking only. MLflow model packaging, + registry/Unity Catalog, Databricks batch delivery, endpoints, and templates + remain SM-13 onward. + +## SM-14 — 2026-09-22 validation record + +- Added `skyulf/integrations/mlflow/registry.py` and + `tests/integrations/test_mlflow_registry.py`. Publication accepts only the + `runs:/...` URI produced by the packaging adapter, uses explicit tracking and + registry clients, and leaves alias promotion to the caller. +- Resolution requires exactly one alias or version, pins an alias to a concrete + `models:/name/version` URI, and returns the packaged signature and bundle + digest. The version's recorded source URI is used for artifact metadata so + separate tracking and registry stores work without process-global MLflow state. +- The isolated MLflow 3.16.1 lane passed **10 tests**. It covers local SQLite + registration, alias movement, separate stores, missing model, access and + dependency failures, non-run publication rejection, and Unity Catalog + three-part-name validation. The base environment skips the optional module + because MLflow is absent. +- Scope boundary: live Unity Catalog/Databricks validation and the G2 Spark + runner remain SM-16 carry-forward work. SM-15 is now READY. diff --git a/skyulf-core/skyulf/inference/local_evaluation.py b/skyulf-core/skyulf/inference/local_evaluation.py new file mode 100644 index 000000000..a58b540d7 --- /dev/null +++ b/skyulf-core/skyulf/inference/local_evaluation.py @@ -0,0 +1,60 @@ +"""Held-out metrics for a saved pandas/Polars local pipeline.""" + +import math + +import pandas as pd +import polars as pl +from sklearn.metrics import ( + accuracy_score, + f1_score, + mean_absolute_error, + mean_squared_error, + r2_score, +) + +from .local_pipeline import LocalPipelineArtifact, predict_local_pipeline + + +def evaluate_local_holdout( + artifact: LocalPipelineArtifact, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, +) -> dict[str, float]: + """Measure a saved local pipeline on labeled rows excluded from fitting. + + The caller owns the split. This function never fits preprocessing or a model; + it predicts with the loaded artifact and records only held-out metrics. + Binary F1 uses the artifact's second class as the positive label. + """ + if not isinstance(artifact, LocalPipelineArtifact): + raise TypeError("artifact must be a LocalPipelineArtifact.") + if not isinstance(heldout, pd.DataFrame | pl.DataFrame): + raise TypeError("heldout must be a pandas or Polars DataFrame.") + if len(heldout) < 2: + raise ValueError("heldout must contain at least two labeled rows.") + if target_column not in heldout.columns or target_column in artifact.manifest.input_columns: + raise ValueError("heldout must contain a separate target column.") + columns = list(artifact.manifest.input_columns) + features = ( + heldout.select(columns) if isinstance(heldout, pl.DataFrame) else heldout.loc[:, columns] + ) + actual = heldout[target_column].to_numpy() + predicted = predict_local_pipeline(features, artifact)["prediction"].to_numpy() + if artifact.manifest.task == "regression": + return { + "heldout_mae": float(mean_absolute_error(actual, predicted)), + "heldout_rmse": float(math.sqrt(mean_squared_error(actual, predicted))), + "heldout_r2": float(r2_score(actual, predicted)), + } + metrics = { + "heldout_accuracy": float(accuracy_score(actual, predicted)), + "heldout_f1_weighted": float( + f1_score(actual, predicted, average="weighted", zero_division=0) + ), + } + if len(artifact.manifest.classes) == 2: + metrics["heldout_f1"] = float( + f1_score(actual, predicted, pos_label=artifact.manifest.classes[1], zero_division=0) + ) + return metrics diff --git a/skyulf-core/skyulf/integrations/databricks/local_batch.py b/skyulf-core/skyulf/integrations/databricks/local_batch.py index 710800998..c25e20aa2 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_batch.py +++ b/skyulf-core/skyulf/integrations/databricks/local_batch.py @@ -6,7 +6,6 @@ from __future__ import annotations -import math import pickle from dataclasses import dataclass from datetime import UTC, datetime @@ -16,19 +15,12 @@ import pandas as pd import polars as pl -from sklearn.metrics import ( - accuracy_score, - f1_score, - mean_absolute_error, - mean_squared_error, - r2_score, -) from ...data.dataset import SplitDataset +from ...inference.local_evaluation import evaluate_local_holdout as evaluate_local_holdout from ...inference.local_pipeline import ( LocalPipelineArtifact, load_local_pipeline, - predict_local_pipeline, save_local_pipeline, ) from ...pipeline import SkyulfPipeline @@ -132,51 +124,6 @@ def fit_local_workflow( return load_local_pipeline(artifact_path) -def evaluate_local_holdout( - artifact: LocalPipelineArtifact, - heldout: pd.DataFrame | pl.DataFrame, - *, - target_column: str, -) -> dict[str, float]: - """Measure a saved local pipeline on labeled rows excluded from fitting. - - The caller owns the split. This function never fits preprocessing or a model; - it predicts with the loaded artifact and records only held-out metrics. - Binary F1 uses the artifact's second class as the positive label. - """ - if not isinstance(artifact, LocalPipelineArtifact): - raise TypeError("artifact must be a LocalPipelineArtifact.") - if not isinstance(heldout, pd.DataFrame | pl.DataFrame): - raise TypeError("heldout must be a pandas or Polars DataFrame.") - if len(heldout) < 2: - raise ValueError("heldout must contain at least two labeled rows.") - if target_column not in heldout.columns or target_column in artifact.manifest.input_columns: - raise ValueError("heldout must contain a separate target column.") - columns = list(artifact.manifest.input_columns) - features = ( - heldout.select(columns) if isinstance(heldout, pl.DataFrame) else heldout.loc[:, columns] - ) - actual = heldout[target_column].to_numpy() - predicted = predict_local_pipeline(features, artifact)["prediction"].to_numpy() - if artifact.manifest.task == "regression": - return { - "heldout_mae": float(mean_absolute_error(actual, predicted)), - "heldout_rmse": float(math.sqrt(mean_squared_error(actual, predicted))), - "heldout_r2": float(r2_score(actual, predicted)), - } - metrics = { - "heldout_accuracy": float(accuracy_score(actual, predicted)), - "heldout_f1_weighted": float( - f1_score(actual, predicted, average="weighted", zero_division=0) - ), - } - if len(artifact.manifest.classes) == 2: - metrics["heldout_f1"] = float( - f1_score(actual, predicted, pos_label=artifact.manifest.classes[1], zero_division=0) - ) - return metrics - - def read_local_source(spark: Any, spec: LocalSourceSpec) -> pd.DataFrame: """Filter and project a fixed Delta snapshot before bounded driver transfer.""" if not isinstance(spec, LocalSourceSpec): diff --git a/skyulf-core/skyulf/integrations/mlflow/validation.py b/skyulf-core/skyulf/integrations/mlflow/validation.py new file mode 100644 index 000000000..3ade89831 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/validation.py @@ -0,0 +1,247 @@ +"""Read-only comparison of pinned registered local pipeline versions.""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from importlib.metadata import version + +import pandas as pd +import polars as pl + +from ...inference.local_evaluation import evaluate_local_holdout +from ...inference.local_pipeline import LocalPipelineArtifact +from .registry import ResolvedModel, load_registered_local_pipeline + +_MINIMIZE = {"heldout_mae", "heldout_rmse"} +_MAXIMIZE = {"heldout_r2", "heldout_accuracy", "heldout_f1_weighted", "heldout_f1"} +_REGRESSION = _MINIMIZE | {"heldout_r2"} +_CLASSIFICATION = _MAXIMIZE - {"heldout_r2"} + + +@dataclass(frozen=True, slots=True) +class ModelComparisonReport: + """Record one candidate/champion decision without modifying the registry.""" + + dataset_id: str + row_count: int + code_version: str + model_name: str + candidate_version: str + candidate_digest: str + champion_version: str | None + champion_digest: str | None + metric: str + metric_direction: str + min_improvement: float + quality_threshold: float | None + candidate_metrics: dict[str, float] + champion_metrics: dict[str, float] | None + improvement: float | None + eligible: bool + reason: str + + +def _validate_request( + candidate: ResolvedModel, + champion: ResolvedModel | None, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, + dataset_id: str, + metric: str, + min_improvement: float, + quality_threshold: float | None, + max_rows: int, + max_bytes: int, +) -> None: + """Reject ambiguous identities, policies and oversized data before loading.""" + if not isinstance(candidate, ResolvedModel) or ( + champion is not None and not isinstance(champion, ResolvedModel) + ): + raise TypeError("candidate and champion must be resolved model references.") + for reference in (candidate, champion): + if reference is None: + continue + if ( + type(reference.name) is not str + or not reference.name + or type(reference.version) is not str + or not reference.version.isascii() + or not reference.version.isdigit() + or int(reference.version) <= 0 + or reference.model_uri != f"models:/{reference.name}/{reference.version}" + or not isinstance(reference.digest, str) + or not reference.digest + ): + raise ValueError("Each model must have a concrete version and artifact digest.") + if champion is not None and ( + candidate.name != champion.name or candidate.version == champion.version + ): + raise ValueError("Candidate and champion must be distinct versions of one model.") + if not isinstance(heldout, pd.DataFrame | pl.DataFrame): + raise TypeError("heldout must be a pandas or Polars DataFrame.") + if type(dataset_id) is not str or not dataset_id.strip(): + raise ValueError("dataset_id must identify the pinned evaluation set.") + if type(target_column) is not str or target_column not in heldout.columns: + raise ValueError("target_column must exist in the evaluation set.") + if type(metric) is not str or metric not in _MINIMIZE | _MAXIMIZE: + raise ValueError("metric must be a supported heldout metric.") + if ( + type(min_improvement) not in (int, float) + or not math.isfinite(min_improvement) + or min_improvement < 0 + ): + raise ValueError("min_improvement must be a finite nonnegative number.") + if quality_threshold is not None and ( + type(quality_threshold) not in (int, float) or not math.isfinite(quality_threshold) + ): + raise ValueError("quality_threshold must be a finite number or None.") + if len(heldout) < 2: + raise ValueError("heldout must contain at least two labeled rows.") + if type(max_rows) is not int or max_rows < 2 or len(heldout) > max_rows: + raise ValueError("heldout exceeds max_rows or the row limit is invalid.") + if type(max_bytes) is not int or max_bytes <= 0: + raise ValueError("max_bytes must be a positive integer.") + frame_bytes = ( + int(heldout.memory_usage(index=True, deep=True).sum()) + if isinstance(heldout, pd.DataFrame) + else int(heldout.estimated_size()) + ) + if frame_bytes > max_bytes: + raise ValueError("heldout exceeds max_bytes.") + + +def _checked_artifact( + reference: ResolvedModel, *, tracking_uri: str | None, registry_uri: str | None +) -> LocalPipelineArtifact: + """Load one concrete artifact and confirm its registry digest.""" + artifact = load_registered_local_pipeline( + reference, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + if artifact.manifest.pipeline_sha256 != reference.digest: + raise ValueError("Registered model digest differs from the loaded pipeline.") + return artifact + + +def compare_registered_local_models( + candidate: ResolvedModel, + champion: ResolvedModel | None, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, + dataset_id: str, + metric: str, + min_improvement: float, + max_rows: int, + max_bytes: int, + quality_threshold: float | None = None, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> ModelComparisonReport: + """Score two pinned versions on identical labeled rows without moving aliases. + + The caller must pin and describe the source snapshot/split in dataset_id. + The report does not prove that identity or approve the model for production. + A tie cannot pass even when min_improvement is zero. Without a champion, + the first candidate is measured but never promoted implicitly. + """ + _validate_request( + candidate, + champion, + heldout, + target_column=target_column, + dataset_id=dataset_id, + metric=metric, + min_improvement=min_improvement, + quality_threshold=quality_threshold, + max_rows=max_rows, + max_bytes=max_bytes, + ) + candidate_artifact = _checked_artifact( + candidate, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + champion_artifact = ( + _checked_artifact(champion, tracking_uri=tracking_uri, registry_uri=registry_uri) + if champion is not None + else None + ) + task = candidate_artifact.manifest.task + if metric not in (_REGRESSION if task == "regression" else _CLASSIFICATION): + raise ValueError("metric is incompatible with the candidate task.") + if champion_artifact is not None and ( + task != champion_artifact.manifest.task + or ( + task == "classification" + and candidate_artifact.manifest.classes != champion_artifact.manifest.classes + ) + ): + raise ValueError("Candidate and champion task or class contracts differ.") + candidate_metrics = evaluate_local_holdout( + candidate_artifact, heldout, target_column=target_column + ) + champion_metrics = ( + evaluate_local_holdout(champion_artifact, heldout, target_column=target_column) + if champion_artifact is not None + else None + ) + candidate_value = candidate_metrics.get(metric) + champion_value = champion_metrics.get(metric) if champion_metrics is not None else None + if ( + candidate_value is None + or not math.isfinite(candidate_value) + or ( + champion_metrics is not None + and (champion_value is None or not math.isfinite(champion_value)) + ) + ): + raise ValueError("Selected metric is unavailable or non-finite on the holdout.") + direction = "minimize" if metric in _MINIMIZE else "maximize" + improvement = ( + None + if champion_value is None + else ( + champion_value - candidate_value + if direction == "minimize" + else candidate_value - champion_value + ) + ) + quality_passed = quality_threshold is None or ( + candidate_value <= quality_threshold + if direction == "minimize" + else candidate_value >= quality_threshold + ) + eligible = ( + improvement is not None + and improvement > 0 + and improvement >= min_improvement + and quality_passed + ) + reason = ( + "no_champion" + if champion is None + else "quality_gate_failed" + if not quality_passed + else "candidate_improved" + if eligible + else "insufficient_improvement" + ) + return ModelComparisonReport( + dataset_id=dataset_id, + row_count=len(heldout), + code_version=version("skyulf-core"), + model_name=candidate.name, + candidate_version=candidate.version, + candidate_digest=candidate.digest or "", + champion_version=champion.version if champion is not None else None, + champion_digest=champion.digest if champion is not None else None, + metric=metric, + metric_direction=direction, + min_improvement=float(min_improvement), + quality_threshold=float(quality_threshold) if quality_threshold is not None else None, + candidate_metrics=candidate_metrics, + champion_metrics=champion_metrics, + improvement=improvement, + eligible=eligible, + reason=reason, + ) diff --git a/skyulf-core/tests/integrations/test_mlflow_validation.py b/skyulf-core/tests/integrations/test_mlflow_validation.py new file mode 100644 index 000000000..35fc9b18c --- /dev/null +++ b/skyulf-core/tests/integrations/test_mlflow_validation.py @@ -0,0 +1,380 @@ +"""Compare pinned local MLflow model versions without changing registry state.""" + +from __future__ import annotations + +import json +from dataclasses import asdict, replace +from importlib.metadata import version +from typing import Any + +import numpy as np +import pandas as pd +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import LocalPipelineArtifact +from skyulf.integrations.databricks.local_batch import fit_local_workflow +from skyulf.integrations.mlflow import validation +from skyulf.integrations.mlflow.registry import ResolvedModel + + +def _fitted(tmp_path, offset: float) -> LocalPipelineArtifact: + """Fit one model whose known bias makes comparison direction observable.""" + x = np.arange(12, dtype="float64") + frame = pd.DataFrame({"x": x, "target": 2.0 * x + offset}) + return fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=frame, test=frame.head(0)), + target_column="target", + artifact_path=tmp_path / f"model-{offset}", + max_rows=12, + max_bytes=10_000, + ) + + +def _reference(artifact: LocalPipelineArtifact, version: str) -> ResolvedModel: + """Bind the fitted artifact to one concrete registry identity.""" + return ResolvedModel( + name="workspace.test.risk", + version=version, + model_uri=f"models:/workspace.test.risk/{version}", + signature=None, + digest=artifact.manifest.pipeline_sha256, + ) + + +def _holdout() -> pd.DataFrame: + """Reserve the same unseen labels for both registered versions.""" + x = np.arange(20, 25, dtype="float64") + return pd.DataFrame({"x": x, "target": 2.0 * x}) + + +def test_comparison_uses_same_holdout_and_minimizes_error(tmp_path, monkeypatch) -> None: + """A better candidate should pass only after both pinned versions are scored.""" + champion = _fitted(tmp_path, 10.0) + candidate = _fitted(tmp_path, 0.0) + references = {_reference(champion, "1"): champion, _reference(candidate, "2"): candidate} + loaded: list[str] = [] + + def load(resolved, **kwargs): + """Record concrete loads; evaluation has no alias mutation path.""" + loaded.append(resolved.version) + return references[resolved] + + monkeypatch.setattr(validation, "load_registered_local_pipeline", load) + heldout = _holdout() + original = heldout.copy(deep=True) + report = validation.compare_registered_local_models( + _reference(candidate, "2"), + _reference(champion, "1"), + heldout, + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_rmse", + min_improvement=1.0, + max_rows=20, + max_bytes=10_000, + ) + + assert loaded == ["2", "1"] + pd.testing.assert_frame_equal(heldout, original) + assert report.eligible is True + assert report.reason == "candidate_improved" + assert report.candidate_metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) + assert report.champion_metrics is not None + assert report.champion_metrics["heldout_rmse"] == pytest.approx(10.0, abs=1e-8) + assert report.improvement == pytest.approx(10.0) + assert report.dataset_id == "workspace.test.labels@5/holdout-v1" + assert report.row_count == 5 + assert report.code_version == version("skyulf-core") + assert json.loads(json.dumps(asdict(report)))["candidate_version"] == "2" + + +def test_first_candidate_is_reported_without_automatic_champion(tmp_path, monkeypatch) -> None: + """The first registered version must still require a separate bootstrap choice.""" + candidate = _fitted(tmp_path, 0.0) + monkeypatch.setattr( + validation, "load_registered_local_pipeline", lambda *args, **kwargs: candidate + ) + report = validation.compare_registered_local_models( + _reference(candidate, "1"), + None, + _holdout(), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_r2", + min_improvement=0.0, + max_rows=20, + max_bytes=10_000, + ) + + assert report.eligible is False + assert report.reason == "no_champion" + assert report.champion_metrics is None + + +def test_incompatible_class_contract_rejects_before_scoring(tmp_path, monkeypatch) -> None: + """Different class labels cannot produce a valid champion comparison.""" + baseline = _fitted(tmp_path, 0.0) + champion = replace( + baseline, + manifest=baseline.manifest.model_copy( + update={"task": "classification", "classes": ("no", "yes")} + ), + ) + candidate = replace( + baseline, + manifest=baseline.manifest.model_copy( + update={"task": "classification", "classes": ("negative", "positive")} + ), + ) + monkeypatch.setattr( + validation, + "load_registered_local_pipeline", + lambda resolved, **kwargs: candidate if resolved.version == "2" else champion, + ) + with pytest.raises(ValueError, match="class"): + validation.compare_registered_local_models( + _reference(candidate, "2"), + _reference(champion, "1"), + _holdout(), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_accuracy", + min_improvement=0.0, + max_rows=20, + max_bytes=10_000, + ) + + +@pytest.mark.parametrize( + ("changes", "message"), + [ + ({"metric": "unknown_metric"}, "metric"), + ({"dataset_id": ""}, "dataset_id"), + ({"max_rows": 2}, "max_rows"), + ({"max_bytes": 1}, "max_bytes"), + ({"min_improvement": -1.0}, "min_improvement"), + ], +) +def test_invalid_comparison_fails_before_model_load( + tmp_path, monkeypatch, changes, message +) -> None: + """Malformed policy or oversized data must not download registered models.""" + candidate = _fitted(tmp_path, 0.0) + monkeypatch.setattr( + validation, + "load_registered_local_pipeline", + lambda *args, **kwargs: pytest.fail("model should not load"), + ) + options: dict[str, Any] = { + "target_column": "target", + "dataset_id": "workspace.test.labels@5/holdout-v1", + "metric": "heldout_rmse", + "min_improvement": 0.0, + "max_rows": 20, + "max_bytes": 10_000, + } + options.update(changes) + with pytest.raises(ValueError, match=message): + validation.compare_registered_local_models( + _reference(candidate, "2"), None, _holdout(), **options + ) + + +def test_polars_classification_comparison_maximizes_accuracy(tmp_path, monkeypatch) -> None: + """A candidate with correct class semantics should beat a biased champion.""" + import polars as pl + + x = np.r_[np.arange(-12, 0), np.arange(1, 13)].astype("float64") + truth = np.where(x > 0, "yes", "no") + train = pl.DataFrame({"x": x, "target": truth}) + reversed_train = pl.DataFrame({"x": x, "target": np.where(x > 0, "no", "yes")}) + config = {"preprocessing": [], "modeling": {"type": "logistic_regression"}} + candidate = fit_local_workflow( + config, + SplitDataset(train=train, test=train.head(0)), + target_column="target", + artifact_path=tmp_path / "candidate-polars", + max_rows=24, + max_bytes=20_000, + ) + champion = fit_local_workflow( + config, + SplitDataset(train=reversed_train, test=reversed_train.head(0)), + target_column="target", + artifact_path=tmp_path / "champion-polars", + max_rows=24, + max_bytes=20_000, + ) + assert candidate.manifest.classes == champion.manifest.classes + monkeypatch.setattr( + validation, + "load_registered_local_pipeline", + lambda resolved, **kwargs: candidate if resolved.version == "2" else champion, + ) + heldout = pl.DataFrame({"x": [-3.0, -2.0, 2.0, 3.0], "target": ["no", "no", "yes", "yes"]}) + + report = validation.compare_registered_local_models( + _reference(candidate, "2"), + _reference(champion, "1"), + heldout, + target_column="target", + dataset_id="workspace.test.labels@6/class-holdout", + metric="heldout_accuracy", + min_improvement=0.2, + quality_threshold=0.9, + max_rows=10, + max_bytes=10_000, + ) + + assert report.metric_direction == "maximize" + assert report.candidate_metrics["heldout_accuracy"] == pytest.approx(1.0) + assert report.champion_metrics is not None + assert report.champion_metrics["heldout_accuracy"] == pytest.approx(0.0) + assert report.eligible is True + + +def test_real_local_registry_comparison_keeps_alias_pinned(tmp_path) -> None: + """Fetching both registered versions must leave the champion alias unchanged.""" + mlflow = pytest.importorskip("mlflow") + from skyulf.integrations.mlflow.local_model import log_local_model + from skyulf.integrations.mlflow.registry import register_model, resolve_model + from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run + + uri = f"sqlite:///{(tmp_path / 'models.db').as_posix()}" + tracking = TrackingConfig(enabled=True, tracking_uri=uri, experiment_name="sm22-local") + client = mlflow.MlflowClient(tracking_uri=uri, registry_uri=uri) + client.create_experiment("sm22-local", artifact_location=(tmp_path / "artifacts").as_uri()) + name = "sm22-candidate-champion" + for offset in (10.0, 0.0): + _fitted(tmp_path, offset) + with track_run(tracking, run_name=f"candidate-{offset}") as run: + assert run.run_id is not None + model_uri = log_local_model( + tmp_path / f"model-{offset}", + run_id=run.run_id, + artifact_path="model", + tracking_uri=uri, + ) + register_model(model_uri, name, tracking_uri=uri, registry_uri=uri) + client.set_registered_model_alias(name, "champion", "1") + champion = resolve_model(name, alias="champion", tracking_uri=uri, registry_uri=uri) + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + + report = validation.compare_registered_local_models( + candidate, + champion, + _holdout(), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_rmse", + min_improvement=1.0, + max_rows=20, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + + assert report.eligible is True + assert report.candidate_version == "2" + assert report.champion_version == "1" + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + +def test_candidate_must_clear_absolute_quality_gate(tmp_path, monkeypatch) -> None: + """Relative improvement alone must not qualify a still-poor challenger.""" + champion = _fitted(tmp_path, 10.0) + candidate = _fitted(tmp_path, 5.0) + monkeypatch.setattr( + validation, + "load_registered_local_pipeline", + lambda resolved, **kwargs: candidate if resolved.version == "2" else champion, + ) + + report = validation.compare_registered_local_models( + _reference(candidate, "2"), + _reference(champion, "1"), + _holdout(), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_rmse", + min_improvement=1.0, + quality_threshold=1.0, + max_rows=20, + max_bytes=10_000, + ) + + assert report.improvement == pytest.approx(5.0) + assert report.eligible is False + assert report.reason == "quality_gate_failed" + + +def test_malformed_resolved_version_fails_before_registry_load(tmp_path, monkeypatch) -> None: + """A caller-built reference with a non-string version must fail clearly.""" + candidate = _fitted(tmp_path, 0.0) + reference = replace(_reference(candidate, "2"), version=2) + monkeypatch.setattr( + validation, + "load_registered_local_pipeline", + lambda *args, **kwargs: pytest.fail("registry must not be called"), + ) + with pytest.raises(ValueError, match="concrete version"): + validation.compare_registered_local_models( + reference, + None, + _holdout(), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_rmse", + min_improvement=0.0, + max_rows=20, + max_bytes=10_000, + ) + + +def test_registry_permission_failure_does_not_yield_a_report(tmp_path, monkeypatch) -> None: + """A denied candidate load must propagate instead of looking like a failed metric.""" + from skyulf.integrations.mlflow.registry import RegistryAccessError + + candidate = _fitted(tmp_path, 0.0) + + def denied(*args, **kwargs): + """Represent an access failure at the optional registry boundary.""" + raise RegistryAccessError("denied") + + monkeypatch.setattr(validation, "load_registered_local_pipeline", denied) + with pytest.raises(RegistryAccessError, match="denied"): + validation.compare_registered_local_models( + _reference(candidate, "2"), + None, + _holdout(), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_rmse", + min_improvement=0.0, + max_rows=20, + max_bytes=10_000, + ) + + +def test_too_small_holdout_fails_before_registry_load(tmp_path, monkeypatch) -> None: + """One labeled row cannot produce meaningful held-out metrics or a remote load.""" + candidate = _fitted(tmp_path, 0.0) + monkeypatch.setattr( + validation, + "load_registered_local_pipeline", + lambda *args, **kwargs: pytest.fail("registry must not be called"), + ) + with pytest.raises(ValueError, match="at least two"): + validation.compare_registered_local_models( + _reference(candidate, "2"), + None, + _holdout().head(1), + target_column="target", + dataset_id="workspace.test.labels@5/holdout-v1", + metric="heldout_rmse", + min_improvement=0.0, + max_rows=20, + max_bytes=10_000, + ) From 23182d430ae7c99ceba0e2813e79906ecddc39a0 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 20:44:39 +0300 Subject: [PATCH 38/85] refactor: reuse core metrics for local MLflow evaluation Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 ++- docs/user_guide/mlflow_registry.md | 47 ++++++++++++++-- .../16-sm22a-local-validation-report.md | 10 ++-- .../skyulf/inference/local_evaluation.py | 54 ++++++++++--------- .../skyulf/integrations/mlflow/validation.py | 41 ++++++++++++-- .../skyulf/modeling/_evaluation/metrics.py | 4 +- .../test_databricks_local_batch.py | 17 +++++- .../integrations/test_mlflow_validation.py | 19 ++++--- 8 files changed, 150 insertions(+), 48 deletions(-) diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 3682cfd02..f727eefd5 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -30,8 +30,10 @@ execution, MLflow registry and Databricks delivery remain under development. - Read-only local MLflow candidate/champion comparison on one bounded labeled holdout reports pinned model/data identities, held-out metrics, improvement and a - directional quality gate. It never moves an alias; controlled promotion and - label-aware retraining remain separate pre-Bundle tasks. + directional quality gate. Held-out evaluation now reuses Core's full model + metric calculators, including probability-based classification metrics when + defined, rather than maintaining separate formulas. It never moves an alias; + controlled promotion and label-aware retraining remain separate pre-Bundle tasks. - Local-engine Databricks SDK configuration and preflight for bounded pandas/Polars batches. It selects trusted local or portable artifacts, resolves MLflow aliases once to concrete versions, checks metadata and diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 6cd8a7d3c..720e04934 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -91,6 +91,32 @@ bundle = load_registered_bundle( assert bundle.semantic_digest == resolved.digest ``` +## How the adapters use Skyulf Core + +The Databricks local workflow calls Skyulf Core's existing pipeline fit and +prediction methods. Its UC reader and Delta writer handle transport and +publication; they do not reimplement feature engineering or model behavior. +The MLflow adapter packages that same saved pipeline, resolves a registry +alias to a concrete version, and loads the artifact for prediction or +comparison. Held-out evaluation runs the saved pipeline once and passes its +predictions and class-ordered probabilities to Core's model metric calculators. +There is no separate Databricks or MLflow training algorithm. + +For example, a training job can log every available held-out metric to +its own MLflow run without implementing a second evaluator: + +```python +from skyulf.inference.local_evaluation import evaluate_local_holdout +from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run + +metrics = evaluate_local_holdout(artifact, heldout, target_column="target") +with track_run( + TrackingConfig(enabled=True, experiment_name="customer-risk"), + run_name="candidate-training", +) as run: + run.log_metrics(metrics) +``` + ## Compare a local challenger before promotion For a fitted pandas/Polars pipeline, resolve both registered versions to @@ -127,10 +153,23 @@ report = compare_registered_local_models( print(report.eligible, report.reason, report.candidate_metrics) ``` -For MAE/RMSE a lower value wins; for R2, accuracy and F1 a higher value -wins. `quality_threshold` is an upper limit for error metrics and a lower -limit for score metrics. A tie does not qualify. If no champion exists, pass -`None` and inspect the candidate report; this never creates a champion. +The report contains all finite metrics available for the task and labeled +holdout. Regression includes MAE, MSE, RMSE, R2, MAPE and explained variance. +Classification includes accuracy, balanced accuracy, weighted precision/recall/F1, +Matthews correlation, binary precision/recall/F1 and, when defined, log loss, +ROC-AUC and PR-AUC variants. Optional metrics such as geometric-mean score may +be absent when their dependency or the required label distribution is unavailable. +Probability metrics use the saved model's class order; hard-label metrics use +its effective prediction thresholds. + +Choose one primary metric before evaluating candidates. Error metrics +(MAE/MSE/RMSE/MAPE/log loss) minimize; the other selectable scores maximize. +`quality_threshold` is an upper limit for error metrics and a lower limit for +scores. A tie does not qualify. If no champion exists, pass `None` and +inspect the candidate report; this never creates a champion. The report is +read-only; the caller explicitly logs the desired numeric metrics to its +MLflow run. Unlabeled production predictions cannot produce supervised +quality metrics until their true labels arrive. Evaluation does not move aliases, publish predictions or deploy endpoints. Explicit version-checked promotion and rollback are the next SM-22b task; monthly candidate training follows in SM-28a before Bundle generation. diff --git a/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md b/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md index ef0f01e41..09f20eca7 100644 --- a/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md +++ b/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md @@ -9,15 +9,17 @@ validated before closing the platform gate. No Bundle or alias mutation was run. versions and their checked local pipeline digests. It scores both versions on the same bounded pandas/Polars labeled frame and reports dataset ID, row count, model and code identities, metrics, improvement, quality threshold and decision reason. -- RMSE/MAE minimize; R2, accuracy and F1 maximize. Ties cannot qualify. A +- Core evaluation metrics now supply the full finite held-out metric set. Error + metrics minimize and scores maximize. Ties cannot qualify. A missing champion yields a candidate report without implicit initialization. Task and class-label contracts must agree; non-finite metrics fail closed. -- Held-out metric calculation moved from the Databricks adapter to a shared - inference module. The old Databricks import remains available for callers. +- Held-out evaluation reuses Core model metric calculators with the saved + pipeline predictions and class-ordered probabilities. The old Databricks + import remains available for callers. ## Evidence -The isolated MLflow 3.16.1 environment passed 25 focused tests with one +The isolated MLflow 3.16.1 environment passed 65 related tests with one optional Spark skip. The tests cover pandas regression, Polars classification, minimum-improvement and absolute quality gates, malformed references, access denial and a real local SQLite MLflow registry with two registered local pipeline diff --git a/skyulf-core/skyulf/inference/local_evaluation.py b/skyulf-core/skyulf/inference/local_evaluation.py index a58b540d7..d27928d40 100644 --- a/skyulf-core/skyulf/inference/local_evaluation.py +++ b/skyulf-core/skyulf/inference/local_evaluation.py @@ -1,17 +1,13 @@ """Held-out metrics for a saved pandas/Polars local pipeline.""" -import math - import pandas as pd import polars as pl -from sklearn.metrics import ( - accuracy_score, - f1_score, - mean_absolute_error, - mean_squared_error, - r2_score, -) +from ..modeling._evaluation.common import sanitize_metrics +from ..modeling._evaluation.metrics import ( + calculate_classification_metrics, + calculate_regression_metrics, +) from .local_pipeline import LocalPipelineArtifact, predict_local_pipeline @@ -40,21 +36,29 @@ def evaluate_local_holdout( heldout.select(columns) if isinstance(heldout, pl.DataFrame) else heldout.loc[:, columns] ) actual = heldout[target_column].to_numpy() - predicted = predict_local_pipeline(features, artifact)["prediction"].to_numpy() - if artifact.manifest.task == "regression": - return { - "heldout_mae": float(mean_absolute_error(actual, predicted)), - "heldout_rmse": float(math.sqrt(mean_squared_error(actual, predicted))), - "heldout_r2": float(r2_score(actual, predicted)), - } - metrics = { - "heldout_accuracy": float(accuracy_score(actual, predicted)), - "heldout_f1_weighted": float( - f1_score(actual, predicted, average="weighted", zero_division=0) - ), + predictions = predict_local_pipeline(features, artifact) + estimator = artifact.pipeline.model_estimator + if estimator is None: + raise ValueError("Local artifact has no fitted model.") + model = estimator._unwrap_tuned_model() + scoring_args = { + "X_np": features.to_numpy(), + "y_np": actual, + "predictions": predictions["prediction"].to_numpy(), } - if len(artifact.manifest.classes) == 2: - metrics["heldout_f1"] = float( - f1_score(actual, predicted, pos_label=artifact.manifest.classes[1], zero_division=0) + if artifact.manifest.task == "regression": + raw_metrics = calculate_regression_metrics( + model, features, heldout[target_column], **scoring_args + ) + else: + probability_columns = [ + f"probability_{position}" for position in range(len(artifact.manifest.classes)) + ] + raw_metrics = calculate_classification_metrics( + model, + features, + heldout[target_column], + proba=predictions.loc[:, probability_columns].to_numpy(), + **scoring_args, ) - return metrics + return {f"heldout_{name}": value for name, value in sanitize_metrics(raw_metrics).items()} diff --git a/skyulf-core/skyulf/integrations/mlflow/validation.py b/skyulf-core/skyulf/integrations/mlflow/validation.py index 3ade89831..a086a4510 100644 --- a/skyulf-core/skyulf/integrations/mlflow/validation.py +++ b/skyulf-core/skyulf/integrations/mlflow/validation.py @@ -13,10 +13,43 @@ from ...inference.local_pipeline import LocalPipelineArtifact from .registry import ResolvedModel, load_registered_local_pipeline -_MINIMIZE = {"heldout_mae", "heldout_rmse"} -_MAXIMIZE = {"heldout_r2", "heldout_accuracy", "heldout_f1_weighted", "heldout_f1"} -_REGRESSION = _MINIMIZE | {"heldout_r2"} -_CLASSIFICATION = _MAXIMIZE - {"heldout_r2"} +_REGRESSION = { + "heldout_mae", + "heldout_mse", + "heldout_rmse", + "heldout_r2", + "heldout_mape", + "heldout_explained_variance", +} +_CLASSIFICATION = { + "heldout_accuracy", + "heldout_balanced_accuracy", + "heldout_precision_weighted", + "heldout_recall_weighted", + "heldout_f1_weighted", + "heldout_matthews_corrcoef", + "heldout_precision", + "heldout_recall", + "heldout_f1", + "heldout_g_score", + "heldout_log_loss", + "heldout_roc_auc", + "heldout_pr_auc", + "heldout_roc_auc_ovr_weighted", + "heldout_roc_auc_weighted", + "heldout_roc_auc_ovr", + "heldout_roc_auc_ovo", + "heldout_roc_auc_ovo_weighted", + "heldout_pr_auc_weighted", +} +_MINIMIZE = { + "heldout_mae", + "heldout_mse", + "heldout_rmse", + "heldout_mape", + "heldout_log_loss", +} +_MAXIMIZE = (_REGRESSION | _CLASSIFICATION) - _MINIMIZE @dataclass(frozen=True, slots=True) diff --git a/skyulf-core/skyulf/modeling/_evaluation/metrics.py b/skyulf-core/skyulf/modeling/_evaluation/metrics.py index c6155cde4..346bae712 100644 --- a/skyulf-core/skyulf/modeling/_evaluation/metrics.py +++ b/skyulf-core/skyulf/modeling/_evaluation/metrics.py @@ -156,7 +156,7 @@ def _select_silhouette_sample_indices( def calculate_classification_metrics( model: Any, - X: pd.DataFrame | SkyulfDataFrame, + X: pd.DataFrame | pl.DataFrame | SkyulfDataFrame, y: pd.Series | Any, *, X_np: Any = None, @@ -396,7 +396,7 @@ def _add_probability_based_metrics( def calculate_regression_metrics( model: Any, - X: pd.DataFrame | SkyulfDataFrame, + X: pd.DataFrame | pl.DataFrame | SkyulfDataFrame, y: pd.Series | Any, *, X_np: Any = None, diff --git a/skyulf-core/tests/integrations/test_databricks_local_batch.py b/skyulf-core/tests/integrations/test_databricks_local_batch.py index 394f5a0a3..fc041bab2 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_batch.py +++ b/skyulf-core/tests/integrations/test_databricks_local_batch.py @@ -186,10 +186,20 @@ def test_heldout_regression_metrics_use_saved_pipeline_and_200_test_rows(tmp_pat metrics = local_batch.evaluate_local_holdout(artifact, native[800:], target_column="target") - assert set(metrics) == {"heldout_mae", "heldout_rmse", "heldout_r2"} + assert set(metrics) == { + "heldout_mae", + "heldout_mse", + "heldout_rmse", + "heldout_r2", + "heldout_mape", + "heldout_explained_variance", + } assert metrics["heldout_mae"] == pytest.approx(0.0, abs=1e-8) assert metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) assert metrics["heldout_r2"] == pytest.approx(1.0) + assert metrics["heldout_mse"] == pytest.approx(0.0, abs=1e-8) + assert metrics["heldout_mape"] == pytest.approx(0.0, abs=1e-8) + assert metrics["heldout_explained_variance"] == pytest.approx(1.0) @pytest.mark.parametrize("engine", ["pandas", "polars"]) @@ -217,6 +227,11 @@ def test_heldout_classification_metrics_use_reserved_labels(tmp_path, engine) -> assert metrics["heldout_accuracy"] == pytest.approx(0.8) assert metrics["heldout_f1"] == pytest.approx(0.8) assert metrics["heldout_f1_weighted"] == pytest.approx(0.8) + assert metrics["heldout_balanced_accuracy"] == pytest.approx(0.8) + assert metrics["heldout_precision"] == pytest.approx(0.8) + assert metrics["heldout_recall"] == pytest.approx(0.8) + assert metrics["heldout_roc_auc"] > 0.5 + assert np.isfinite(metrics["heldout_log_loss"]) and metrics["heldout_log_loss"] > 0.0 def test_scoring_rejects_changed_identity_and_raw_column_order_before_read(tmp_path) -> None: diff --git a/skyulf-core/tests/integrations/test_mlflow_validation.py b/skyulf-core/tests/integrations/test_mlflow_validation.py index 35fc9b18c..a41d67a3a 100644 --- a/skyulf-core/tests/integrations/test_mlflow_validation.py +++ b/skyulf-core/tests/integrations/test_mlflow_validation.py @@ -182,8 +182,11 @@ def test_invalid_comparison_fails_before_model_load( ) -def test_polars_classification_comparison_maximizes_accuracy(tmp_path, monkeypatch) -> None: - """A candidate with correct class semantics should beat a biased champion.""" +@pytest.mark.parametrize("metric", ["heldout_accuracy", "heldout_roc_auc", "heldout_log_loss"]) +def test_polars_classification_comparison_selects_core_metrics( + tmp_path, monkeypatch, metric +) -> None: + """A candidate must beat a biased champion in the chosen metric direction.""" import polars as pl x = np.r_[np.arange(-12, 0), np.arange(1, 13)].astype("float64") @@ -221,17 +224,21 @@ def test_polars_classification_comparison_maximizes_accuracy(tmp_path, monkeypat heldout, target_column="target", dataset_id="workspace.test.labels@6/class-holdout", - metric="heldout_accuracy", + metric=metric, min_improvement=0.2, quality_threshold=0.9, max_rows=10, max_bytes=10_000, ) - assert report.metric_direction == "maximize" - assert report.candidate_metrics["heldout_accuracy"] == pytest.approx(1.0) assert report.champion_metrics is not None - assert report.champion_metrics["heldout_accuracy"] == pytest.approx(0.0) + if metric == "heldout_log_loss": + assert report.metric_direction == "minimize" + assert report.candidate_metrics[metric] < report.champion_metrics[metric] + else: + assert report.metric_direction == "maximize" + assert report.candidate_metrics[metric] == pytest.approx(1.0) + assert report.champion_metrics[metric] == pytest.approx(0.0) assert report.eligible is True From 68d90c0a19902179955c050fa66f85e8fd6ab7f8 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 21:07:45 +0300 Subject: [PATCH 39/85] test: validate held-out metrics on Databricks Signed-off-by: flyingriverhorse --- .../06-prebundle-model-lifecycle-plan.md | 4 +- .../16-sm22a-local-validation-report.md | 5 +- .../17-sm22a-live-metrics-report.md | 65 ++++++ initiatives/spark_and_mlflow/HANDOFF.md | 14 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 12 +- .../databricks_local_sm22_metrics_live.py | 212 ++++++++++++++++++ 6 files changed, 297 insertions(+), 15 deletions(-) create mode 100644 initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md create mode 100644 skyulf-core/examples/databricks_local_sm22_metrics_live.py diff --git a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md index b2b57e4f9..8654e13fc 100644 --- a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md +++ b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md @@ -29,7 +29,9 @@ - [x] Keep report creation read-only and deterministic; test that no MLflow alias changes. - [x] Run focused tests, Ruff, ty and the existing local MLflow/holdout suites. -Local implementation and tests are complete; the isolated Unity Catalog gate is still pending. +Local implementation and tests are complete. The isolated Unity Catalog gate +passed with four pandas/Polars metric runs and one pinned model comparison; +see the [live report](17-sm22a-live-metrics-report.md). No alias was mutated. ## Alias concurrency decision diff --git a/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md b/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md index 09f20eca7..a922b9490 100644 --- a/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md +++ b/initiatives/spark_and_mlflow/16-sm22a-local-validation-report.md @@ -1,7 +1,8 @@ # SM-22a local candidate/champion validation -Status: LOCAL VERIFIED, 2026-09-23. Unity Catalog comparison remains to be -validated before closing the platform gate. No Bundle or alias mutation was run. +Status: LOCAL VERIFIED, 2026-09-23. The subsequent isolated Unity Catalog +comparison is documented in the [live report](17-sm22a-live-metrics-report.md). +No Bundle or alias mutation was run. ## Delivered diff --git a/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md b/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md new file mode 100644 index 000000000..767ec5142 --- /dev/null +++ b/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md @@ -0,0 +1,65 @@ +# SM-22a Databricks metrics and comparison validation + +Status: LIVE VERIFIED, 2026-09-23. This is an isolated, bounded serverless +validation of Skyulf Core held-out metrics, MLflow tracking, and a pinned +Unity Catalog model comparison. It does not promote an alias. + +## Execution + +- Workspace profile: `skyulf`; existing test schema: + `workspace.skyulf_sm24a_20260923`. +- [Serverless job run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/338095925832270/run/402693440245633): + parent run `402693440245633`, task run `779149119285800`, + `TERMINATED / SUCCESS`, one attempt, 15-minute task timeout. +- Notebook: `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm22_metrics_r1/live_metrics`; + source: `skyulf-core/examples/databricks_local_sm22_metrics_live.py`. +- Wheel: `skyulf_core-0.9.0-py3-none-any.whl`, SHA-256 + `B8ACD810FAF0AC07E1A066B4E186F485CFD4B0A60DADDF7C24F45BDD2C39050C`. +- Runtime: skyulf-core 0.9.0, MLflow 3.16.1, pandas 2.2.3, + Polars 1.44.2, scikit-learn 1.6.1. + +The notebook fitted actual Skyulf local pipeline artifacts for each engine +and task, evaluated held-out data through `evaluate_local_holdout`, logged +all finite metrics, then read each MLflow run back and compared every value. +An independent `databricks experiments get-run` check confirmed all four +runs were `FINISHED` and retained the metric keys shown below. + +| Case | MLflow run ID | Persisted metrics | Selected values | +| --- | --- | ---: | --- | +| pandas regression | `546df4fed4d443999990707df7255335` | 6 | MAE `4.54747e-14`, RMSE `5.08423e-14`, R2 `1.0` | +| Polars regression | `dc5cdc23ad424e61b143d2d0b9410697` | 6 | MAE `4.54747e-14`, RMSE `5.08423e-14`, R2 `1.0` | +| pandas classification | `856b7d03794143b78c6f533374e938e2` | 12 | accuracy `1.0`, F1 `1.0`, log loss `0.0969631`, ROC AUC `1.0` | +| Polars classification | `c703eb554cef48bf914d8ce082d0d9b7` | 12 | accuracy `1.0`, F1 `1.0`, log loss `0.0969631`, ROC AUC `1.0` | + +The six regression keys were `heldout_mae`, `heldout_mse`, `heldout_rmse`, +`heldout_r2`, `heldout_mape`, and `heldout_explained_variance`. The twelve +classification keys were `heldout_accuracy`, `heldout_balanced_accuracy`, +`heldout_precision_weighted`, `heldout_recall_weighted`, +`heldout_f1_weighted`, `heldout_matthews_corrcoef`, `heldout_precision`, +`heldout_recall`, `heldout_f1`, `heldout_log_loss`, `heldout_roc_auc`, and +`heldout_pr_auc`. + +## Pinned Unity Catalog comparison + +The test registered two real local pipeline packages in +`workspace.skyulf_sm24a_20260923.skyulf_sm22_metrics_r1` and resolved their +concrete versions. Version 1 was the reference model, trained with a deliberate +target offset; version 2 was the candidate. On the same synthetic labeled +holdout, candidate `heldout_mse = 2.58494e-27` versus reference +`heldout_mse = 100.00000000000088`. With `min_improvement=1.0` and +`quality_threshold=1.0`, the report returned `eligible=true`. The reference +model's MLflow run was `3fcb9236b2434eb1bec2eb42af8b1d45`. CLI registry +checks independently found the two model versions; version 2 was `READY`. + +"Reference" or "champion" here means a pinned comparison version. No +`@champion` alias was created, changed, or tested. SM-22b owns alias promotion +and rollback. + +## Boundary + +The data are deterministic synthetic frames, not a production dataset. This +proves finite metric calculation and MLflow persistence for these four cases +on one Databricks serverless runtime, plus one pinned UC comparison. It does +not prove performance on other data, alias concurrency, Delta admission, +prediction-table writes, or a Bundle. The experiment, five runs, two UC model +versions, uploaded notebook and wheel remain in the isolated test area. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index c6265c68e..d6073ccb6 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -12,15 +12,17 @@ The revised order completes SM-22a/b comparison and controlled promotion, then SM-28a label-aware challenger training before SM-20a. SM-28b adds the optional monthly schedule after the Bundle; SM-27 remains later. Target release: 0.9.0. Branch: `090`. -SM-22a now has a locally verified, read-only comparison API; see -[its report](16-sm22a-local-validation-report.md). The isolated UC gate is -pending, and SM-22b has not started. Alias writes lack native compare-and-swap, -so SM-22b needs shared admission and restricted writers before promotion. +SM-22a has a locally verified, read-only comparison API and passed its +isolated Databricks metrics and UC comparison gate; see the +[local report](16-sm22a-local-validation-report.md) and +[live report](17-sm22a-live-metrics-report.md). SM-22b is next and has not +started. Alias writes lack native compare-and-swap, so SM-22b needs shared +admission and restricted writers before promotion. ## Starting point -- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25 and SM-26 are complete. - Start SM-22a from [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). +- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26 and SM-22a are complete. + Start SM-22b from [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). SM-20a follows the verified SM-22a/b and SM-28a services. SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 0236a6bda..24b04e587 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,14 +1,14 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a active before SM-20a. Target: 0.9.0.** -Next deliverable: candidate/champion validation, controlled promotion and -label-aware retraining services, then a working local-engine Bundle. Spark +Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a complete; SM-22b next before SM-20a. Target: 0.9.0.** +Next deliverable: controlled promotion and label-aware retraining services, +then a working local-engine Bundle. Spark expansion follows that Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-22a. +and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-22b. The [SM-20 Bundle plan](05-sm20-bundle-plan.md) remains the packaging gate. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). @@ -46,8 +46,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-26 | Local pandas/Polars pipeline MLflow packaging | SM-16, existing local persistence | DONE | Fitted FE/model/engine, schema and thresholds preserved; MLflow 3.16.1 isolated-process parity; Spark/HTTP scopes rejected | | SM-25 | Local-first config / SDK preflight | SM-26 | DONE | Immutable local config; pinned artifact load, bounded frame and actionable preflight; no node/model allowlist | | SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | -| SM-22a | Pinned candidate/champion validation | Current evaluation/registry | ACTIVE | Local comparison/report passed; isolated UC gate pending; [evidence](16-sm22a-local-validation-report.md) | -| SM-22b | Explicit promotion and rollback | SM-22a | WAIT | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests | +| SM-22a | Pinned candidate/champion validation | Current evaluation/registry | DONE | Local comparison/report and isolated UC metrics gate passed; [local evidence](16-sm22a-local-validation-report.md), [live evidence](17-sm22a-live-metrics-report.md) | +| SM-22b | Explicit promotion and rollback | SM-22a | READY | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests | | SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-24a | WAIT | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | | SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-28a | WAIT | Package tested train/compare/promote/incremental-score services; validate, deploy and run | | SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | WAIT | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | diff --git a/skyulf-core/examples/databricks_local_sm22_metrics_live.py b/skyulf-core/examples/databricks_local_sm22_metrics_live.py new file mode 100644 index 000000000..5d02e5606 --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm22_metrics_live.py @@ -0,0 +1,212 @@ +# Databricks notebook source +"""One-time Databricks validation of Core-held-out metrics and UC comparison.""" + +from __future__ import annotations + +import json +import tempfile +from importlib.metadata import version +from pathlib import Path +from typing import Any + +import mlflow # ty: ignore[unresolved-import] +import numpy as np +import pandas as pd +import polars as pl + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_evaluation import evaluate_local_holdout +from skyulf.integrations.databricks.local_batch import fit_local_workflow +from skyulf.integrations.mlflow.local_model import log_local_model +from skyulf.integrations.mlflow.registry import register_model, resolve_model +from skyulf.integrations.mlflow.validation import compare_registered_local_models + +EXPERIMENT = "/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm22_metrics_r1_experiment" +MODEL_NAME = "workspace.skyulf_sm24a_20260923.skyulf_sm22_metrics_r1" +REGRESSION_METRICS = { + "heldout_mae", + "heldout_mse", + "heldout_rmse", + "heldout_r2", + "heldout_mape", + "heldout_explained_variance", +} +CLASSIFICATION_METRICS = { + "heldout_accuracy", + "heldout_balanced_accuracy", + "heldout_precision_weighted", + "heldout_recall_weighted", + "heldout_f1_weighted", + "heldout_matthews_corrcoef", + "heldout_precision", + "heldout_recall", + "heldout_f1", + "heldout_log_loss", + "heldout_roc_auc", + "heldout_pr_auc", +} + + +def _native(frame: pd.DataFrame, engine: str) -> pd.DataFrame | pl.DataFrame: + """Use the requested local engine without changing row order.""" + return pl.from_pandas(frame) if engine == "polars" else frame + + +def _fit( + path: Path, + engine: str, + task: str, + train: pd.DataFrame, + heldout: pd.DataFrame, +): + """Fit and reload a real Skyulf local artifact.""" + model_type = "linear_regression" if task == "regression" else "logistic_regression" + return fit_local_workflow( + {"preprocessing": [], "modeling": {"type": model_type}}, + SplitDataset(train=_native(train, engine), test=_native(heldout, engine)), + target_column="target", + artifact_path=path, + max_rows=200, + max_bytes=200_000, + ) + + +def _log_metrics( + name: str, metrics: dict[str, float], *, artifact_path: Path | None = None +) -> tuple[str, str | None]: + """Log every finite metric and optionally package the fitted model.""" + if not metrics or not all(np.isfinite(value) for value in metrics.values()): + raise AssertionError(f"{name} produced missing or non-finite metrics") + with mlflow.start_run(run_name=name) as run: + mlflow.log_metrics(metrics) + mlflow.log_params({"validation": "heldout", "case": name}) + model_uri = ( + log_local_model( + artifact_path, + run_id=run.info.run_id, + artifact_path="model", + tracking_uri="databricks", + ) + if artifact_path is not None + else None + ) + run_id = run.info.run_id + recorded = mlflow.MlflowClient(tracking_uri="databricks").get_run(run_id).data.metrics + if not metrics.keys() <= recorded.keys(): + raise AssertionError(f"{name} is missing MLflow metrics") + for key, value in metrics.items(): + if not np.isclose(recorded[key], value): + raise AssertionError(f"{name} changed MLflow metric {key}") + return run_id, model_uri + + +def run() -> dict[str, Any]: + """Exercise four local-engine cases and one pinned UC model comparison.""" + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + mlflow.set_experiment(EXPERIMENT) + report: dict[str, Any] = {"cases": {}, "runtime": {}} + train_x = np.arange(80, dtype="float64") + heldout_x = np.arange(80, 110, dtype="float64") + reg_train = pd.DataFrame({"x": train_x, "target": 3.0 * train_x + 2.0}) + reg_heldout = pd.DataFrame({"x": heldout_x, "target": 3.0 * heldout_x + 2.0}) + class_x = np.r_[np.linspace(-4.0, -0.2, 50), np.linspace(0.2, 4.0, 50)] + class_train = pd.DataFrame({"x": class_x, "target": (class_x > 0).astype("int64")}) + class_test_x = np.r_[np.linspace(-2.0, -0.3, 10), np.linspace(0.3, 2.0, 10)] + class_heldout = pd.DataFrame({"x": class_test_x, "target": (class_test_x > 0).astype("int64")}) + with tempfile.TemporaryDirectory(prefix="skyulf-sm22-live-") as directory: + root = Path(directory) + candidate_uri = None + for engine in ("pandas", "polars"): + for task, train, heldout, required in ( + ("regression", reg_train, reg_heldout, REGRESSION_METRICS), + ("classification", class_train, class_heldout, CLASSIFICATION_METRICS), + ): + case = f"{engine}_{task}" + path = root / case + artifact = _fit(path, engine, task, train, heldout) + metrics = evaluate_local_holdout( + artifact, _native(heldout, engine), target_column="target" + ) + if not required <= metrics.keys(): + raise AssertionError(f"{case} lacks {sorted(required - metrics.keys())}") + run_id, model_uri = _log_metrics( + f"sm22-metrics-{case}", + metrics, + artifact_path=path if case == "pandas_regression" else None, + ) + report["cases"][case] = {"run_id": run_id, "metrics": metrics} + if case == "pandas_regression": + candidate_uri = model_uri + if candidate_uri is None: + raise AssertionError("Candidate model was not packaged.") + champion_train = reg_train.copy() + champion_train["target"] += 10.0 + champion_path = root / "champion" + champion_artifact = _fit(champion_path, "pandas", "regression", champion_train, reg_heldout) + champion_metrics = evaluate_local_holdout( + champion_artifact, reg_heldout, target_column="target" + ) + champion_run_id, champion_uri = _log_metrics( + "sm22-metrics-champion", + champion_metrics, + artifact_path=champion_path, + ) + if champion_uri is None: + raise AssertionError("Champion model was not packaged.") + champion_version = register_model( + champion_uri, MODEL_NAME, tracking_uri="databricks", registry_uri="databricks-uc" + ) + candidate_version = register_model( + candidate_uri, MODEL_NAME, tracking_uri="databricks", registry_uri="databricks-uc" + ) + champion = resolve_model( + MODEL_NAME, + version=champion_version.version, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + candidate = resolve_model( + MODEL_NAME, + version=candidate_version.version, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + comparison = compare_registered_local_models( + candidate, + champion, + reg_heldout, + target_column="target", + dataset_id="synthetic-sm22-metrics-r1/holdout", + metric="heldout_mse", + min_improvement=1.0, + quality_threshold=1.0, + max_rows=100, + max_bytes=100_000, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if not comparison.eligible or comparison.improvement is None: + raise AssertionError(f"UC comparison rejected candidate: {comparison.reason}") + report["comparison"] = { + "model_name": MODEL_NAME, + "candidate_version": candidate.version, + "champion_version": champion.version, + "metric": comparison.metric, + "candidate_mse": comparison.candidate_metrics["heldout_mse"], + "champion_mse": comparison.champion_metrics["heldout_mse"] + if comparison.champion_metrics is not None + else None, + "eligible": comparison.eligible, + "champion_run_id": champion_run_id, + } + report["runtime"] = { + name: version(name) + for name in ("skyulf-core", "mlflow", "pandas", "polars", "scikit-learn") + } + return report + + +runtime_dbutils: Any = globals().get("dbutils") +if runtime_dbutils is not None: + runtime_dbutils.notebook.exit(json.dumps(run(), default=str)) From 66738582f4d78c72976be5dc064f04bafe7003fe Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 21:10:42 +0300 Subject: [PATCH 40/85] chore: remove unnecessary future annotations import Signed-off-by: flyingriverhorse --- skyulf-core/examples/databricks_local_sm22_metrics_live.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/skyulf-core/examples/databricks_local_sm22_metrics_live.py b/skyulf-core/examples/databricks_local_sm22_metrics_live.py index 5d02e5606..78e2e44f8 100644 --- a/skyulf-core/examples/databricks_local_sm22_metrics_live.py +++ b/skyulf-core/examples/databricks_local_sm22_metrics_live.py @@ -1,8 +1,6 @@ # Databricks notebook source """One-time Databricks validation of Core-held-out metrics and UC comparison.""" -from __future__ import annotations - import json import tempfile from importlib.metadata import version From 8452ebd8554ee39ce3d3d65ae860548952de8b1b Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 21:18:10 +0300 Subject: [PATCH 41/85] refactor: show direct SkyulfPipeline fit in Databricks example Signed-off-by: flyingriverhorse --- .../spark_and_mlflow/17-sm22a-live-metrics-report.md | 5 ++++- .../examples/databricks_local_sm22_metrics_live.py | 12 ++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md b/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md index 767ec5142..35d05010b 100644 --- a/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md +++ b/initiatives/spark_and_mlflow/17-sm22a-live-metrics-report.md @@ -12,7 +12,10 @@ Unity Catalog model comparison. It does not promote an alias. parent run `402693440245633`, task run `779149119285800`, `TERMINATED / SUCCESS`, one attempt, 15-minute task timeout. - Notebook: `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm22_metrics_r1/live_metrics`; - source: `skyulf-core/examples/databricks_local_sm22_metrics_live.py`. + uploaded from `skyulf-core/examples/databricks_local_sm22_metrics_live.py` at commit + `68d90c0a`. The current example now calls `SkyulfPipeline.fit` directly; + that refactor passed a local pandas/Polars artifact smoke test but was not + rerun on Databricks. - Wheel: `skyulf_core-0.9.0-py3-none-any.whl`, SHA-256 `B8ACD810FAF0AC07E1A066B4E186F485CFD4B0A60DADDF7C24F45BDD2C39050C`. - Runtime: skyulf-core 0.9.0, MLflow 3.16.1, pandas 2.2.3, diff --git a/skyulf-core/examples/databricks_local_sm22_metrics_live.py b/skyulf-core/examples/databricks_local_sm22_metrics_live.py index 78e2e44f8..d3e12aeb9 100644 --- a/skyulf-core/examples/databricks_local_sm22_metrics_live.py +++ b/skyulf-core/examples/databricks_local_sm22_metrics_live.py @@ -14,10 +14,11 @@ from skyulf.data.dataset import SplitDataset from skyulf.inference.local_evaluation import evaluate_local_holdout -from skyulf.integrations.databricks.local_batch import fit_local_workflow +from skyulf.inference.local_pipeline import load_local_pipeline, save_local_pipeline from skyulf.integrations.mlflow.local_model import log_local_model from skyulf.integrations.mlflow.registry import register_model, resolve_model from skyulf.integrations.mlflow.validation import compare_registered_local_models +from skyulf.pipeline import SkyulfPipeline EXPERIMENT = "/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm22_metrics_r1_experiment" MODEL_NAME = "workspace.skyulf_sm24a_20260923.skyulf_sm22_metrics_r1" @@ -59,14 +60,13 @@ def _fit( ): """Fit and reload a real Skyulf local artifact.""" model_type = "linear_regression" if task == "regression" else "logistic_regression" - return fit_local_workflow( - {"preprocessing": [], "modeling": {"type": model_type}}, + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": model_type}}) + pipeline.fit( SplitDataset(train=_native(train, engine), test=_native(heldout, engine)), target_column="target", - artifact_path=path, - max_rows=200, - max_bytes=200_000, ) + save_local_pipeline(pipeline, path) + return load_local_pipeline(path) def _log_metrics( From ea68efb28c245cd06629efdcdc1910c2ca5f4a49 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 22:22:52 +0300 Subject: [PATCH 42/85] feat: guard MLflow champion promotion and rollback Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 8 +- docs/user_guide/databricks_batch.md | 11 +- docs/user_guide/mlflow_registry.md | 85 +++- .../06-prebundle-model-lifecycle-plan.md | 6 +- .../18-sm22b-live-validation-report.md | 65 +++ initiatives/spark_and_mlflow/HANDOFF.md | 11 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 8 +- .../examples/databricks_sm22b_alias_live.py | 120 ++++++ .../databricks_sm22b_restricted_live.py | 36 ++ .../skyulf/integrations/mlflow/promotion.py | 374 ++++++++++++++++++ .../integrations/test_mlflow_promotion.py | 233 +++++++++++ 11 files changed, 938 insertions(+), 19 deletions(-) create mode 100644 initiatives/spark_and_mlflow/18-sm22b-live-validation-report.md create mode 100644 skyulf-core/examples/databricks_sm22b_alias_live.py create mode 100644 skyulf-core/examples/databricks_sm22b_restricted_live.py create mode 100644 skyulf-core/skyulf/integrations/mlflow/promotion.py create mode 100644 skyulf-core/tests/integrations/test_mlflow_promotion.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index f727eefd5..96978f1dc 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -28,12 +28,18 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added +- Explicit MLflow champion promotion and rollback revalidate a pinned local + model comparison, acquire shared admission, check the expected alias version + and record durable transition receipts. Local registry tests and an isolated + Unity Catalog run verified promotion, conflict rejection, rollback and a + restricted principal's alias-write denial. + - Read-only local MLflow candidate/champion comparison on one bounded labeled holdout reports pinned model/data identities, held-out metrics, improvement and a directional quality gate. Held-out evaluation now reuses Core's full model metric calculators, including probability-based classification metrics when defined, rather than maintaining separate formulas. It never moves an alias; - controlled promotion and label-aware retraining remain separate pre-Bundle tasks. + label-aware retraining remains a separate pre-Bundle task. - Local-engine Databricks SDK configuration and preflight for bounded pandas/Polars batches. It selects trusted local or portable artifacts, resolves MLflow aliases once to concrete versions, checks metadata and diff --git a/docs/user_guide/databricks_batch.md b/docs/user_guide/databricks_batch.md index 362114499..1a0b53ad5 100644 --- a/docs/user_guide/databricks_batch.md +++ b/docs/user_guide/databricks_batch.md @@ -138,16 +138,19 @@ target_id = spark.sql( "DESCRIBE DETAIL analytics.customer_predictions" ).first()["id"] # One-time provisioning only; do not overwrite an existing authority. -spark.createDataFrame( - [(target_id, None)], "target_id string, owner string" -).write.format("delta").mode("errorifexists").saveAsTable( - "analytics.customer_predictions_admission" +spark.sql( + "CREATE TABLE analytics.customer_predictions_admission USING DELTA AS " + f"SELECT '{target_id}' AS target_id, CAST(NULL AS STRING) AS owner" ) admission = DeltaTableAdmission(spark, "analytics.customer_predictions_admission") # Supply admission=admission to run_batch(...). ``` +The plain CREATE TABLE statement fails if the authority already exists; it does +not overwrite an existing control row. Serverless Spark Connect rejects the +DataFrameWriter errorifexists save mode for this provisioning step. + The provider requires exactly one row with the immutable output table ID and a nullable string owner. It uses a conditional Delta UPDATE to claim ownership, checks the committed token before entering, and clears only its own token after diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 720e04934..db41636a5 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -171,8 +171,89 @@ read-only; the caller explicitly logs the desired numeric metrics to its MLflow run. Unlabeled production predictions cannot produce supervised quality metrics until their true labels arrive. Evaluation does not move aliases, publish predictions or deploy endpoints. -Explicit version-checked promotion and rollback are the next SM-22b task; -monthly candidate training follows in SM-28a before Bundle generation. +Promotion is a separate, explicit operation. SM-28a monthly candidate training +follows before Bundle generation. + +## Promote and roll back a local pipeline + +The promote_candidate function re-resolves both concrete model versions and +re-evaluates the same bounded labeled holdout. It rejects a changed comparison +report, an ineligible candidate, a missing champion alias, or a stale expected +champion version. The caller must pin the holdout's source snapshot externally; +dataset_id alone is not proof of the underlying data. There is no implicit +first-champion initialization. + +Alias writes have no expected-prior-version parameter. Every alias writer +must use the same non-expiring admission authority, and registry write +permissions must be restricted to that controlled path. A local development +store can use LocalAliasAdmission with a shared lock directory: + +~~~python +from skyulf.integrations.mlflow.promotion import ( + LocalAliasAdmission, + promote_candidate, + rollback_promotion, +) + +admission = LocalAliasAdmission("/var/lib/skyulf/alias-locks") +receipt = promote_candidate( + report, + heldout, + target_column="target", + expected_champion_version="1", + admission=admission, + max_rows=10_000, + max_bytes=20_000_000, + tracking_uri="sqlite:///tracking.db", + registry_uri="sqlite:///registry.db", +) +reversal = rollback_promotion( + receipt, + expected_current_version=receipt.new_version, + admission=admission, + tracking_uri="sqlite:///tracking.db", + registry_uri="sqlite:///registry.db", +) +~~~ + +For Unity Catalog, use DeltaAliasAdmission(spark, control_table) with a +separate, preprovisioned Delta control table containing exactly one row: +target_id = alias_resource_id(model_name, "champion") and nullable owner = NULL. +Provision it once with a plain CREATE TABLE statement so an existing authority +cannot be overwritten: + +~~~python +from skyulf.integrations.mlflow.promotion import DeltaAliasAdmission, alias_resource_id + +key = alias_resource_id("catalog.schema.customer_risk", "champion") +spark.sql( + "CREATE TABLE catalog.schema.customer_risk_alias_admission USING DELTA AS " + f"SELECT '{key}' AS target_id, CAST(NULL AS STRING) AS owner" +) +admission = DeltaAliasAdmission( + spark, "catalog.schema.customer_risk_alias_admission" +) +~~~ + +All participating promotion and rollback jobs must point to that same table. +Do not use the predictions-table admission row for aliases. Local file locks +are rejected when the registry URI is databricks-uc. + +The transition writes a prepared model-version tag before changing the alias, +then verifies the new alias, writes a committed event tag and an active-event +registered-model tag. The returned receipt names both versions and the event +ID. Rollback verifies the committed promotion event and refuses a later event, +even if it happens to select the same model version. If the alias write or +receipt update has an uncertain outcome, AliasOutcomeUnknownError includes +the event ID: inspect the alias and tags before retrying. A prepared tag is +not proof that promotion completed. Registry tags are audit records for +controlled writers, not tamper-proof authorization tokens. +The event tag key uses underscores, and its compact value stays within Unity +Catalog's 256-byte tag-value limit. + +The lock protects only participating jobs. A principal with direct registry +write permission can bypass it. A crashed Delta admission owner does not +expire; clear it only after proving the original job cannot publish. Only load trusted registry artifacts: bundle loading deserializes pickle, and digest matching is an identity check, not authentication of an unknown producer. diff --git a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md index 8654e13fc..37bb53a17 100644 --- a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md +++ b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md @@ -55,9 +55,9 @@ operational limitation and must not be described as race-safe. The promotion path must revalidate the pinned model identities and decision; an in-memory comparison report is not an authorization token and its metric dictionaries can be changed by a caller. -- [ ] Write failing tests for normal promotion, stale alias, missing champion, access denial, no implicit first champion and rollback conflicts. -- [ ] Implement explicit version-checked operations without changing the tracking run or inference code path. -- [ ] Verify with a disposable local MLflow registry; perform isolated UC permission/conflict validation before marking SM-22b done. +- [x] Write failing tests for normal promotion, stale alias, missing champion, access denial, no implicit first champion and rollback conflicts. +- [x] Implement explicit version-checked operations without changing the tracking run or inference code path. +- [x] Verify with a disposable local MLflow registry and an isolated UC permission/conflict run; see [live evidence](18-sm22b-live-validation-report.md). ### Task 3: SM-28a label-aware retraining workflow diff --git a/initiatives/spark_and_mlflow/18-sm22b-live-validation-report.md b/initiatives/spark_and_mlflow/18-sm22b-live-validation-report.md new file mode 100644 index 000000000..851f9b370 --- /dev/null +++ b/initiatives/spark_and_mlflow/18-sm22b-live-validation-report.md @@ -0,0 +1,65 @@ +# SM-22b isolated validation — 2026-09-23 + +SM-22b adds explicit, version-checked MLflow champion promotion and rollback. +It re-evaluates the supplied comparison against concrete registered versions, +uses one shared non-expiring admission, records a prepared/committed receipt, +and treats an uncertain alias write as an operator-reconciliation case. It +does not train a candidate or promote automatically. + +## Local gate + +The focused MLflow suite passed **40 tests** in the isolated MLflow 3.16.1 +environment (promotion, comparison, registry and local model packaging). +Promotion cases use a real SQLite MLflow registry and cover normal promotion +and rollback, forged reports, stale and missing champion aliases, admission +contention, access denial, uncertain write response and stale rollback receipts. +Ruff, formatting and ty passed on the new Python files. + +## Unity Catalog gate + +The selected `skyulf` profile points to the previously approved Databricks +workspace. Only disposable resources in +`workspace.skyulf_sm24a_20260923` were used: + +- Model: `skyulf_sm22b_promotion_r1`, with existing local-pipeline package + versions 1 (reference) and 2 (candidate). +- Alias: `@champion`, initialized explicitly to version 1 for this test. +- Delta admission table: `skyulf_sm22b_alias_admission_r1`, with one stable + alias key and nullable owner. +- Notebook folder: + `/Workspace/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm22b_alias_r1`. + The successful run loaded wheel SHA-256 + `E6F13F4DD3F0D090A1B986FA4B5C0D710257BFD0637BA9D42C423ACD46A20AED`. + +[Final-code owner run 73594561805168](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/702249165139866/run/73594561805168) +completed SUCCESS. On the same labeled holdout, candidate MSE was +`2.5849394142282116e-27` versus reference MSE `100.00000000000088`. +The run rejected a second admission holder, promoted version 2 (event +`e9be7c187a114c41afb21e79284bd3e9`), and rolled back to version 1 +(event `c74b6ca99c4b462a9401e9991c61d38e`). The final alias was version 1. The earlier r4 owner run also passed, but r5 used the exact final tag names and admission guard. + +The existing restricted test service principal +`skyulf-sm16-restricted-20260922` received only `USE_SCHEMA` on the test +schema and `EXECUTE` on this test model. It has no model ownership or registry +write grant. [Restricted run 821722911076530](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1033450117407968/run/821722911076530) +completed SUCCESS: it read champion version 1, its attempt to set champion to +version 2 returned `PERMISSION_DENIED`, and a second read still returned 1. +No credential was created or copied. + +Three earlier isolated owner attempts failed before promotion: serverless +Spark rejected `DataFrameWriter.mode("errorifexists")` for control-table +provisioning; Unity Catalog rejected dots in model-version tag keys; then it +rejected a receipt tag value over 256 bytes. The final implementation uses +`CREATE TABLE ... USING DELTA AS SELECT`, underscore tag keys and a bounded +compact receipt value. Runs `245964031922258`, `1102712691086932` and +`111298932154094` remain failed in the job history and are not counted as +passing gates. + +## Operational boundary + +All promotion/rollback writers must share the same admission row, and direct +alias writers must be denied by Unity Catalog permissions. The registry alias +API does not offer compare-and-swap. A bypass writer or a crashed owner still +requires operator inspection; a prepared event alone does not prove completion. +The labeled holdout snapshot must be pinned by the caller. SM-28a adds the +label-aware candidate-training workflow; no Bundle was created here. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index d6073ccb6..d86fe884b 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -15,14 +15,15 @@ optional monthly schedule after the Bundle; SM-27 remains later. Target release: SM-22a has a locally verified, read-only comparison API and passed its isolated Databricks metrics and UC comparison gate; see the [local report](16-sm22a-local-validation-report.md) and -[live report](17-sm22a-live-metrics-report.md). SM-22b is next and has not -started. Alias writes lack native compare-and-swap, so SM-22b needs shared -admission and restricted writers before promotion. +[live report](17-sm22a-live-metrics-report.md). SM-22b has explicit +version-checked promotion and rollback with shared admission. Its isolated +UC promotion, conflict, rollback and restricted-principal denial passed; see +[live evidence](18-sm22b-live-validation-report.md). SM-28a is next. ## Starting point -- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26 and SM-22a are complete. - Start SM-22b from [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). +- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26 and SM-22a/b are complete. + Start SM-28a from [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). SM-20a follows the verified SM-22a/b and SM-28a services. SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 24b04e587..318ce11d0 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a complete; SM-22b next before SM-20a. Target: 0.9.0.** +Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a/b complete; SM-28a next before SM-20a. Target: 0.9.0.** Next deliverable: controlled promotion and label-aware retraining services, then a working local-engine Bundle. Spark expansion follows that Bundle. SM-15L @@ -8,7 +8,7 @@ provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-22b. +and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-28a. The [SM-20 Bundle plan](05-sm20-bundle-plan.md) remains the packaging gate. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). @@ -47,8 +47,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-25 | Local-first config / SDK preflight | SM-26 | DONE | Immutable local config; pinned artifact load, bounded frame and actionable preflight; no node/model allowlist | | SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | | SM-22a | Pinned candidate/champion validation | Current evaluation/registry | DONE | Local comparison/report and isolated UC metrics gate passed; [local evidence](16-sm22a-local-validation-report.md), [live evidence](17-sm22a-live-metrics-report.md) | -| SM-22b | Explicit promotion and rollback | SM-22a | READY | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests | -| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-24a | WAIT | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | +| SM-22b | Explicit promotion and rollback | SM-22a | DONE | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests; [live evidence](18-sm22b-live-validation-report.md) | +| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-24a | READY | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | | SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-28a | WAIT | Package tested train/compare/promote/incremental-score services; validate, deploy and run | | SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | WAIT | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | diff --git a/skyulf-core/examples/databricks_sm22b_alias_live.py b/skyulf-core/examples/databricks_sm22b_alias_live.py new file mode 100644 index 000000000..1f199e586 --- /dev/null +++ b/skyulf-core/examples/databricks_sm22b_alias_live.py @@ -0,0 +1,120 @@ +# Databricks notebook source +"""Isolated Unity Catalog validation of guarded Skyulf champion promotion.""" + +import json +from typing import Any + +import mlflow # ty: ignore[unresolved-import] +import numpy as np +import pandas as pd + +from skyulf.integrations.mlflow.promotion import ( + AliasConflictError, + DeltaAliasAdmission, + alias_resource_id, + promote_candidate, + rollback_promotion, +) +from skyulf.integrations.mlflow.registry import resolve_model +from skyulf.integrations.mlflow.validation import compare_registered_local_models + +MODEL = "workspace.skyulf_sm24a_20260923.skyulf_sm22b_promotion_r1" +CONTROL = "workspace.skyulf_sm24a_20260923.skyulf_sm22b_alias_admission_r1" +REFERENCE_URI = "runs:/3fcb9236b2434eb1bec2eb42af8b1d45/model" +CANDIDATE_URI = "runs:/546df4fed4d443999990707df7255335/model" + + +def run() -> dict[str, Any]: + """Reuse two disposable versions, promote, prove conflict, and roll back.""" + spark_session: Any = globals()["spark"] + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + client = mlflow.MlflowClient(tracking_uri="databricks", registry_uri="databricks-uc") + reference = client.get_model_version(MODEL, "1") + candidate = client.get_model_version(MODEL, "2") + if reference.source != REFERENCE_URI or candidate.source != CANDIDATE_URI: + raise AssertionError("Existing isolated model versions have unexpected sources.") + reference_version = str(reference.version) + candidate_version = str(candidate.version) + if str(client.get_model_version_by_alias(MODEL, "champion").version) != reference_version: + raise AssertionError("Test champion alias differs from the original version.") + key = alias_resource_id(MODEL, "champion") + rows = spark_session.table(CONTROL).limit(2).collect() + if len(rows) != 1 or rows[0]["target_id"] != key or rows[0]["owner"] is not None: + raise AssertionError("Existing alias admission row has unexpected state.") + admission = DeltaAliasAdmission(spark_session, CONTROL) + x = np.arange(80, 110, dtype="float64") + heldout = pd.DataFrame({"x": x, "target": 3.0 * x + 2.0}) + report = compare_registered_local_models( + resolve_model( + MODEL, + version=candidate_version, + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + resolve_model( + MODEL, + version=reference_version, + tracking_uri="databricks", + registry_uri="databricks-uc", + ), + heldout, + target_column="target", + dataset_id="synthetic-sm22b-r1/heldout", + metric="heldout_mse", + min_improvement=1.0, + quality_threshold=1.0, + max_rows=100, + max_bytes=100_000, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if not report.eligible: + raise AssertionError(f"Candidate failed comparison: {report.reason}") + with admission.hold(key): + try: + with admission.hold(key): + raise AssertionError("Contender entered while owner held admission.") + except AliasConflictError: + pass + receipt = promote_candidate( + report, + heldout, + target_column="target", + expected_champion_version=reference_version, + admission=admission, + max_rows=100, + max_bytes=100_000, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if str(client.get_model_version_by_alias(MODEL, "champion").version) != candidate_version: + raise AssertionError("Promotion did not select the candidate.") + reversal = rollback_promotion( + receipt, + expected_current_version=candidate_version, + admission=admission, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if str(client.get_model_version_by_alias(MODEL, "champion").version) != reference_version: + raise AssertionError("Rollback did not restore the reference.") + return { + "model": MODEL, + "control_table": CONTROL, + "reference_version": reference_version, + "candidate_version": candidate_version, + "candidate_mse": report.candidate_metrics["heldout_mse"], + "reference_mse": report.champion_metrics["heldout_mse"] + if report.champion_metrics is not None + else None, + "promotion_event": receipt.event_id, + "rollback_event": reversal.event_id, + "final_alias_version": reference_version, + "conflict_rejected": True, + } + + +runtime_dbutils: Any = globals().get("dbutils") +if runtime_dbutils is not None: + runtime_dbutils.notebook.exit(json.dumps(run())) diff --git a/skyulf-core/examples/databricks_sm22b_restricted_live.py b/skyulf-core/examples/databricks_sm22b_restricted_live.py new file mode 100644 index 000000000..e19e0a34f --- /dev/null +++ b/skyulf-core/examples/databricks_sm22b_restricted_live.py @@ -0,0 +1,36 @@ +# Databricks notebook source +"""Confirm a read-only test principal cannot mutate the isolated UC champion alias.""" + +import json +from typing import Any + +import mlflow # ty: ignore[unresolved-import] + +MODEL = "workspace.skyulf_sm24a_20260923.skyulf_sm22b_promotion_r1" + + +def run() -> dict[str, str]: + """Read the allowed champion, then require a real registry write denial.""" + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + client = mlflow.MlflowClient(tracking_uri="databricks", registry_uri="databricks-uc") + original = str(client.get_model_version_by_alias(MODEL, "champion").version) + if original != "1": + raise AssertionError(f"Test alias must be restored to version 1, got {original}.") + try: + client.set_registered_model_alias(MODEL, "champion", "2") + except Exception as exc: # noqa: BLE001 - Databricks may wrap permission errors + code = str(getattr(exc, "error_code", "")).upper() + if "PERMISSION_DENIED" not in code and "PERMISSION_DENIED" not in str(exc).upper(): + raise + else: + raise AssertionError("Restricted principal unexpectedly changed the champion alias.") + after = str(client.get_model_version_by_alias(MODEL, "champion").version) + if after != original: + raise AssertionError("Denied alias write changed the champion.") + return {"read_version": original, "final_version": after, "denial": "PERMISSION_DENIED"} + + +runtime_dbutils: Any = globals().get("dbutils") +if runtime_dbutils is not None: + runtime_dbutils.notebook.exit(json.dumps(run())) diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py new file mode 100644 index 000000000..97cdf508d --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -0,0 +1,374 @@ +"""Version-checked MLflow champion promotion with shared admission and receipts. + +Alias writes are not compare-and-swap. Every writer must use the same non-expiring +admission and registry writes must be restricted to those writers. A prepared +receipt survives an uncertain mutation, which requires operator reconciliation. +""" + +import hashlib +import json +from collections.abc import Iterator +from contextlib import AbstractContextManager, contextmanager +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Protocol +from uuid import uuid4 + +import pandas as pd +import polars as pl + +from ...integrations.databricks.admission import BatchConflictError, LocalTableLock +from ...integrations.databricks.delta_admission import DeltaTableAdmission +from .registry import ( + RegistryError, + RegistryOperationError, + _error_code, + _make_client, + _require_mlflow, + _translate_error, + resolve_model, +) +from .validation import ModelComparisonReport, compare_registered_local_models + +_ALIAS = "champion" +_ACTIVE_TAG = "champion_current_event" + + +class AliasConflictError(RegistryError): + """The champion alias or shared admission disagrees with the expected state.""" + + +class AliasOutcomeUnknownError(RegistryOperationError): + """Alias mutation may have succeeded but its final receipt was not verified.""" + + +class AliasAdmission(Protocol): + """Hold one non-expiring shared resource claim through alias verification.""" + + local_only: bool + + def hold(self, resource_id: str) -> AbstractContextManager[None]: + """Reject a competing alias writer and release after the receipt is durable.""" + ... + + +def alias_resource_id(model_name: str, alias: str = _ALIAS) -> str: + """Derive a stable, unambiguous control-row key for one model alias.""" + if not isinstance(model_name, str) or not model_name.strip(): + raise ValueError("model_name must be nonempty.") + if alias != _ALIAS: + raise ValueError("Only the champion alias is supported.") + encoded = json.dumps([model_name, alias], separators=(",", ":")).encode() + return "mlflow-alias:" + hashlib.sha256(encoded).hexdigest() + + +class LocalAliasAdmission: + """Coordinate test/development writers sharing one host and lock directory.""" + + local_only = True + + def __init__(self, directory: str | Path) -> None: + """Reuse the tested non-expiring OS file-lock implementation.""" + self._lock = LocalTableLock(directory) + + @contextmanager + def hold(self, resource_id: str) -> Iterator[None]: + """Translate local lock contention to an alias conflict.""" + try: + with self._lock.hold(resource_id): + yield + except BatchConflictError as exc: + raise AliasConflictError("Another writer holds alias admission.") from exc + + +class DeltaAliasAdmission: + """Coordinate Databricks writers through a preprovisioned Delta control row. + + Provision exactly one target_id/owner row with target_id equal to + alias_resource_id(model_name). Keep this authority separate from prediction + table admission. The underlying Delta claim never expires automatically. + """ + + local_only = False + + def __init__(self, spark: Any, control_table: str) -> None: + """Bind a pre-existing control table without creating resources.""" + self._lock = DeltaTableAdmission(spark, control_table) + + @contextmanager + def hold(self, resource_id: str) -> Iterator[None]: + """Translate distributed Delta contention to an alias conflict.""" + try: + with self._lock.hold(resource_id): + yield + except BatchConflictError as exc: + raise AliasConflictError("Another writer holds alias admission.") from exc + + +@dataclass(frozen=True, slots=True) +class AliasChangeReceipt: + """Record a verified alias transition and its durable registry event.""" + + event_id: str + kind: str + model_name: str + alias: str + prior_version: str + new_version: str + comparison_sha256: str | None + parent_event_id: str | None + + +def _admission(admission: AliasAdmission, registry_uri: str | None) -> AliasAdmission: + """Reject missing or host-local admission for a Unity Catalog writer.""" + if not callable(getattr(admission, "hold", None)) or not isinstance( + getattr(admission, "local_only", None), bool + ): + raise ValueError("A shared alias admission is required.") + effective_registry_uri = registry_uri or _require_mlflow().get_registry_uri() + if effective_registry_uri.startswith("databricks-uc") and admission.local_only: + raise ValueError("Unity Catalog promotion requires distributed alias admission.") + return admission + + +def _read_alias(client: Any, name: str) -> str: + """Read the current champion without creating a missing alias.""" + try: + return str(client.get_model_version_by_alias(name, _ALIAS).version) + except Exception as exc: # noqa: BLE001 - MLflow backends expose different error classes + missing_alias = _error_code(exc) in {"RESOURCE_DOES_NOT_EXIST", "NOT_FOUND"} or ( + _error_code(exc) == "INVALID_PARAMETER_VALUE" + and "alias" in str(exc).lower() + and "not found" in str(exc).lower() + ) + if missing_alias: + raise AliasConflictError( + "Champion alias is missing; initialize it explicitly." + ) from exc + raise _translate_error(exc, name=name, version=_ALIAS) from exc + + +def _active_marker(client: Any, name: str, current: str) -> str | None: + """Reject a bypass write that left the active receipt on another version.""" + try: + raw = (client.get_registered_model(name).tags or {}).get(_ACTIVE_TAG) + except Exception as exc: # noqa: BLE001 - registry transport boundary + raise _translate_error(exc, name=name, version=current) from exc + if raw is None: + return None + try: + marker = json.loads(raw) + if type(marker) is not dict or marker["version"] != current: + raise ValueError + event_id = marker["event_id"] + if type(event_id) is not str or not event_id: + raise ValueError + except (TypeError, ValueError, KeyError) as exc: + raise AliasConflictError("Active receipt disagrees with champion alias.") from exc + return event_id + + +def _event_tag(event_id: str) -> str: + """Name an event without overwriting another promotion or rollback.""" + return f"promotion_{event_id}" + + +def _event_payload(receipt: AliasChangeReceipt, status: str) -> dict[str, str | None]: + """Keep UC tag values under 256 bytes; model, version and event ID are in the tag address.""" + return { + "k": receipt.kind, + "p": receipt.prior_version, + "h": receipt.comparison_sha256, + "e": receipt.parent_event_id, + "s": status, + } + + +def _write_event(client: Any, receipt: AliasChangeReceipt, status: str) -> None: + """Persist a prepared or committed transition on its destination version.""" + value = json.dumps(_event_payload(receipt, status), sort_keys=True, separators=(",", ":")) + if len(value.encode("utf-8")) > 256: + raise ValueError("UC model-version receipt exceeds the 256-byte tag value limit.") + client.set_model_version_tag( + receipt.model_name, receipt.new_version, _event_tag(receipt.event_id), value + ) + + +def _verify_original_receipt(client: Any, receipt: AliasChangeReceipt) -> None: + """Refuse rollback of a forged or unfinished promotion receipt.""" + try: + raw = client.get_model_version(receipt.model_name, receipt.new_version).tags.get( + _event_tag(receipt.event_id) + ) + except Exception as exc: # noqa: BLE001 - registry transport boundary + raise _translate_error(exc, name=receipt.model_name, version=receipt.new_version) from exc + expected = _event_payload(receipt, "committed") + try: + if raw is None or json.loads(raw) != expected: + raise ValueError("Promotion receipt is missing or differs from registry state.") + except (TypeError, json.JSONDecodeError) as exc: + raise ValueError("Promotion receipt is malformed.") from exc + + +def _commit_change(client: Any, receipt: AliasChangeReceipt) -> None: + """Write intent, mutate alias, then verify and commit the durable receipt.""" + try: + _write_event(client, receipt, "prepared") + except Exception as exc: # noqa: BLE001 - registry transport boundary + raise _translate_error(exc, name=receipt.model_name, version=receipt.new_version) from exc + try: + client.set_registered_model_alias(receipt.model_name, receipt.alias, receipt.new_version) + except Exception as exc: # noqa: BLE001 - alias write can have an unknown outcome + try: + current = _read_alias(client, receipt.model_name) + except RegistryError: + raise AliasOutcomeUnknownError( + f"Alias outcome unknown; inspect prepared event {receipt.event_id}." + ) from exc + if current == receipt.prior_version: + raise _translate_error( + exc, name=receipt.model_name, version=receipt.new_version + ) from exc + raise AliasOutcomeUnknownError( + f"Alias outcome unknown; inspect prepared event {receipt.event_id}." + ) from exc + try: + if _read_alias(client, receipt.model_name) != receipt.new_version: + raise AliasOutcomeUnknownError( + f"Alias verification failed; inspect prepared event {receipt.event_id}." + ) + _write_event(client, receipt, "committed") + client.set_registered_model_tag( + receipt.model_name, + _ACTIVE_TAG, + json.dumps({"event_id": receipt.event_id, "version": receipt.new_version}), + ) + if _active_marker(client, receipt.model_name, receipt.new_version) != receipt.event_id: + raise AliasOutcomeUnknownError( + f"Active receipt verification failed for event {receipt.event_id}." + ) + except Exception as exc: # noqa: BLE001 - never imply rollback after a possible alias write + raise AliasOutcomeUnknownError( + f"Alias may have changed; inspect event {receipt.event_id} before retry." + ) from exc + + +def promote_candidate( + report: ModelComparisonReport, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, + expected_champion_version: str, + admission: AliasAdmission, + max_rows: int, + max_bytes: int, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> AliasChangeReceipt: + """Re-evaluate a pinned report and explicitly promote only a better candidate.""" + if not isinstance(report, ModelComparisonReport): + raise TypeError("report must be a ModelComparisonReport.") + if ( + type(expected_champion_version) is not str + or expected_champion_version != report.champion_version + or not expected_champion_version.isascii() + or not expected_champion_version.isdigit() + ): + raise ValueError("Expected champion version must match the comparison report.") + if not report.eligible or report.reason != "candidate_improved": + raise ValueError("Comparison does not approve candidate promotion.") + _admission(admission, registry_uri) + candidate = resolve_model( + report.model_name, + version=report.candidate_version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + champion = resolve_model( + report.model_name, + version=expected_champion_version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + fresh = compare_registered_local_models( + candidate, + champion, + heldout, + target_column=target_column, + dataset_id=report.dataset_id, + metric=report.metric, + min_improvement=report.min_improvement, + quality_threshold=report.quality_threshold, + max_rows=max_rows, + max_bytes=max_bytes, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + if fresh != report or not fresh.eligible: + raise ValueError("Pinned comparison no longer matches the supplied report.") + mlflow = _require_mlflow() + client = _make_client(mlflow, tracking_uri, registry_uri) + with admission.hold(alias_resource_id(report.model_name)): + current = _read_alias(client, report.model_name) + if current != expected_champion_version: + raise AliasConflictError("Champion alias differs from expected version.") + prior_event = _active_marker(client, report.model_name, current) + digest = hashlib.sha256( + json.dumps(asdict(fresh), sort_keys=True, allow_nan=False).encode() + ).hexdigest() + receipt = AliasChangeReceipt( + event_id=uuid4().hex, + kind="promotion", + model_name=report.model_name, + alias=_ALIAS, + prior_version=current, + new_version=report.candidate_version, + comparison_sha256=digest, + parent_event_id=prior_event, + ) + _commit_change(client, receipt) + return receipt + + +def rollback_promotion( + receipt: AliasChangeReceipt, + *, + expected_current_version: str, + admission: AliasAdmission, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> AliasChangeReceipt: + """Restore the prior version only while the matching promotion remains active.""" + if not isinstance(receipt, AliasChangeReceipt) or receipt.kind != "promotion": + raise ValueError("Rollback requires a completed promotion receipt.") + if expected_current_version != receipt.new_version: + raise ValueError("Expected current version must match the promotion receipt.") + _admission(admission, registry_uri) + mlflow = _require_mlflow() + client = _make_client(mlflow, tracking_uri, registry_uri) + with admission.hold(alias_resource_id(receipt.model_name)): + current = _read_alias(client, receipt.model_name) + if current != expected_current_version: + raise AliasConflictError("Champion alias differs from expected current version.") + if _active_marker(client, receipt.model_name, current) != receipt.event_id: + raise AliasConflictError("A newer promotion superseded this rollback receipt.") + _verify_original_receipt(client, receipt) + # The previous version must still exist before changing the alias. + resolve_model( + receipt.model_name, + version=receipt.prior_version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + reversal = AliasChangeReceipt( + event_id=uuid4().hex, + kind="rollback", + model_name=receipt.model_name, + alias=_ALIAS, + prior_version=current, + new_version=receipt.prior_version, + comparison_sha256=receipt.comparison_sha256, + parent_event_id=receipt.event_id, + ) + _commit_change(client, reversal) + return reversal diff --git a/skyulf-core/tests/integrations/test_mlflow_promotion.py b/skyulf-core/tests/integrations/test_mlflow_promotion.py new file mode 100644 index 000000000..4fc0eced5 --- /dev/null +++ b/skyulf-core/tests/integrations/test_mlflow_promotion.py @@ -0,0 +1,233 @@ +"""Explicit alias promotion must preserve pinned comparisons and rollback receipts.""" + +import json +from dataclasses import replace +from pathlib import Path +from typing import cast + +import numpy as np +import pandas as pd +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.inference.local_pipeline import save_local_pipeline +from skyulf.integrations.mlflow.local_model import log_local_model +from skyulf.integrations.mlflow.promotion import ( + AliasConflictError, + AliasOutcomeUnknownError, + LocalAliasAdmission, + _admission, + alias_resource_id, + promote_candidate, + rollback_promotion, +) +from skyulf.integrations.mlflow.registry import RegistryAccessError, register_model, resolve_model +from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run +from skyulf.integrations.mlflow.validation import ( + ModelComparisonReport, + compare_registered_local_models, +) +from skyulf.pipeline import SkyulfPipeline + +mlflow = pytest.importorskip("mlflow") + + +@pytest.fixture +def case(tmp_path: Path): + """Use real local MLflow versions so alias and receipt behavior cannot be mocked away.""" + uri = f"sqlite:///{(tmp_path / 'registry.db').as_posix()}" + name = "sm22-promotion" + tracking = TrackingConfig(enabled=True, tracking_uri=uri, experiment_name=name) + client = mlflow.MlflowClient(tracking_uri=uri, registry_uri=uri) + client.create_experiment(name, artifact_location=(tmp_path / "mlruns").as_uri()) + x = np.arange(12, dtype="float64") + holdout_x = np.arange(20, 25, dtype="float64") + heldout = pd.DataFrame({"x": holdout_x, "target": 2.0 * holdout_x}) + for offset in (10.0, 0.0): + train = pd.DataFrame({"x": x, "target": 2.0 * x + offset}) + pipeline = SkyulfPipeline({"preprocessing": [], "modeling": {"type": "linear_regression"}}) + pipeline.fit(SplitDataset(train=train, test=train.head(0)), target_column="target") + artifact_path = tmp_path / f"model-{int(offset)}" + save_local_pipeline(pipeline, artifact_path) + with track_run(tracking, run_name=f"fit-{offset}") as run: + assert run.run_id is not None + model_uri = log_local_model( + artifact_path, run_id=run.run_id, artifact_path="model", tracking_uri=uri + ) + register_model(model_uri, name, tracking_uri=uri, registry_uri=uri) + client.set_registered_model_alias(name, "champion", "1") + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + champion = resolve_model(name, version="1", tracking_uri=uri, registry_uri=uri) + report = compare_registered_local_models( + candidate, + champion, + heldout, + target_column="target", + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=1.0, + quality_threshold=1.0, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + assert report.eligible + return client, uri, name, heldout, report, LocalAliasAdmission(tmp_path / "locks") + + +def _promote(case, **changes): + """Call the real promotion path with one validated local comparison.""" + _, uri, _, heldout, report, admission = case + options = { + "target_column": "target", + "expected_champion_version": "1", + "admission": admission, + "max_rows": 10, + "max_bytes": 10_000, + "tracking_uri": uri, + "registry_uri": uri, + } + options.update(changes) + selected = cast(ModelComparisonReport, options.pop("report", report)) + return promote_candidate(selected, heldout, **options) + + +def test_promote_and_rollback_persist_receipts(case) -> None: + """An accepted candidate moves the alias and leaves auditable forward and reverse receipts.""" + client, uri, name, _, _, admission = case + + receipt = _promote(case) + assert receipt.prior_version == "1" + assert receipt.new_version == "2" + assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + tag = client.get_model_version(name, "2").tags[f"promotion_{receipt.event_id}"] + assert len(tag.encode("utf-8")) <= 256 + assert json.loads(tag)["s"] == "committed" + assert json.loads(client.get_registered_model(name).tags["champion_current_event"]) == { + "event_id": receipt.event_id, + "version": "2", + } + + reversal = rollback_promotion( + receipt, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + assert reversal.prior_version == "2" + assert reversal.new_version == "1" + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + assert json.loads(client.get_registered_model(name).tags["champion_current_event"]) == { + "event_id": reversal.event_id, + "version": "1", + } + + +def test_stale_alias_and_modified_report_cannot_promote(case) -> None: + """The lock path must reject stale alias state and forged comparison fields.""" + client, _, name, _, report, _ = case + client.set_registered_model_alias(name, "champion", "2") + with pytest.raises(AliasConflictError, match="expected"): + _promote(case) + client.set_registered_model_alias(name, "champion", "1") + + tampered = replace(report, eligible=True, candidate_metrics={"heldout_mse": -1.0}) + with pytest.raises(ValueError, match="comparison"): + _promote(case, report=tampered) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + +def test_missing_champion_and_contention_refuse_promotion(case) -> None: + """The first alias must be initialized separately, and a second writer cannot enter.""" + client, _, name, _, _, admission = case + client.delete_registered_model_alias(name, "champion") + with pytest.raises(AliasConflictError, match="missing"): + _promote(case) + client.set_registered_model_alias(name, "champion", "1") + with ( + admission.hold(alias_resource_id(name, "champion")), + pytest.raises(AliasConflictError, match="admission"), + ): + _promote(case) + + +def test_rollback_rejects_newer_alias_state(case) -> None: + """A receipt cannot roll back a different current model version.""" + client, uri, name, _, _, admission = case + receipt = _promote(case) + client.set_registered_model_alias(name, "champion", "1") + with pytest.raises(AliasConflictError, match="expected"): + rollback_promotion( + receipt, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + + +def test_permission_denial_does_not_move_alias(case, monkeypatch) -> None: + """A denied registry write is typed and leaves the previous alias selected.""" + client, _, name, _, _, _ = case + error = mlflow.exceptions.MlflowException("denied") + error.error_code = "PERMISSION_DENIED" + + def denied(*args, **kwargs): + """Simulate a restricted registry principal at the mutation boundary.""" + raise error + + monkeypatch.setattr(client, "set_registered_model_alias", denied) + monkeypatch.setattr("skyulf.integrations.mlflow.promotion._make_client", lambda *args: client) + with pytest.raises(RegistryAccessError): + _promote(case) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + +def test_lost_alias_write_response_is_reported_as_unknown(case, monkeypatch) -> None: + """A committed alias move with a lost response must never be reported as safely denied.""" + client, _, name, _, _, _ = case + original = client.set_registered_model_alias + + def move_then_fail(model_name, alias, version): + """Simulate a transport failure after the registry accepted the alias move.""" + original(model_name, alias, version) + raise mlflow.exceptions.MlflowException("response lost") + + monkeypatch.setattr(client, "set_registered_model_alias", move_then_fail) + monkeypatch.setattr("skyulf.integrations.mlflow.promotion._make_client", lambda *args: client) + with pytest.raises(AliasOutcomeUnknownError, match="inspect prepared event"): + _promote(case) + assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + + +def test_old_receipt_cannot_rollback_newer_promotion_to_same_version(case) -> None: + """An old receipt must not undo a later promotion even when its version numbers match.""" + client, uri, name, _, _, admission = case + old_receipt = _promote(case) + rollback_promotion( + old_receipt, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + new_receipt = _promote(case) + assert new_receipt.event_id != old_receipt.event_id + with pytest.raises(AliasConflictError, match="superseded"): + rollback_promotion( + old_receipt, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + + +def test_global_uc_registry_rejects_local_admission(tmp_path, monkeypatch) -> None: + """Implicit UC registry configuration must still require distributed admission.""" + monkeypatch.setattr(mlflow, "get_registry_uri", lambda: "databricks-uc") + with pytest.raises(ValueError, match="distributed"): + _admission(LocalAliasAdmission(tmp_path / "locks"), None) From f42cbf75a4846d36700d2d90782e359057e8176d Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Wed, 23 Sep 2026 23:09:13 +0300 Subject: [PATCH 43/85] feat(mlflow): add challenger and previous champion aliases Signed-off-by: flyingriverhorse --- docs/user_guide/mlflow_registry.md | 55 +++- ...sm22c-lifecycle-alias-validation-report.md | 68 +++++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 16 +- .../examples/databricks_sm22b_alias_live.py | 34 +++ .../skyulf/integrations/mlflow/promotion.py | 258 ++++++++++++++---- .../integrations/test_mlflow_promotion.py | 169 +++++++++++- .../integrations/test_mlflow_tracking.py | 8 +- 7 files changed, 533 insertions(+), 75 deletions(-) create mode 100644 initiatives/spark_and_mlflow/19-sm22c-lifecycle-alias-validation-report.md diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index db41636a5..71fa23116 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -174,12 +174,19 @@ Evaluation does not move aliases, publish predictions or deploy endpoints. Promotion is a separate, explicit operation. SM-28a monthly candidate training follows before Bundle generation. -## Promote and roll back a local pipeline +## Stage, promote, and roll back a local pipeline + +After a successful comparison, stage_challenger re-evaluates the same pinned +holdout and assigns the concrete candidate version to `@challenger`. It does +not move `@champion`. A replacement challenger requires an explicit +`expected_challenger_version`; staging cannot silently overwrite another +candidate. Merely registering or comparing a model never assigns an alias. The promote_candidate function re-resolves both concrete model versions and re-evaluates the same bounded labeled holdout. It rejects a changed comparison -report, an ineligible candidate, a missing champion alias, or a stale expected -champion version. The caller must pin the holdout's source snapshot externally; +report, an ineligible candidate, a missing champion alias, a stale expected +champion version, or a challenger alias without a matching committed staging +event. The caller must pin the holdout's source snapshot externally; dataset_id alone is not proof of the underlying data. There is no implicit first-champion initialization. @@ -193,9 +200,21 @@ from skyulf.integrations.mlflow.promotion import ( LocalAliasAdmission, promote_candidate, rollback_promotion, + stage_challenger, ) admission = LocalAliasAdmission("/var/lib/skyulf/alias-locks") +staging = stage_challenger( + report, + heldout, + target_column="target", + expected_champion_version="1", + admission=admission, + max_rows=10_000, + max_bytes=20_000_000, + tracking_uri="sqlite:///tracking.db", + registry_uri="sqlite:///registry.db", +) receipt = promote_candidate( report, heldout, @@ -235,18 +254,30 @@ admission = DeltaAliasAdmission( ) ~~~ -All participating promotion and rollback jobs must point to that same table. +All participating staging, promotion and rollback jobs must point to that same table. Do not use the predictions-table admission row for aliases. Local file locks are rejected when the registry URI is databricks-uc. -The transition writes a prepared model-version tag before changing the alias, -then verifies the new alias, writes a committed event tag and an active-event -registered-model tag. The returned receipt names both versions and the event -ID. Rollback verifies the committed promotion event and refuses a later event, -even if it happens to select the same model version. If the alias write or -receipt update has an uncertain outcome, AliasOutcomeUnknownError includes -the event ID: inspect the alias and tags before retrying. A prepared tag is -not proof that promotion completed. Registry tags are audit records for +Staging writes a prepared model-version tag, assigns `@challenger`, verifies +the alias, and commits a staging event. Promotion assigns +`@previous_champion` to the old champion, moves `@champion` to the +challenger, then removes `@challenger`. The returned receipt records the +concrete model versions, event ID, and the previous value of +`@previous_champion`. Rollback verifies the committed promotion event, +restores `@champion` and the previous rollback pointer, and does not +reinstate the rolled-back model as challenger. A prior release's single-alias +promotion receipt remains reversible. A staged newer challenger blocks +rollback until the operator reconciles it. + +MLflow performs these alias changes as separate calls, not one atomic +transaction. If a later call fails after an earlier alias moved, the operation +reports an unknown outcome; inspect all three aliases and the prepared event +before retrying. `@previous_champion` identifies only the latest rollback +pointer, not the full history. Concrete versions and promotion/rollback event +tags retain that history; predictions should record the resolved model version. +Rollback refuses a later promotion, even if it selects the same version. +AliasOutcomeUnknownError includes the event ID for inspection. A prepared tag +is not proof that promotion completed. Registry tags are audit records for controlled writers, not tamper-proof authorization tokens. The event tag key uses underscores, and its compact value stays within Unity Catalog's 256-byte tag-value limit. diff --git a/initiatives/spark_and_mlflow/19-sm22c-lifecycle-alias-validation-report.md b/initiatives/spark_and_mlflow/19-sm22c-lifecycle-alias-validation-report.md new file mode 100644 index 000000000..e7867d919 --- /dev/null +++ b/initiatives/spark_and_mlflow/19-sm22c-lifecycle-alias-validation-report.md @@ -0,0 +1,68 @@ +# SM-22c model lifecycle aliases - 2026-09-23 + +SM-22c stages an eligible, re-evaluated registered version as +`@challenger`. Explicit promotion requires that committed staging event, +moves the old `@champion` to `@previous_champion`, points `@champion` +to the candidate, and removes `@challenger` and its active marker. +Guarded rollback restores the prior champion and the previous rollback +pointer without restaging the rolled-back model. Concrete version numbers and +prepared/committed event tags retain the transition history. + +## Local gate + +The real SQLite MLflow 3.16.1 integration gate passed **40 tests** across +promotion, comparison, and registry. The promotion module covers eligible +staging, tampered/missing challenger, three-alias transition, previous-pointer +restoration, stale rollback, a pre-SM-22c receipt, permission denial, and +partial/uncertain writes. Ruff, formatting, and Ty passed for the changed +Python files and Core package. The final wheel's `promotion.py` bytes were +compared with the current source. Installing optional MLflow exposed two +pre-existing Ty diagnostics in the caller-owned-run tracking test; explicit +non-null run assertions made that test stronger, and its focused case passed. + +## Unity Catalog gate + +The existing isolated test resources in +`workspace.skyulf_sm24a_20260923` were reused: model +`skyulf_sm22b_promotion_r1` versions 1 and 2 and Delta admission table +`skyulf_sm22b_alias_admission_r1`. The new wheel and notebook were uploaded +only under the authenticated user's `sm22c_alias_r1` folder. The final +0.9.0 wheel SHA-256 is +`57755268204A3DBDC6D962B37DF52C37AC0E394E411E2ED829C1C9808FD11933`. + +[Final-wheel owner run 269743074025024](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/693080435047326/run/269743074025024) +completed **SUCCESS** with a 900-second task timeout, zero retries, +serverless environment version 4, and MLflow 3.16.1. The candidate's +heldout MSE was `2.5849394142282116e-27`, versus `100.00000000000088` +for the reference. Event IDs were: + +- Staging: `2e3a81c3ac8744b0805486aebd7f813e` +- Promotion: `d8685bdba6a74ccf812e59feeaaf1aca` +- Rollback: `c72b03a5374540b5968cc581796cbe72` + +The notebook asserted the challenger alias at version 2, champion at version +2 and previous champion at version 1 after promotion, and the absence of the +challenger alias and active marker. After rollback it asserted champion at +version 1 and no stale previous-champion alias. The same run also rejected a +contending Delta admission holder. The final model alias state is restored to +the original champion version 1; the transition events and uploaded test +files remain for audit. + +A first request, [run 912755889386772](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/656058797751923/run/912755889386772), +failed before compute launch because the deprecated `client: "1"` environment +channel is unsupported in this workspace. A corrected +[run 417916316136066](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/259434330041715/run/417916316136066) +passed the three-alias path, but its wheel preceded the final +challenger-marker cleanup. Only the final-wheel run is counted as the +complete SM-22c platform gate. + +## Operational boundary + +All staging, promotion, and rollback writers must share the same +non-expiring Delta admission row and controlled registry permissions. +Unity Catalog does not make the three alias changes atomic. A failure after +any alias mutation reports an unknown outcome and requires inspection of +aliases and the prepared event before retry. `@previous_champion` points +only to the immediate rollback target; it does not replace version history. +The caller still owns the labeled holdout snapshot and first-champion +initialization. No retraining service or Bundle was created here. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 318ce11d0..4ae473ff1 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,7 +1,7 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a/b complete; SM-28a next before SM-20a. Target: 0.9.0.** -Next deliverable: controlled promotion and label-aware retraining services, +Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a/b/c complete; SM-28a next before SM-20a. Target: 0.9.0.** +Next deliverable: label-aware retraining service, then a working local-engine Bundle. Spark expansion follows that Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring @@ -48,8 +48,9 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-24a | Local training and bounded batch prediction | SM-25 | DONE | Two UC source tables, five live cross-job models, 62-ID FE audit and bounded monthly reads; [evidence](08-sm24a-live-validation-report.md) | | SM-22a | Pinned candidate/champion validation | Current evaluation/registry | DONE | Local comparison/report and isolated UC metrics gate passed; [local evidence](16-sm22a-local-validation-report.md), [live evidence](17-sm22a-live-metrics-report.md) | | SM-22b | Explicit promotion and rollback | SM-22a | DONE | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests; [live evidence](18-sm22b-live-validation-report.md) | -| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-24a | READY | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | -| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-28a | WAIT | Package tested train/compare/promote/incremental-score services; validate, deploy and run | +| SM-22c | Challenger and previous-champion aliases | SM-22b | DONE | Validated challenger staging; guarded three-alias promotion/rollback; legacy receipts and partial-write tests; [local and UC evidence](19-sm22c-lifecycle-alias-validation-report.md) | +| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-22c, SM-24a | READY | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | +| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | WAIT | Package tested train/compare/promote/incremental-score services; validate, deploy and run | | SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | WAIT | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | @@ -60,7 +61,7 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-24c | Spark batch workflow adapter | SM-20a, existing Spark sink | LATER | Expose tested Spark runner after first local Bundle | | SM-20b | Spark Bundle enhancement | SM-24c, selected SM-17 slices | LATER | Add tested Spark engine choice while preserving local variant | -SM-22a/b and SM-28a are now prerequisites for the first Bundle. SM-28b only +SM-22a/b/c and SM-28a are now prerequisites for the first Bundle. SM-28b only wires their optional monthly schedule after the Bundle exists. SM-27 remains post-Bundle and independent. Endpoint, feature lookup and monitoring remain optional; broad Spark expansion follows the local Bundle. @@ -83,8 +84,9 @@ in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). 5. **SM-15I:** add automatic first-snapshot and later new-row scoring with a committed source-version receipt and append-safe output. See the [incremental plan](12-sm15i-incremental-scoring-plan.md). -6. **SM-22a/b:** compare concrete candidate/champion versions on one labeled - holdout, then provide separate explicit promotion and rollback. +6. **SM-22a/b/c:** compare concrete candidate/champion versions on one labeled + holdout, stage a validated `@challenger`, then explicitly promote with + `@previous_champion` and guarded rollback. 7. **SM-28a:** train a candidate from a pinned, label-aware snapshot and temporal holdout; compare it without automatic promotion. 8. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle diff --git a/skyulf-core/examples/databricks_sm22b_alias_live.py b/skyulf-core/examples/databricks_sm22b_alias_live.py index 1f199e586..490a669c0 100644 --- a/skyulf-core/examples/databricks_sm22b_alias_live.py +++ b/skyulf-core/examples/databricks_sm22b_alias_live.py @@ -14,6 +14,7 @@ alias_resource_id, promote_candidate, rollback_promotion, + stage_challenger, ) from skyulf.integrations.mlflow.registry import resolve_model from skyulf.integrations.mlflow.validation import compare_registered_local_models @@ -77,6 +78,19 @@ def run() -> dict[str, Any]: raise AssertionError("Contender entered while owner held admission.") except AliasConflictError: pass + staging = stage_challenger( + report, + heldout, + target_column="target", + expected_champion_version=reference_version, + admission=admission, + max_rows=100, + max_bytes=100_000, + tracking_uri="databricks", + registry_uri="databricks-uc", + ) + if str(client.get_model_version_by_alias(MODEL, "challenger").version) != candidate_version: + raise AssertionError("Staging did not select the candidate.") receipt = promote_candidate( report, heldout, @@ -90,6 +104,19 @@ def run() -> dict[str, Any]: ) if str(client.get_model_version_by_alias(MODEL, "champion").version) != candidate_version: raise AssertionError("Promotion did not select the candidate.") + if ( + str(client.get_model_version_by_alias(MODEL, "previous_champion").version) + != reference_version + ): + raise AssertionError("Promotion did not preserve the previous champion.") + if "challenger_current_event" in client.get_registered_model(MODEL).tags: + raise AssertionError("Promotion left a stale challenger event marker.") + try: + client.get_model_version_by_alias(MODEL, "challenger") + except mlflow.exceptions.MlflowException: + pass + else: + raise AssertionError("Promotion left the challenger alias assigned.") reversal = rollback_promotion( receipt, expected_current_version=candidate_version, @@ -99,6 +126,12 @@ def run() -> dict[str, Any]: ) if str(client.get_model_version_by_alias(MODEL, "champion").version) != reference_version: raise AssertionError("Rollback did not restore the reference.") + try: + client.get_model_version_by_alias(MODEL, "previous_champion") + except mlflow.exceptions.MlflowException: + pass + else: + raise AssertionError("Rollback left a stale previous champion alias.") return { "model": MODEL, "control_table": CONTROL, @@ -108,6 +141,7 @@ def run() -> dict[str, Any]: "reference_mse": report.champion_metrics["heldout_mse"] if report.champion_metrics is not None else None, + "staging_event": staging.event_id, "promotion_event": receipt.event_id, "rollback_event": reversal.event_id, "final_alias_version": reference_version, diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py index 97cdf508d..ca1e27e30 100644 --- a/skyulf-core/skyulf/integrations/mlflow/promotion.py +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -31,7 +31,10 @@ from .validation import ModelComparisonReport, compare_registered_local_models _ALIAS = "champion" +_CHALLENGER = "challenger" +_PREVIOUS = "previous_champion" _ACTIVE_TAG = "champion_current_event" +_CHALLENGER_TAG = "challenger_current_event" class AliasConflictError(RegistryError): @@ -113,10 +116,11 @@ class AliasChangeReceipt: kind: str model_name: str alias: str - prior_version: str + prior_version: str | None new_version: str comparison_sha256: str | None parent_event_id: str | None + previous_champion_version: str | None = None def _admission(admission: AliasAdmission, registry_uri: str | None) -> AliasAdmission: @@ -131,10 +135,10 @@ def _admission(admission: AliasAdmission, registry_uri: str | None) -> AliasAdmi return admission -def _read_alias(client: Any, name: str) -> str: - """Read the current champion without creating a missing alias.""" +def _read_optional_alias(client: Any, name: str, alias: str) -> str | None: + """Resolve one alias, distinguishing a missing alias from registry failures.""" try: - return str(client.get_model_version_by_alias(name, _ALIAS).version) + return str(client.get_model_version_by_alias(name, alias).version) except Exception as exc: # noqa: BLE001 - MLflow backends expose different error classes missing_alias = _error_code(exc) in {"RESOURCE_DOES_NOT_EXIST", "NOT_FOUND"} or ( _error_code(exc) == "INVALID_PARAMETER_VALUE" @@ -142,16 +146,23 @@ def _read_alias(client: Any, name: str) -> str: and "not found" in str(exc).lower() ) if missing_alias: - raise AliasConflictError( - "Champion alias is missing; initialize it explicitly." - ) from exc - raise _translate_error(exc, name=name, version=_ALIAS) from exc + return None + raise _translate_error(exc, name=name, version=alias) from exc -def _active_marker(client: Any, name: str, current: str) -> str | None: +def _read_alias(client: Any, name: str) -> str: + """Read the current champion without creating a missing alias.""" + current = _read_optional_alias(client, name, _ALIAS) + if current is None: + raise AliasConflictError("Champion alias is missing; initialize it explicitly.") + return current + + +def _active_marker(client: Any, name: str, current: str, alias: str = _ALIAS) -> str | None: """Reject a bypass write that left the active receipt on another version.""" + tag = _ACTIVE_TAG if alias == _ALIAS else _CHALLENGER_TAG try: - raw = (client.get_registered_model(name).tags or {}).get(_ACTIVE_TAG) + raw = (client.get_registered_model(name).tags or {}).get(tag) except Exception as exc: # noqa: BLE001 - registry transport boundary raise _translate_error(exc, name=name, version=current) from exc if raw is None: @@ -164,7 +175,7 @@ def _active_marker(client: Any, name: str, current: str) -> str | None: if type(event_id) is not str or not event_id: raise ValueError except (TypeError, ValueError, KeyError) as exc: - raise AliasConflictError("Active receipt disagrees with champion alias.") from exc + raise AliasConflictError(f"Active receipt disagrees with {alias} alias.") from exc return event_id @@ -181,6 +192,7 @@ def _event_payload(receipt: AliasChangeReceipt, status: str) -> dict[str, str | "h": receipt.comparison_sha256, "e": receipt.parent_event_id, "s": status, + "o": receipt.previous_champion_version, } @@ -194,8 +206,8 @@ def _write_event(client: Any, receipt: AliasChangeReceipt, status: str) -> None: ) -def _verify_original_receipt(client: Any, receipt: AliasChangeReceipt) -> None: - """Refuse rollback of a forged or unfinished promotion receipt.""" +def _verify_original_receipt(client: Any, receipt: AliasChangeReceipt) -> bool: + """Refuse forged receipts; return true for a pre-multi-alias promotion.""" try: raw = client.get_model_version(receipt.model_name, receipt.new_version).tags.get( _event_tag(receipt.event_id) @@ -204,68 +216,91 @@ def _verify_original_receipt(client: Any, receipt: AliasChangeReceipt) -> None: raise _translate_error(exc, name=receipt.model_name, version=receipt.new_version) from exc expected = _event_payload(receipt, "committed") try: - if raw is None or json.loads(raw) != expected: - raise ValueError("Promotion receipt is missing or differs from registry state.") + stored = json.loads(raw) if raw is not None else None except (TypeError, json.JSONDecodeError) as exc: raise ValueError("Promotion receipt is malformed.") from exc + if stored == expected: + return False + legacy = {key: value for key, value in expected.items() if key != "o"} + if receipt.previous_champion_version is None and stored == legacy: + return True + raise ValueError("Promotion receipt is missing or differs from registry state.") + +def _commit_change( + client: Any, + receipt: AliasChangeReceipt, + updates: list[tuple[str, str | None, str | None]], +) -> None: + """Prepare, apply verified alias updates, then persist their common receipt. -def _commit_change(client: Any, receipt: AliasChangeReceipt) -> None: - """Write intent, mutate alias, then verify and commit the durable receipt.""" + MLflow alias calls are not atomic. Once any call may have changed an alias, + failures are reported as unknown and require reconciliation before retry. + """ try: _write_event(client, receipt, "prepared") except Exception as exc: # noqa: BLE001 - registry transport boundary raise _translate_error(exc, name=receipt.model_name, version=receipt.new_version) from exc - try: - client.set_registered_model_alias(receipt.model_name, receipt.alias, receipt.new_version) - except Exception as exc: # noqa: BLE001 - alias write can have an unknown outcome + changed = False + for alias, new_version, old_version in updates: try: - current = _read_alias(client, receipt.model_name) - except RegistryError: + if new_version is None: + client.delete_registered_model_alias(receipt.model_name, alias) + else: + client.set_registered_model_alias(receipt.model_name, alias, new_version) + except Exception as exc: # noqa: BLE001 - alias write can have an unknown outcome + try: + current = _read_optional_alias(client, receipt.model_name, alias) + except RegistryError: + current = object() + if not changed and current == old_version: + raise _translate_error( + exc, name=receipt.model_name, version=receipt.new_version + ) from exc raise AliasOutcomeUnknownError( f"Alias outcome unknown; inspect prepared event {receipt.event_id}." ) from exc - if current == receipt.prior_version: - raise _translate_error( - exc, name=receipt.model_name, version=receipt.new_version + changed = True + try: + if _read_optional_alias(client, receipt.model_name, alias) != new_version: + raise AliasOutcomeUnknownError("Alias verification failed.") + except Exception as exc: # noqa: BLE001 - a mutation has already occurred + raise AliasOutcomeUnknownError( + f"Alias outcome unknown; inspect prepared event {receipt.event_id}." ) from exc - raise AliasOutcomeUnknownError( - f"Alias outcome unknown; inspect prepared event {receipt.event_id}." - ) from exc try: - if _read_alias(client, receipt.model_name) != receipt.new_version: - raise AliasOutcomeUnknownError( - f"Alias verification failed; inspect prepared event {receipt.event_id}." - ) + if receipt.kind == "promotion": + client.delete_registered_model_tag(receipt.model_name, _CHALLENGER_TAG) _write_event(client, receipt, "committed") + tag = _ACTIVE_TAG if receipt.alias == _ALIAS else _CHALLENGER_TAG client.set_registered_model_tag( receipt.model_name, - _ACTIVE_TAG, + tag, json.dumps({"event_id": receipt.event_id, "version": receipt.new_version}), ) - if _active_marker(client, receipt.model_name, receipt.new_version) != receipt.event_id: - raise AliasOutcomeUnknownError( - f"Active receipt verification failed for event {receipt.event_id}." - ) + if ( + _active_marker(client, receipt.model_name, receipt.new_version, receipt.alias) + != receipt.event_id + ): + raise AliasOutcomeUnknownError("Active receipt verification failed.") except Exception as exc: # noqa: BLE001 - never imply rollback after a possible alias write raise AliasOutcomeUnknownError( f"Alias may have changed; inspect event {receipt.event_id} before retry." ) from exc -def promote_candidate( +def _validated_report( report: ModelComparisonReport, heldout: pd.DataFrame | pl.DataFrame, *, target_column: str, expected_champion_version: str, - admission: AliasAdmission, max_rows: int, max_bytes: int, - tracking_uri: str | None = None, - registry_uri: str | None = None, -) -> AliasChangeReceipt: - """Re-evaluate a pinned report and explicitly promote only a better candidate.""" + tracking_uri: str | None, + registry_uri: str | None, +) -> str: + """Re-evaluate the pinned candidate and return its comparison digest.""" if not isinstance(report, ModelComparisonReport): raise TypeError("report must be a ModelComparisonReport.") if ( @@ -277,7 +312,6 @@ def promote_candidate( raise ValueError("Expected champion version must match the comparison report.") if not report.eligible or report.reason != "candidate_improved": raise ValueError("Comparison does not approve candidate promotion.") - _admission(admission, registry_uri) candidate = resolve_model( report.model_name, version=report.candidate_version, @@ -306,16 +340,117 @@ def promote_candidate( ) if fresh != report or not fresh.eligible: raise ValueError("Pinned comparison no longer matches the supplied report.") + return hashlib.sha256( + json.dumps(asdict(fresh), sort_keys=True, allow_nan=False).encode() + ).hexdigest() + + +def stage_challenger( + report: ModelComparisonReport, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, + expected_champion_version: str, + admission: AliasAdmission, + max_rows: int, + max_bytes: int, + expected_challenger_version: str | None = None, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> AliasChangeReceipt: + """Assign a validated candidate to challenger without moving champion.""" + _admission(admission, registry_uri) + digest = _validated_report( + report, + heldout, + target_column=target_column, + expected_champion_version=expected_champion_version, + max_rows=max_rows, + max_bytes=max_bytes, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + with admission.hold(alias_resource_id(report.model_name)): + if _read_alias(client, report.model_name) != expected_champion_version: + raise AliasConflictError("Champion alias differs from expected version.") + existing = _read_optional_alias(client, report.model_name, _CHALLENGER) + if existing != expected_challenger_version: + raise AliasConflictError("Challenger alias differs from expected version.") + if existing == report.candidate_version: + raise AliasConflictError("Candidate already holds challenger alias.") + receipt = AliasChangeReceipt( + event_id=uuid4().hex, + kind="challenger", + model_name=report.model_name, + alias=_CHALLENGER, + prior_version=existing, + new_version=report.candidate_version, + comparison_sha256=digest, + parent_event_id=_active_marker(client, report.model_name, expected_champion_version), + ) + _commit_change(client, receipt, [(_CHALLENGER, report.candidate_version, existing)]) + return receipt + + +def _verify_staged_challenger( + client: Any, report: ModelComparisonReport, comparison_sha256: str +) -> str: + """Require a committed staging event for this exact comparison.""" + if _read_optional_alias(client, report.model_name, _CHALLENGER) != report.candidate_version: + raise AliasConflictError("Challenger alias differs from candidate version.") + event_id = _active_marker(client, report.model_name, report.candidate_version, _CHALLENGER) + if event_id is None: + raise AliasConflictError("Challenger alias lacks a controlled staging event.") + try: + raw = client.get_model_version(report.model_name, report.candidate_version).tags.get( + _event_tag(event_id) + ) + event = json.loads(raw) if raw is not None else None + except Exception as exc: # noqa: BLE001 - registry transport boundary + raise AliasConflictError("Challenger staging event cannot be verified.") from exc + if not isinstance(event, dict) or ( + event.get("k") != "challenger" + or event.get("s") != "committed" + or event.get("h") != comparison_sha256 + ): + raise AliasConflictError("Challenger staging event differs from comparison.") + return event_id + + +def promote_candidate( + report: ModelComparisonReport, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, + expected_champion_version: str, + admission: AliasAdmission, + max_rows: int, + max_bytes: int, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> AliasChangeReceipt: + """Re-evaluate a pinned report and explicitly promote only a better candidate.""" + _admission(admission, registry_uri) + digest = _validated_report( + report, + heldout, + target_column=target_column, + expected_champion_version=expected_champion_version, + max_rows=max_rows, + max_bytes=max_bytes, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) mlflow = _require_mlflow() client = _make_client(mlflow, tracking_uri, registry_uri) with admission.hold(alias_resource_id(report.model_name)): current = _read_alias(client, report.model_name) if current != expected_champion_version: raise AliasConflictError("Champion alias differs from expected version.") + _verify_staged_challenger(client, report, digest) prior_event = _active_marker(client, report.model_name, current) - digest = hashlib.sha256( - json.dumps(asdict(fresh), sort_keys=True, allow_nan=False).encode() - ).hexdigest() + previous = _read_optional_alias(client, report.model_name, _PREVIOUS) receipt = AliasChangeReceipt( event_id=uuid4().hex, kind="promotion", @@ -325,8 +460,17 @@ def promote_candidate( new_version=report.candidate_version, comparison_sha256=digest, parent_event_id=prior_event, + previous_champion_version=previous, + ) + _commit_change( + client, + receipt, + [ + (_PREVIOUS, current, previous), + (_ALIAS, report.candidate_version, current), + (_CHALLENGER, None, report.candidate_version), + ], ) - _commit_change(client, receipt) return receipt @@ -341,6 +485,8 @@ def rollback_promotion( """Restore the prior version only while the matching promotion remains active.""" if not isinstance(receipt, AliasChangeReceipt) or receipt.kind != "promotion": raise ValueError("Rollback requires a completed promotion receipt.") + if receipt.prior_version is None: + raise ValueError("Promotion receipt must name its prior champion version.") if expected_current_version != receipt.new_version: raise ValueError("Expected current version must match the promotion receipt.") _admission(admission, registry_uri) @@ -352,7 +498,13 @@ def rollback_promotion( raise AliasConflictError("Champion alias differs from expected current version.") if _active_marker(client, receipt.model_name, current) != receipt.event_id: raise AliasConflictError("A newer promotion superseded this rollback receipt.") - _verify_original_receipt(client, receipt) + legacy = _verify_original_receipt(client, receipt) + if _read_optional_alias(client, receipt.model_name, _CHALLENGER) is not None: + raise AliasConflictError("Clear the newer challenger before rollback.") + if not legacy and ( + _read_optional_alias(client, receipt.model_name, _PREVIOUS) != receipt.prior_version + ): + raise AliasConflictError("Previous champion alias differs from promotion receipt.") # The previous version must still exist before changing the alias. resolve_model( receipt.model_name, @@ -369,6 +521,12 @@ def rollback_promotion( new_version=receipt.prior_version, comparison_sha256=receipt.comparison_sha256, parent_event_id=receipt.event_id, + previous_champion_version=receipt.previous_champion_version, ) - _commit_change(client, reversal) + updates: list[tuple[str, str | None, str | None]] = [ + (_ALIAS, receipt.prior_version, current) + ] + if not legacy: + updates.append((_PREVIOUS, receipt.previous_champion_version, receipt.prior_version)) + _commit_change(client, reversal, updates) return reversal diff --git a/skyulf-core/tests/integrations/test_mlflow_promotion.py b/skyulf-core/tests/integrations/test_mlflow_promotion.py index 4fc0eced5..ce078d2a2 100644 --- a/skyulf-core/tests/integrations/test_mlflow_promotion.py +++ b/skyulf-core/tests/integrations/test_mlflow_promotion.py @@ -3,7 +3,7 @@ import json from dataclasses import replace from pathlib import Path -from typing import cast +from typing import Any, cast import numpy as np import pandas as pd @@ -13,6 +13,7 @@ from skyulf.inference.local_pipeline import save_local_pipeline from skyulf.integrations.mlflow.local_model import log_local_model from skyulf.integrations.mlflow.promotion import ( + AliasChangeReceipt, AliasConflictError, AliasOutcomeUnknownError, LocalAliasAdmission, @@ -20,6 +21,7 @@ alias_resource_id, promote_candidate, rollback_promotion, + stage_challenger, ) from skyulf.integrations.mlflow.registry import RegistryAccessError, register_model, resolve_model from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run @@ -79,7 +81,7 @@ def case(tmp_path: Path): def _promote(case, **changes): """Call the real promotion path with one validated local comparison.""" _, uri, _, heldout, report, admission = case - options = { + options: dict[str, Any] = { "target_column": "target", "expected_champion_version": "1", "admission": admission, @@ -93,14 +95,67 @@ def _promote(case, **changes): return promote_candidate(selected, heldout, **options) +def _stage(case, **changes): + """Publish a verified challenger before an explicit champion promotion.""" + _, uri, _, heldout, report, admission = case + options: dict[str, Any] = { + "target_column": "target", + "expected_champion_version": "1", + "admission": admission, + "max_rows": 10, + "max_bytes": 10_000, + "tracking_uri": uri, + "registry_uri": uri, + } + options.update(changes) + selected = cast(ModelComparisonReport, options.pop("report", report)) + return stage_challenger(selected, heldout, **options) + + +def test_stage_challenger_requires_validation_and_preserves_champion(case) -> None: + """Only a freshly eligible candidate becomes challenger without moving production.""" + client, _, name, _, report, _ = case + staged = _stage(case) + assert staged.kind == "challenger" + assert staged.new_version == "2" + assert str(client.get_model_version_by_alias(name, "challenger").version) == "2" + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + assert json.loads(client.get_registered_model(name).tags["challenger_current_event"]) == { + "event_id": staged.event_id, + "version": "2", + } + + with pytest.raises(AliasConflictError, match="[Cc]hallenger"): + _stage(case) + with pytest.raises(ValueError, match="comparison"): + _stage(case, report=replace(report, eligible=True, candidate_metrics={"heldout_mse": -1.0})) + + +def test_promotion_requires_staged_challenger(case) -> None: + """A direct or tampered challenger alias must not bypass the validated staging step.""" + client, _, name, _, _, _ = case + with pytest.raises(AliasConflictError, match="[Cc]hallenger"): + _promote(case) + _stage(case) + client.set_registered_model_alias(name, "challenger", "1") + with pytest.raises(AliasConflictError, match="[Cc]hallenger"): + _promote(case) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + def test_promote_and_rollback_persist_receipts(case) -> None: """An accepted candidate moves the alias and leaves auditable forward and reverse receipts.""" client, uri, name, _, _, admission = case + _stage(case) receipt = _promote(case) assert receipt.prior_version == "1" assert receipt.new_version == "2" assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + assert str(client.get_model_version_by_alias(name, "previous_champion").version) == "1" + with pytest.raises(mlflow.exceptions.MlflowException): + client.get_model_version_by_alias(name, "challenger") + assert "challenger_current_event" not in client.get_registered_model(name).tags tag = client.get_model_version(name, "2").tags[f"promotion_{receipt.event_id}"] assert len(tag.encode("utf-8")) <= 256 assert json.loads(tag)["s"] == "committed" @@ -119,12 +174,112 @@ def test_promote_and_rollback_persist_receipts(case) -> None: assert reversal.prior_version == "2" assert reversal.new_version == "1" assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + with pytest.raises(mlflow.exceptions.MlflowException): + client.get_model_version_by_alias(name, "previous_champion") assert json.loads(client.get_registered_model(name).tags["champion_current_event"]) == { "event_id": reversal.event_id, "version": "1", } +def test_rollback_restores_prior_previous_champion_pointer(case) -> None: + """Rollback restores the preceding rollback pointer rather than leaving a stale one.""" + client, uri, name, _, _, admission = case + client.set_registered_model_alias(name, "previous_champion", "2") + _stage(case) + receipt = _promote(case) + assert receipt.previous_champion_version == "2" + assert str(client.get_model_version_by_alias(name, "previous_champion").version) == "1" + + rollback_promotion( + receipt, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + assert str(client.get_model_version_by_alias(name, "previous_champion").version) == "2" + + +def test_rollback_rejects_changed_previous_pointer(case) -> None: + """A bypass edit to the rollback target cannot silently be accepted.""" + client, uri, name, _, _, admission = case + _stage(case) + receipt = _promote(case) + client.set_registered_model_alias(name, "previous_champion", "2") + with pytest.raises(AliasConflictError, match="Previous champion"): + rollback_promotion( + receipt, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + + +def test_legacy_champion_receipt_can_still_roll_back(case) -> None: + """A receipt written before the challenger aliases existed stays reversible.""" + client, uri, name, _, _, admission = case + legacy = AliasChangeReceipt( + event_id="legacy", + kind="promotion", + model_name=name, + alias="champion", + prior_version="1", + new_version="2", + comparison_sha256="old-comparison", + parent_event_id=None, + ) + client.set_model_version_tag( + name, + "2", + "promotion_legacy", + json.dumps( + {"k": "promotion", "p": "1", "h": "old-comparison", "e": None, "s": "committed"}, + sort_keys=True, + separators=(",", ":"), + ), + ) + client.set_registered_model_alias(name, "champion", "2") + client.set_registered_model_tag( + name, "champion_current_event", json.dumps({"event_id": "legacy", "version": "2"}) + ) + + reversal = rollback_promotion( + legacy, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + assert reversal.new_version == "1" + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + +def test_partial_promotion_reports_unknown_outcome(case, monkeypatch) -> None: + """A failure after changing the previous pointer requires reconciliation.""" + client, _, name, _, _, _ = case + _stage(case) + original = client.set_registered_model_alias + error = mlflow.exceptions.MlflowException("denied") + error.error_code = "PERMISSION_DENIED" + + def deny_champion(model_name, alias, version): + """Allow the first alias update, then deny the champion move.""" + if alias == "champion": + raise error + return original(model_name, alias, version) + + monkeypatch.setattr(client, "set_registered_model_alias", deny_champion) + monkeypatch.setattr("skyulf.integrations.mlflow.promotion._make_client", lambda *args: client) + with pytest.raises(AliasOutcomeUnknownError, match="inspect prepared event"): + _promote(case) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + assert str(client.get_model_version_by_alias(name, "previous_champion").version) == "1" + assert str(client.get_model_version_by_alias(name, "challenger").version) == "2" + + def test_stale_alias_and_modified_report_cannot_promote(case) -> None: """The lock path must reject stale alias state and forged comparison fields.""" client, _, name, _, report, _ = case @@ -156,6 +311,7 @@ def test_missing_champion_and_contention_refuse_promotion(case) -> None: def test_rollback_rejects_newer_alias_state(case) -> None: """A receipt cannot roll back a different current model version.""" client, uri, name, _, _, admission = case + _stage(case) receipt = _promote(case) client.set_registered_model_alias(name, "champion", "1") with pytest.raises(AliasConflictError, match="expected"): @@ -178,6 +334,7 @@ def denied(*args, **kwargs): """Simulate a restricted registry principal at the mutation boundary.""" raise error + _stage(case) monkeypatch.setattr(client, "set_registered_model_alias", denied) monkeypatch.setattr("skyulf.integrations.mlflow.promotion._make_client", lambda *args: client) with pytest.raises(RegistryAccessError): @@ -188,12 +345,14 @@ def denied(*args, **kwargs): def test_lost_alias_write_response_is_reported_as_unknown(case, monkeypatch) -> None: """A committed alias move with a lost response must never be reported as safely denied.""" client, _, name, _, _, _ = case + _stage(case) original = client.set_registered_model_alias def move_then_fail(model_name, alias, version): - """Simulate a transport failure after the registry accepted the alias move.""" + """Simulate a transport failure after the champion alias moved.""" original(model_name, alias, version) - raise mlflow.exceptions.MlflowException("response lost") + if alias == "champion": + raise mlflow.exceptions.MlflowException("response lost") monkeypatch.setattr(client, "set_registered_model_alias", move_then_fail) monkeypatch.setattr("skyulf.integrations.mlflow.promotion._make_client", lambda *args: client) @@ -205,6 +364,7 @@ def move_then_fail(model_name, alias, version): def test_old_receipt_cannot_rollback_newer_promotion_to_same_version(case) -> None: """An old receipt must not undo a later promotion even when its version numbers match.""" client, uri, name, _, _, admission = case + _stage(case) old_receipt = _promote(case) rollback_promotion( old_receipt, @@ -213,6 +373,7 @@ def test_old_receipt_cannot_rollback_newer_promotion_to_same_version(case) -> No tracking_uri=uri, registry_uri=uri, ) + _stage(case) new_receipt = _promote(case) assert new_receipt.event_id != old_receipt.event_id with pytest.raises(AliasConflictError, match="superseded"): diff --git a/skyulf-core/tests/integrations/test_mlflow_tracking.py b/skyulf-core/tests/integrations/test_mlflow_tracking.py index 911debe1b..f7724ef55 100644 --- a/skyulf-core/tests/integrations/test_mlflow_tracking.py +++ b/skyulf-core/tests/integrations/test_mlflow_tracking.py @@ -167,8 +167,12 @@ def test_tracking_does_not_close_callers_active_run(tmp_path: Path) -> None: with mlflow.start_run(experiment_id=experiment_id, run_name="caller") as caller: with tracking.track_run(config, run_name="skyulf"): - assert mlflow.active_run().info.run_id == caller.info.run_id - assert mlflow.active_run().info.run_id == caller.info.run_id + active = mlflow.active_run() + assert active is not None + assert active.info.run_id == caller.info.run_id + active = mlflow.active_run() + assert active is not None + assert active.info.run_id == caller.info.run_id def test_warn_policy_preserves_body_result_when_logging_fails( From 5c922c0e954501008e0a615717b7fde4c1f671c2 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 14:16:41 +0300 Subject: [PATCH 44/85] feat: add label-aware local candidate retraining Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 9 +- docs/user_guide/databricks_local_sdk.md | 48 +++ .../06-prebundle-model-lifecycle-plan.md | 6 +- .../20-sm28a-label-aware-retraining-report.md | 63 ++++ initiatives/spark_and_mlflow/HANDOFF.md | 19 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 11 +- .../examples/databricks_local_sm28a_job.py | 144 ++++++++ .../integrations/databricks/__init__.py | 12 + .../databricks/local_retraining.py | 324 ++++++++++++++++++ .../test_databricks_local_retraining.py | 262 ++++++++++++++ 10 files changed, 880 insertions(+), 18 deletions(-) create mode 100644 initiatives/spark_and_mlflow/20-sm28a-label-aware-retraining-report.md create mode 100644 skyulf-core/examples/databricks_local_sm28a_job.py create mode 100644 skyulf-core/skyulf/integrations/databricks/local_retraining.py create mode 100644 skyulf-core/tests/integrations/test_databricks_local_retraining.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 96978f1dc..5867af440 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -38,8 +38,13 @@ execution, MLflow registry and Databricks delivery remain under development. reports pinned model/data identities, held-out metrics, improvement and a directional quality gate. Held-out evaluation now reuses Core's full model metric calculators, including probability-based classification metrics when - defined, rather than maintaining separate formulas. It never moves an alias; - label-aware retraining remains a separate pre-Bundle task. + defined, rather than maintaining separate formulas. It never moves an alias. +- Label-aware local candidate training reads a pinned bounded Delta snapshot, + excludes labels unavailable at cutoff, fits pandas or Polars Skyulf pipelines + before a temporal holdout, logs the model and comparison evidence to one + MLflow run, and registers a concrete model version without changing aliases. + A real taxi serverless test compared two UC model versions on 1,770 holdout + rows and verified six late labels stayed out of both fit and evaluation. - Local-engine Databricks SDK configuration and preflight for bounded pandas/Polars batches. It selects trusted local or portable artifacts, resolves MLflow aliases once to concrete versions, checks metadata and diff --git a/docs/user_guide/databricks_local_sdk.md b/docs/user_guide/databricks_local_sdk.md index 33d73dc9d..13aef3fc6 100644 --- a/docs/user_guide/databricks_local_sdk.md +++ b/docs/user_guide/databricks_local_sdk.md @@ -12,6 +12,54 @@ an explicit, versioned UC Delta source reader for selected-period local batches. SM-15L publishes an explicitly selected period to UC Delta. The separate incremental runner below discovers new source inserts automatically. +## Train a candidate when labels are ready + +`train_local_candidate` reads a **specific Delta table version**, filters a +bounded event window in Spark, then makes a temporal split in pandas. Rows whose +labels were not available by `cutoff` are excluded from both fit and holdout. +The feature/model pipeline fits only on events before `holdout_start`; later +eligible events are reserved for evaluation. The fit engine can be pandas or +Polars. The run logs the Skyulf config, source and code identities, fitted model, +held-out metrics and `candidate_comparison.json`. It registers a new concrete +model version but never assigns `@challenger` or `@champion`. + +```python +from datetime import UTC, datetime +from skyulf.integrations.databricks import LocalTrainingSpec, train_local_candidate + +spec = LocalTrainingSpec( + table="catalog.schema.labeled_events", version=12, + start=datetime(2026, 1, 1, tzinfo=UTC), + holdout_start=datetime(2026, 2, 1, tzinfo=UTC), + cutoff=datetime(2026, 3, 1, tzinfo=UTC), + event_column="event_time", label_time_column="label_available_at", + row_keys=("event_id",), input_columns=("feature_a", "feature_b"), + target_column="target", max_rows=10_000, max_bytes=32_000_000, +) +result = train_local_candidate( + spark, spec, pipeline_config, + model_name="catalog.schema.customer_model", + tracking_uri="databricks", registry_uri="databricks-uc", + experiment_name="/Users/me/customer-model", run_name="candidate-2026-03", + artifact_path="/tmp/customer-model", metric="heldout_rmse", + min_improvement=0.05, engine="polars", + champion_version="7", # Pin this concrete version before the job starts. +) +print(result.model_version, result.comparison.eligible) +``` + +The example assumes event and label timestamps represent UTC instants. A +missing or later label is not a training label, even if its target value is +already present in the pinned table. The source must have unique nonnull row +keys and distinct feature, target and timestamp columns. A nonempty training +set and holdout of at least two rows each are required. The row and byte limits +bound decoded rows and the local frame, not Spark's wire transfer size. The +caller supplies a concrete `champion_version`; omit it for the first candidate. +Review the comparison report, then use the separate guarded staging/promotion +operations if a human approves a change. If fit, packaging, registration or +comparison fails, no alias moves; a registered but unapproved candidate may +remain for inspection. A scheduling policy is separate from this service. + ## Fit and score a small batch Install the same `skyulf-core`, pandas, Polars and scikit-learn versions in the diff --git a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md index 37bb53a17..806ee2d46 100644 --- a/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md +++ b/initiatives/spark_and_mlflow/06-prebundle-model-lifecycle-plan.md @@ -65,9 +65,9 @@ The promotion path must revalidate the pinned model identities and decision; an **Interface:** Consume a caller-pinned bounded source snapshot, label availability cutoff and temporal holdout; fit with Skyulf, log metrics/artifact, register a candidate, then call SM-22a. Do not promote automatically. -- [ ] Write failing tests for late labels, leakage across cutoff, reproducible split, failed candidate and unchanged champion. -- [ ] Reuse current fitted artifact packaging and registry publication; store source/code/model/evaluation identities. -- [ ] Run a small isolated Databricks validation after local tests pass, without touching production aliases. +- [x] Write failing tests for late labels, leakage across cutoff, reproducible split, failed candidate and unchanged champion. +- [x] Reuse current fitted artifact packaging and registry publication; store source/code/model/evaluation identities. +- [x] Run a small isolated Databricks validation after local tests pass, without touching production aliases; see [SM-28a evidence](20-sm28a-label-aware-retraining-report.md). ### Task 4: SM-20a Bundle integration diff --git a/initiatives/spark_and_mlflow/20-sm28a-label-aware-retraining-report.md b/initiatives/spark_and_mlflow/20-sm28a-label-aware-retraining-report.md new file mode 100644 index 000000000..1423ba7cf --- /dev/null +++ b/initiatives/spark_and_mlflow/20-sm28a-label-aware-retraining-report.md @@ -0,0 +1,63 @@ +# SM-28a label-aware candidate training - 2026-09-24 + +Status: **PASS** for the standalone, small-data retraining service. The first +local-engine Bundle (SM-20a) is still unstarted; no schedule or promotion was +created. + +## Contract + +`LocalTrainingSpec` pins one Delta table/version, UTC event interval, label +availability cutoff, temporal holdout boundary, raw input/target columns, row +keys and local resource budget. Spark filters and projects before a bounded +driver read. Unavailable labels are excluded; available targets must be +nonnull. Stable event/key sorting produces disjoint training and holdout rows. +The normal Skyulf pipeline fits on only the earlier rows with pandas or Polars. +The MLflow run logs held-out metrics, config, source and code identity, plus +the fitted model. A new concrete UC model version is registered, then the +candidate and caller-pinned prior version are compared on the same holdout. +The comparison report is logged to `candidate_comparison.json`. Neither path +changes model aliases; staging and promotion are separate operations. + +## Local gate + +The focused Databricks/MLflow integration gate passed **55 tests, 1 skipped**. +The new retraining tests cover late-label exclusion, cutoff and temporal +membership, deterministic row order, invalid provenance, bounded versioned +reading, failed registration, real pandas/Polars Skyulf fits and SQLite MLflow +model-version comparisons without alias mutation. Ruff and Ty passed; the +documentation built with `mkdocs build --strict`. + +## Databricks gate + +The existing `skyulf` CLI profile and isolated +`workspace.skyulf_sm24a_20260923` test schema were reused. A one-time +[serverless job](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/753857281922815/run/487563692360508) +finished **SUCCESS** with no retries and a 900-second task timeout. It ran +the uploaded wheel in the user's `sm28a_r1` folder (SHA-256 +`02c63e1b4d24ad2b061d61583debd6b0b227fcfbdf449ddee06d2daba8274c34`). +The source was a read-only copy of the prior real taxi test table into new +managed Delta table `skyulf_sm28a_labels_r1`, pinned at version **0**. The +test derived label availability one hour after pickup and deliberately marked +one label late. Five additional labels crossed the February cutoff naturally. +This timestamp construction tests the API boundary; it is not a claim about +the production arrival time of taxi fare labels. + +| Run | UC model version | MLflow run | Train / holdout / unavailable | Holdout MAE / RMSE / R2 | +| --- | ---: | --- | --- | --- | +| Linear baseline | 1 | `b95b219b11994e09bf5a8d8eef7a7cb8` | 1,724 / 1,770 / 6 | 0.612642 / 2.252941 / 0.949224 | +| Imputed, scaled random forest candidate | 2 | `79bcd243aebd4ef1b0655e7e0695f4e7` | 1,724 / 1,770 / 6 | 0.488965 / 2.088749 / 0.956355 | + +Both UC versions were independently listed as `READY`. Both MLflow runs were +`FINISHED`, had the same source version and row counts, and independently +listed `model/`, `skyulf_pipeline_config.json` and +`candidate_comparison.json`. The second call pinned version 1 as its comparison +reference. A separate registered-model lookup with aliases included returned +no aliases. The candidate improved RMSE by about 0.1642 on this one holdout; +that does not authorize promotion or imply future performance. + +The uploaded wheel preceded only the final public export and stricter +`LocalTrainingSpec` identity/time validation edits. Those final edits passed +the local integration gate; the live run proves the training, publication and +comparison path exercised by that wheel. No inference, schedule or Bundle +was tested by this job. The shared alias-admission rule remains the separate +SM-22b/c promotion contract. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index d86fe884b..cfec90223 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,4 +1,4 @@ -# Session handoff - 2026-09-23 +# Session handoff - 2026-09-24 SM-00 through SM-16, SM-15L/15I and SM-24a/25/26 are complete for their documented scopes. The selected Databricks serverless local monthly UC @@ -8,8 +8,8 @@ values for recurring jobs. SM-15I now provides automatic new-row scoring for the first small-data pandas/Polars Databricks Bundle (SM-20a). Spark handles table I/O; Spark FE/model execution follows the Bundle. SM-18 and streaming remain parked.** -The revised order completes SM-22a/b comparison and controlled promotion, -then SM-28a label-aware challenger training before SM-20a. SM-28b adds the +The revised order completed SM-22a/b/c comparison and controlled promotion, +then SM-28a label-aware candidate training before SM-20a. SM-28b adds the optional monthly schedule after the Bundle; SM-27 remains later. Target release: 0.9.0. Branch: `090`. SM-22a has a locally verified, read-only comparison API and passed its @@ -18,13 +18,18 @@ isolated Databricks metrics and UC comparison gate; see the [live report](17-sm22a-live-metrics-report.md). SM-22b has explicit version-checked promotion and rollback with shared admission. Its isolated UC promotion, conflict, rollback and restricted-principal denial passed; see -[live evidence](18-sm22b-live-validation-report.md). SM-28a is next. +[live evidence](18-sm22b-live-validation-report.md). SM-22c added challenger +and previous-champion aliases; see [its report](19-sm22c-lifecycle-alias-validation-report.md). +SM-28a now trains from a pinned label-aware Delta snapshot and compares a +registered candidate without promotion; see [its local and live report](20-sm28a-label-aware-retraining-report.md). +SM-20a is next. ## Starting point -- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26 and SM-22a/b are complete. - Start SM-28a from [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). - SM-20a follows the verified SM-22a/b and SM-28a services. +- SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26, + SM-22a/b/c and SM-28a are complete. Start SM-20a from + [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md), using the services in + [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. A later [real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 4ae473ff1..e74c7f33d 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,14 +1,13 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-23. **SM-00 through SM-16, SM-15L/15I/24a/25/26 complete; SM-22a/b/c complete; SM-28a next before SM-20a. Target: 0.9.0.** -Next deliverable: label-aware retraining service, -then a working local-engine Bundle. Spark +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26 and SM-22a/b/c/28a complete. SM-20a next. Target: 0.9.0.** +Next deliverable: the first working local-engine Bundle. Spark expansion follows that Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. Read [HANDOFF.md](HANDOFF.md), [the integration plan](04-databricks-integration-plan.md) -and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-28a. +and [the pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md) before SM-20a. The [SM-20 Bundle plan](05-sm20-bundle-plan.md) remains the packaging gate. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). @@ -49,8 +48,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-22a | Pinned candidate/champion validation | Current evaluation/registry | DONE | Local comparison/report and isolated UC metrics gate passed; [local evidence](16-sm22a-local-validation-report.md), [live evidence](17-sm22a-live-metrics-report.md) | | SM-22b | Explicit promotion and rollback | SM-22a | DONE | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests; [live evidence](18-sm22b-live-validation-report.md) | | SM-22c | Challenger and previous-champion aliases | SM-22b | DONE | Validated challenger staging; guarded three-alias promotion/rollback; legacy receipts and partial-write tests; [local and UC evidence](19-sm22c-lifecycle-alias-validation-report.md) | -| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-22c, SM-24a | READY | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion | -| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | WAIT | Package tested train/compare/promote/incremental-score services; validate, deploy and run | +| SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-22c, SM-24a | DONE | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion; [evidence](20-sm28a-label-aware-retraining-report.md) | +| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | READY | Package tested train/compare/promote/incremental-score services; validate, deploy and run | | SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | WAIT | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | diff --git a/skyulf-core/examples/databricks_local_sm28a_job.py b/skyulf-core/examples/databricks_local_sm28a_job.py new file mode 100644 index 000000000..0dfe6e518 --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm28a_job.py @@ -0,0 +1,144 @@ +# Databricks notebook source +"""One-time SM-28a rehearsal on isolated, real NYC taxi Delta records.""" + +import json +import tempfile +from datetime import UTC, datetime +from pathlib import Path + +import mlflow # ty: ignore[unresolved-import] +from pyspark.sql import functions as F # ty: ignore[unresolved-import] + +from skyulf.integrations.databricks.local_retraining import ( + LocalTrainingSpec, + train_local_candidate, +) + +SCHEMA = "workspace.skyulf_sm24a_20260923" +ORIGINAL = "workspace.skyulf_nyctaxi_e2e_20260923.taxi_training" +SOURCE = f"{SCHEMA}.skyulf_sm28a_labels_r1" +MODEL = f"{SCHEMA}.skyulf_sm28a_candidate_r1" +EXPERIMENT = "/Users/edwardwolfe99@gmail.com/skyulf_sm24a_20260923/sm28a_r1_experiment" +FEATURES = ("trip_distance", "trip_duration_minutes", "pickup_hour", "pickup_weekday") + + +def main() -> None: + """Create a pinned label table and compare two registered candidates.""" + spark = globals().get("spark") + if spark is None: + raise RuntimeError("This example requires a Databricks notebook Spark session.") + if spark.catalog.tableExists(SOURCE): + raise RuntimeError("SM-28a test table already exists; use a new revision.") + original = spark.table(ORIGINAL) + late_id = original.orderBy("entity_id").first().entity_id + labeled = original.select( + "entity_id", + F.col("tpep_pickup_datetime").alias("event_time"), + *FEATURES, + "fare_amount", + ).withColumn( + "label_at", + F.when( + F.col("entity_id") == late_id, F.lit("2016-03-02 00:00:00").cast("timestamp") + ).otherwise(F.expr("event_time + INTERVAL 1 HOUR")), + ) + labeled.write.format("delta").saveAsTable(SOURCE) + source_version = int(spark.sql(f"DESCRIBE HISTORY {SOURCE}").first().version) + spec = LocalTrainingSpec( + table=SOURCE, + version=source_version, + start=datetime(2016, 1, 1, tzinfo=UTC), + holdout_start=datetime(2016, 2, 1, tzinfo=UTC), + cutoff=datetime(2016, 3, 1, tzinfo=UTC), + event_column="event_time", + label_time_column="label_at", + row_keys=("entity_id",), + input_columns=FEATURES, + target_column="fare_amount", + max_rows=3500, + max_bytes=18_000_000, + ) + mlflow.set_tracking_uri("databricks") + mlflow.set_registry_uri("databricks-uc") + with tempfile.TemporaryDirectory(prefix="skyulf-sm28a-") as directory: + baseline = train_local_candidate( + spark, + spec, + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + model_name=MODEL, + tracking_uri="databricks", + registry_uri="databricks-uc", + experiment_name=EXPERIMENT, + run_name="sm28a-baseline", + artifact_path=Path(directory) / "baseline", + metric="heldout_rmse", + min_improvement=0, + ) + candidate = train_local_candidate( + spark, + spec, + { + "preprocessing": [ + { + "name": "impute", + "transformer": "SimpleImputer", + "params": {"columns": list(FEATURES), "strategy": "median"}, + }, + { + "name": "scale", + "transformer": "StandardScaler", + "params": {"columns": list(FEATURES)}, + }, + ], + "modeling": { + "type": "random_forest_regressor", + "params": {"n_estimators": 30, "max_depth": 8, "random_state": 42, "n_jobs": 1}, + }, + }, + model_name=MODEL, + tracking_uri="databricks", + registry_uri="databricks-uc", + experiment_name=EXPERIMENT, + run_name="sm28a-candidate", + artifact_path=Path(directory) / "candidate", + metric="heldout_rmse", + min_improvement=0, + champion_version=baseline.model_version, + ) + if baseline.training_rows < 100 or baseline.holdout_rows < 100: + raise AssertionError("Temporal split did not preserve both large partitions.") + if baseline.unavailable_labels < 1: + raise AssertionError("The intentionally late label was not excluded.") + if candidate.comparison.champion_version != baseline.model_version: + raise AssertionError("Comparison did not use the pinned baseline version.") + client = mlflow.MlflowClient(tracking_uri="databricks", registry_uri="databricks-uc") + aliases = client.get_registered_model(MODEL).aliases + if any(alias.alias in ("champion", "challenger") for alias in aliases): + raise AssertionError("SM-28a must not set promotion aliases.") + for result in (baseline, candidate): + artifacts = {item.path for item in client.list_artifacts(result.run_id)} + if not {"model", "candidate_comparison.json", "skyulf_pipeline_config.json"} <= artifacts: + raise AssertionError("Candidate run is missing required evidence artifacts.") + print( + json.dumps( + { + "source": SOURCE, + "source_version": source_version, + "baseline_version": baseline.model_version, + "baseline_run_id": baseline.run_id, + "candidate_version": candidate.model_version, + "candidate_run_id": candidate.run_id, + "training_rows": candidate.training_rows, + "holdout_rows": candidate.holdout_rows, + "unavailable_labels": candidate.unavailable_labels, + "candidate_rmse": candidate.comparison.candidate_metrics["heldout_rmse"], + "baseline_rmse": candidate.comparison.champion_metrics["heldout_rmse"], + "eligible": candidate.comparison.eligible, + "reason": candidate.comparison.reason, + }, + sort_keys=True, + ) + ) + + +main() diff --git a/skyulf-core/skyulf/integrations/databricks/__init__.py b/skyulf-core/skyulf/integrations/databricks/__init__.py index e7ac5a6ff..1b31fe5a7 100644 --- a/skyulf-core/skyulf/integrations/databricks/__init__.py +++ b/skyulf-core/skyulf/integrations/databricks/__init__.py @@ -11,6 +11,13 @@ ) from .local_incremental import IncrementalBatchResult, run_incremental_local_batch from .local_publish import run_local_batch +from .local_retraining import ( + LocalCandidateResult, + LocalTrainingSpec, + read_training_snapshot, + split_labeled_snapshot, + train_local_candidate, +) from .local_sdk import ( InputSource, LocalWorkflowConfig, @@ -32,6 +39,8 @@ "LocalWorkflowConfig", "LocalScoreResult", "LocalSourceSpec", + "LocalCandidateResult", + "LocalTrainingSpec", "ModelSelection", "OutputSink", "PreflightError", @@ -43,8 +52,11 @@ "preflight_local", "prepare_local_workflow", "read_local_source", + "read_training_snapshot", "run_batch", "run_incremental_local_batch", "run_local_batch", "score_local_source", + "split_labeled_snapshot", + "train_local_candidate", ] diff --git a/skyulf-core/skyulf/integrations/databricks/local_retraining.py b/skyulf-core/skyulf/integrations/databricks/local_retraining.py new file mode 100644 index 000000000..119213388 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_retraining.py @@ -0,0 +1,324 @@ +"""Bounded, label-aware local candidate training from a pinned Delta snapshot. + +This adapter uses Spark only for a narrow, bounded read. Fit and evaluation run +on the recorded local engine; publication never changes a registry alias. +""" + +from __future__ import annotations + +import math +import pickle +from dataclasses import asdict, dataclass +from datetime import UTC, datetime +from importlib.metadata import version +from pathlib import Path +from typing import Any, Literal + +import pandas as pd +import polars as pl + +from ...data.dataset import SplitDataset +from ...inference.local_evaluation import evaluate_local_holdout +from ..mlflow.registry import register_model, resolve_model +from ..mlflow.tracking import TrackingConfig, track_run +from ..mlflow.validation import ModelComparisonReport, compare_registered_local_models +from ._contracts import column_name, table_name +from .local_batch import _frame_bytes, fit_local_workflow + + +@dataclass(frozen=True, slots=True, kw_only=True) +class LocalTrainingSpec: + """Pin the source version, label cutoff, split and local memory budget.""" + + table: str + version: int + start: datetime + holdout_start: datetime + cutoff: datetime + event_column: str + label_time_column: str + row_keys: tuple[str, ...] + input_columns: tuple[str, ...] + target_column: str + max_rows: int + max_bytes: int + + def __post_init__(self) -> None: + """Reject ambiguous or unsafe snapshots before opening a Spark reader.""" + table_name(self.table) + if type(self.version) is not int or self.version < 0: + raise ValueError("version must be a nonnegative Delta snapshot version.") + for name in ("start", "holdout_start", "cutoff"): + value = getattr(self, name) + if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware.") + if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( + tzinfo=None + ): + raise ValueError(f"{name} is not a valid local instant.") + if not self.start < self.holdout_start < self.cutoff: + raise ValueError("Require start < holdout_start < cutoff.") + if not self.row_keys or not self.input_columns: + raise ValueError("row_keys and input_columns must be nonempty.") + names = ( + *self.row_keys, + *self.input_columns, + self.target_column, + self.event_column, + self.label_time_column, + ) + for name in names: + column_name(name) + if len({name.lower() for name in names}) != len(names): + raise ValueError("Training columns must be distinct.") + if type(self.max_rows) is not int or self.max_rows <= 0: + raise ValueError("max_rows must be positive.") + if type(self.max_bytes) is not int or self.max_bytes <= 0: + raise ValueError("max_bytes must be positive.") + + @property + def dataset_id(self) -> str: + """Describe the immutable evaluation rows and temporal selection.""" + return ( + f"{self.table}@{self.version}/event[{self.start.astimezone(UTC).isoformat()}," + f"{self.cutoff.astimezone(UTC).isoformat()})/holdout>=" + f"{self.holdout_start.astimezone(UTC).isoformat()}" + f"/label<={self.cutoff.astimezone(UTC).isoformat()}" + f"/event_column={self.event_column}/label_column={self.label_time_column}" + f"/target={self.target_column}/keys={','.join(self.row_keys)}" + ) + + +@dataclass(frozen=True, slots=True) +class LocalCandidateResult: + """Record a concrete candidate and its read-only comparison evidence.""" + + run_id: str + model_name: str + model_version: str + model_digest: str + dataset_id: str + training_rows: int + holdout_rows: int + unavailable_labels: int + engine: str + comparison: ModelComparisonReport + + +def read_training_snapshot(spark: Any, spec: LocalTrainingSpec) -> pd.DataFrame: + """Project and cap a versioned Delta read before materializing driver rows.""" + if not isinstance(spec, LocalTrainingSpec): + raise TypeError("spec must be LocalTrainingSpec.") + names = ( + *spec.row_keys, + spec.event_column, + spec.label_time_column, + *spec.input_columns, + spec.target_column, + ) + source = spark.read.format("delta").option("versionAsOf", spec.version).table(spec.table) + start = spec.start.astimezone(UTC).isoformat() + cutoff = spec.cutoff.astimezone(UTC).isoformat() + selected = ( + source.where( + f"{column_name(spec.event_column)} >= TIMESTAMP '{start}' AND " + f"{column_name(spec.event_column)} < TIMESTAMP '{cutoff}'" + ) + .select(*names) + .orderBy(spec.event_column, *spec.row_keys) + .limit(spec.max_rows + 1) + ) + records: list[dict[str, Any]] = [] + serialized_bytes = 0 + for row in selected.toLocalIterator(): + if len(records) >= spec.max_rows: + raise ValueError("Training source exceeds max_rows.") + record = row.asDict(recursive=True) if hasattr(row, "asDict") else dict(row) + serialized_bytes += len(pickle.dumps(record, protocol=pickle.HIGHEST_PROTOCOL)) + if serialized_bytes > spec.max_bytes: + raise ValueError("Training source exceeds max_bytes.") + records.append(record) + frame = pd.DataFrame.from_records(records, columns=names) + if _frame_bytes(frame) > spec.max_bytes: + raise ValueError("Training frame exceeds max_bytes.") + return frame + + +def split_labeled_snapshot( + frame: pd.DataFrame, spec: LocalTrainingSpec +) -> tuple[pd.DataFrame, pd.DataFrame, int]: + """Make disjoint, reproducible fit and holdout sets from available labels.""" + if not isinstance(frame, pd.DataFrame) or not isinstance(spec, LocalTrainingSpec): + raise TypeError("Expected a pandas frame and LocalTrainingSpec.") + expected = ( + *spec.row_keys, + spec.event_column, + spec.label_time_column, + *spec.input_columns, + spec.target_column, + ) + if not set(expected).issubset(frame.columns): + raise ValueError("Training snapshot is missing required columns.") + if frame.loc[:, list(spec.row_keys)].isna().any().any(): + raise ValueError("Training row keys must not be null.") + if frame.duplicated(subset=list(spec.row_keys)).any(): + raise ValueError("Training row keys must be unique.") + events = pd.to_datetime(frame[spec.event_column], utc=True, errors="raise") + labels = pd.to_datetime(frame[spec.label_time_column], utc=True, errors="raise") + if events.isna().any() or (events < spec.start).any() or (events >= spec.cutoff).any(): + raise ValueError("Training event time falls outside the pinned window.") + if ((labels < events) & labels.notna()).any(): + raise ValueError("Label availability precedes event time.") + available = labels.notna() & (labels <= spec.cutoff) + if frame.loc[available, spec.target_column].isna().any(): + raise ValueError("Available labels must have nonnull targets.") + selected = frame.loc[available].copy() + selected[spec.event_column] = events.loc[available] + selected = selected.sort_values([spec.event_column, *spec.row_keys], kind="stable") + holdout = selected[spec.event_column] >= spec.holdout_start + columns = [*spec.input_columns, spec.target_column] + train_frame = selected.loc[~holdout, columns].reset_index(drop=True) + holdout_frame = selected.loc[holdout, columns].reset_index(drop=True) + if len(train_frame) < 2 or len(holdout_frame) < 2: + raise ValueError("Training and temporal holdout each need at least two labeled rows.") + return train_frame, holdout_frame, int((~available).sum()) + + +def _log_local_model(artifact_path: str | Path, *, run_id: str, tracking_uri: str) -> str: + """Import the optional MLflow pyfunc package only for a tracked run.""" + from ..mlflow.local_model import log_local_model # noqa: PLC0415 + + return log_local_model( + artifact_path, run_id=run_id, artifact_path="model", tracking_uri=tracking_uri + ) + + +def train_local_candidate( + spark: Any, + spec: LocalTrainingSpec, + config: dict[str, Any], + *, + model_name: str, + tracking_uri: str, + registry_uri: str, + experiment_name: str, + run_name: str, + artifact_path: str | Path, + metric: str, + min_improvement: float, + engine: Literal["pandas", "polars"] = "pandas", + champion_version: str | None = None, + quality_threshold: float | None = None, +) -> LocalCandidateResult: + """Fit, log, register and compare a candidate without changing any aliases.""" + if not isinstance(spec, LocalTrainingSpec): + raise TypeError("spec must be LocalTrainingSpec.") + if engine not in ("pandas", "polars"): + raise ValueError("engine must be pandas or polars.") + if ( + type(min_improvement) not in (int, float) + or not math.isfinite(min_improvement) + or min_improvement < 0 + ): + raise ValueError("min_improvement must be a finite nonnegative number.") + if quality_threshold is not None and ( + type(quality_threshold) not in (int, float) or not math.isfinite(quality_threshold) + ): + raise ValueError("quality_threshold must be a finite number or None.") + if champion_version is not None and ( + type(champion_version) is not str + or not champion_version.isdecimal() + or int(champion_version) <= 0 + ): + raise ValueError("champion_version must be a concrete positive version.") + champion = ( + resolve_model( + model_name, + version=champion_version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + if champion_version is not None + else None + ) + frame = read_training_snapshot(spark, spec) + train_frame, holdout, unavailable = split_labeled_snapshot(frame, spec) + native_train = pl.from_pandas(train_frame) if engine == "polars" else train_frame + native_holdout = pl.from_pandas(holdout) if engine == "polars" else holdout + artifact = fit_local_workflow( + config, + SplitDataset(train=native_train, test=native_train.head(0)), + target_column=spec.target_column, + artifact_path=artifact_path, + max_rows=spec.max_rows, + max_bytes=spec.max_bytes, + ) + metrics = evaluate_local_holdout(artifact, native_holdout, target_column=spec.target_column) + if metric not in metrics or not math.isfinite(metrics[metric]): + raise ValueError("Selected metric is unavailable or non-finite on the holdout.") + tracking = TrackingConfig( + enabled=True, + tracking_uri=tracking_uri, + experiment_name=experiment_name, + failure_policy="raise", + ) + with track_run(tracking, run_name=run_name) as run: + if run.run_id is None: + raise RuntimeError("MLflow did not provide a run ID.") + run.log_config(config, artifact_file="skyulf_pipeline_config.json") + run.log_params( + { + "source_table": spec.table, + "source_version": spec.version, + "training_rows": len(train_frame), + "holdout_rows": len(holdout), + "unavailable_labels": unavailable, + "target_column": spec.target_column, + "model_digest": artifact.manifest.pipeline_sha256, + "engine": engine, + "code_version": version("skyulf-core"), + } + ) + run.set_tags({"dataset_id": spec.dataset_id, "phase": "candidate_training"}) + run.log_metrics(metrics) + model_uri = _log_local_model(artifact_path, run_id=run.run_id, tracking_uri=tracking_uri) + run_id = run.run_id + registered = register_model( + model_uri, + model_name, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + candidate = resolve_model( + model_name, + version=str(registered.version), + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + report = compare_registered_local_models( + candidate, + champion, + native_holdout, + target_column=spec.target_column, + dataset_id=spec.dataset_id, + metric=metric, + min_improvement=min_improvement, + max_rows=spec.max_rows, + max_bytes=spec.max_bytes, + quality_threshold=quality_threshold, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + run.client.log_dict(run_id, asdict(report), "candidate_comparison.json") + return LocalCandidateResult( + run_id=run_id, + model_name=model_name, + model_version=candidate.version, + model_digest=candidate.digest or "", + dataset_id=spec.dataset_id, + training_rows=len(train_frame), + holdout_rows=len(holdout), + unavailable_labels=unavailable, + engine=engine, + comparison=report, + ) diff --git a/skyulf-core/tests/integrations/test_databricks_local_retraining.py b/skyulf-core/tests/integrations/test_databricks_local_retraining.py new file mode 100644 index 000000000..a9dc3fa8e --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_local_retraining.py @@ -0,0 +1,262 @@ +"""Label-aware local candidate training from pinned Databricks snapshots.""" + +from contextlib import contextmanager +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pandas as pd +import polars as pl +import pytest + +from skyulf.data.dataset import SplitDataset +from skyulf.integrations.databricks import local_retraining as retraining + + +def _spec(**changes): + """Keep training, holdout and label cutoffs explicit in tests.""" + values = { + "table": "workspace.test.labels", + "version": 4, + "start": datetime(2026, 1, 1, tzinfo=UTC), + "holdout_start": datetime(2026, 2, 1, tzinfo=UTC), + "cutoff": datetime(2026, 3, 1, tzinfo=UTC), + "event_column": "event_time", + "label_time_column": "label_at", + "row_keys": ("id",), + "input_columns": ("x",), + "target_column": "target", + "max_rows": 10, + "max_bytes": 10000, + } + values.update(changes) + return retraining.LocalTrainingSpec(**values) + + +def _frame(): + """Include an unavailable label and rows straddling the temporal holdout.""" + return pd.DataFrame( + { + "id": [3, 1, 4, 2, 5], + "event_time": pd.to_datetime( + ["2026-02-10", "2026-01-10", "2026-02-11", "2026-01-11", "2026-02-12"], utc=True + ), + "label_at": pd.to_datetime( + ["2026-02-15", "2026-01-15", "2026-03-02", "2026-01-16", "2026-02-16"], utc=True + ), + "x": [3.0, 1.0, 4.0, 2.0, 5.0], + "target": [6.0, 2.0, 8.0, 4.0, 10.0], + } + ) + + +def test_split_excludes_late_labels_and_preserves_temporal_boundary(): + """A label unavailable at cutoff must never enter fit or evaluation.""" + train, holdout, skipped = retraining.split_labeled_snapshot(_frame(), _spec()) + assert train["x"].tolist() == [1.0, 2.0] + assert holdout["x"].tolist() == [3.0, 5.0] + assert skipped == 1 + assert "event_time" not in train.columns + + +def test_split_is_reproducible_under_source_row_reordering(): + """Snapshot row order cannot change the train or holdout membership.""" + first = retraining.split_labeled_snapshot(_frame(), _spec()) + second = retraining.split_labeled_snapshot(_frame().sample(frac=1, random_state=4), _spec()) + pd.testing.assert_frame_equal(first[0], second[0]) + pd.testing.assert_frame_equal(first[1], second[1]) + assert first[2] == second[2] + + +def test_split_rejects_event_after_label_and_unpinned_source(): + """Invalid temporal provenance must fail before training begins.""" + frame = _frame() + frame.loc[0, "label_at"] = pd.Timestamp("2026-02-01", tz="UTC") + with pytest.raises(ValueError, match="event time"): + retraining.split_labeled_snapshot(frame, _spec()) + with pytest.raises(ValueError, match="version"): + _spec(version=None) + + +def test_reader_pins_projects_and_limits_before_collecting(): + """Training must not materialize a whole unversioned Delta table.""" + source = MagicMock() + source.read.format.return_value = source.read + source.read.option.return_value = source.read + source.read.table.return_value = source + source.where.return_value = source + source.select.return_value = source + source.orderBy.return_value = source + source.limit.return_value = source + source.toLocalIterator.return_value = iter([_frame().iloc[0].to_dict()]) + frame = retraining.read_training_snapshot(source, _spec()) + source.read.option.assert_called_once_with("versionAsOf", 4) + source.where.assert_called_once() + source.select.assert_called_once_with("id", "event_time", "label_at", "x", "target") + source.limit.assert_called_once_with(11) + assert len(frame) == 1 + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_temporal_split_fits_real_skyulf_pipeline_without_holdout_leakage(tmp_path, engine): + """Both local engines must fit on past labels and score unseen later rows.""" + train, holdout, _ = retraining.split_labeled_snapshot(_frame(), _spec()) + native_train = pl.from_pandas(train) if engine == "polars" else train + native_holdout = pl.from_pandas(holdout) if engine == "polars" else holdout + artifact = retraining.fit_local_workflow( + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + SplitDataset(train=native_train, test=native_train.head(0)), + target_column="target", + artifact_path=tmp_path / engine, + max_rows=10, + max_bytes=10000, + ) + metrics = retraining.evaluate_local_holdout(artifact, native_holdout, target_column="target") + assert metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) + + +def test_failed_candidate_never_mutates_champion(monkeypatch, tmp_path): + """A failed publication leaves promotion to an explicit later operation.""" + spec = _spec() + monkeypatch.setattr(retraining, "read_training_snapshot", lambda spark, request: _frame()) + monkeypatch.setattr( + retraining, + "fit_local_workflow", + lambda *args, **kwargs: SimpleNamespace(manifest=SimpleNamespace(pipeline_sha256="a" * 64)), + ) + monkeypatch.setattr( + retraining, "evaluate_local_holdout", lambda *args, **kwargs: {"heldout_rmse": 0.1} + ) + monkeypatch.setattr(retraining, "_log_local_model", lambda *args, **kwargs: "runs:/run/model") + monkeypatch.setattr( + retraining, + "register_model", + lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("publish failed")), + ) + monkeypatch.setattr( + retraining, + "resolve_model", + lambda *args, **kwargs: pytest.fail("alias must not be read before publish"), + ) + + @contextmanager + def fake_run(*args, **kwargs): + """Let publication fail after recording without contacting MLflow.""" + yield SimpleNamespace( + run_id="run", + log_config=lambda *args, **kwargs: None, + log_params=lambda *args, **kwargs: None, + set_tags=lambda *args, **kwargs: None, + log_metrics=lambda *args, **kwargs: None, + ) + + monkeypatch.setattr(retraining, "track_run", fake_run) + with pytest.raises(RuntimeError, match="publish failed"): + retraining.train_local_candidate( + None, + spec, + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + model_name="workspace.test.model", + tracking_uri="file:unused", + registry_uri="file:unused", + experiment_name="test", + run_name="candidate", + artifact_path=tmp_path / "artifact", + metric="heldout_rmse", + min_improvement=0, + ) + + +def test_invalid_comparison_request_fails_before_mlflow_publication(monkeypatch, tmp_path): + """An unusable metric must not create an orphan candidate version.""" + monkeypatch.setattr(retraining, "read_training_snapshot", lambda spark, request: _frame()) + monkeypatch.setattr( + retraining, + "fit_local_workflow", + lambda *args, **kwargs: SimpleNamespace(manifest=SimpleNamespace(pipeline_sha256="a" * 64)), + ) + monkeypatch.setattr( + retraining, "evaluate_local_holdout", lambda *args, **kwargs: {"heldout_rmse": 0.1} + ) + monkeypatch.setattr( + retraining, + "register_model", + lambda *args, **kwargs: pytest.fail("invalid comparison must not register"), + ) + with pytest.raises(ValueError, match="Selected metric"): + retraining.train_local_candidate( + None, + _spec(), + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + model_name="workspace.test.model", + tracking_uri="file:unused", + registry_uri="file:unused", + experiment_name="test", + run_name="candidate", + artifact_path=tmp_path / "artifact", + metric="heldout_not_a_metric", + min_improvement=0, + ) + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_candidate_workflow_logs_and_registers_without_alias(monkeypatch, tmp_path, engine): + """A real local MLflow run must retain model, metrics and comparison evidence.""" + import mlflow + + x = list(range(12)) + frame = pd.DataFrame( + { + "id": x, + "event_time": pd.to_datetime(["2026-01-10"] * 8 + ["2026-02-10"] * 4, utc=True), + "label_at": pd.to_datetime(["2026-01-11"] * 8 + ["2026-02-11"] * 4, utc=True), + "x": pd.Series(x, dtype="float64"), + "target": pd.Series([2 * value for value in x], dtype="float64"), + } + ) + monkeypatch.setattr(retraining, "read_training_snapshot", lambda spark, request: frame) + store = f"sqlite:///{(tmp_path / 'registry.db').as_posix()}" + client = mlflow.MlflowClient(tracking_uri=store, registry_uri=store) + client.create_experiment("candidate_test", artifact_location=(tmp_path / "mlruns").as_uri()) + result = retraining.train_local_candidate( + None, + _spec(max_rows=12, max_bytes=20000), + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + model_name=f"candidate_{engine}", + tracking_uri=store, + registry_uri=store, + experiment_name="candidate_test", + run_name=engine, + artifact_path=tmp_path / "artifact", + metric="heldout_rmse", + min_improvement=0, + engine=engine, + ) + run = client.get_run(result.run_id) + artifacts = {artifact.path for artifact in client.list_artifacts(result.run_id)} + assert result.model_version == "1" + assert result.training_rows == 8 and result.holdout_rows == 4 + assert result.comparison.reason == "no_champion" + assert run.data.metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) + assert "candidate_comparison.json" in artifacts + assert "model" in artifacts + next_result = retraining.train_local_candidate( + None, + _spec(max_rows=12, max_bytes=20000), + {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + model_name=f"candidate_{engine}", + tracking_uri=store, + registry_uri=store, + experiment_name="candidate_test", + run_name=f"{engine}-challenger", + artifact_path=tmp_path / "artifact2", + metric="heldout_rmse", + min_improvement=0, + engine=engine, + champion_version=result.model_version, + ) + assert next_result.model_version == "2" + assert next_result.comparison.champion_version == "1" + assert next_result.comparison.eligible is False + with pytest.raises(Exception, match="alias|Alias"): + client.get_model_version_by_alias(result.model_name, "champion") From 749894ab895ac029813874ba3a1516f47e4dd885 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 15:13:07 +0300 Subject: [PATCH 45/85] feat: add local-engine Databricks bundle template Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 8 + docs/user_guide/databricks_bundle.md | 65 ++++++ .../spark_and_mlflow/05-sm20-bundle-plan.md | 21 +- ...21-sm20a-local-bundle-validation-report.md | 89 ++++++++ initiatives/spark_and_mlflow/HANDOFF.md | 11 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 33 ++- mkdocs.yml | 1 + .../databricks_local_sm20a_rehearsal.py | 140 +++++++++++++ .../databricks_template_schema.json | 33 +++ .../template/{{.project_name}}/README.md.tmpl | 52 +++++ .../config/workflow.json.tmpl | 30 +++ .../{{.project_name}}/databricks.yml.tmpl | 16 ++ .../resources/workflow.jobs.yml | 88 ++++++++ .../{{.project_name}}/src/workflow.py | 194 ++++++++++++++++++ .../integration/test_sm20a_bundle_template.py | 121 +++++++++++ 15 files changed, 878 insertions(+), 24 deletions(-) create mode 100644 docs/user_guide/databricks_bundle.md create mode 100644 initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md create mode 100644 skyulf-core/examples/databricks_local_sm20a_rehearsal.py create mode 100644 templates/databricks/databricks_template_schema.json create mode 100644 templates/databricks/template/{{.project_name}}/README.md.tmpl create mode 100644 templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl create mode 100644 templates/databricks/template/{{.project_name}}/databricks.yml.tmpl create mode 100644 templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml create mode 100644 templates/databricks/template/{{.project_name}}/src/workflow.py create mode 100644 tests/integration/test_sm20a_bundle_template.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 5867af440..893c08379 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -28,6 +28,14 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added +- A custom local-engine Databricks Bundle template now generates five separate + serverless jobs for candidate training, read-only comparison, challenger + staging, explicit promotion and automatic incremental scoring. It uses the + existing Skyulf Core services and an editable pandas/Polars configuration. + An isolated generated Bundle passed strict validation, deployment, Polars + train/compare/stage/promote jobs, two 2-row Delta scoring runs and a no-op + replay. Existing predictions retained their pinned model version after alias + promotion. Scheduling, Spark FE/model execution and endpoints remain separate. - Explicit MLflow champion promotion and rollback revalidate a pinned local model comparison, acquire shared admission, check the expected alias version and record durable transition receipts. Local registry tests and an isolated diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md new file mode 100644 index 000000000..e4e3e7157 --- /dev/null +++ b/docs/user_guide/databricks_bundle.md @@ -0,0 +1,65 @@ +# Local-engine Databricks Bundle + +Skyulf's custom template creates a self-contained Databricks Bundle project +with separate jobs for candidate training, read-only model comparison, +challenger staging, explicit promotion and incremental batch scoring. Choose +`pandas` or `polars` when generating the project. The selected engine fits +feature engineering and the model, then applies the saved pipeline at scoring +time. Spark reads bounded Unity Catalog Delta rows and writes predictions; +this first Bundle does not distribute local feature engineering across Spark +workers. + +Generate a project from a Skyulf checkout: + +```powershell +databricks bundle init templates/databricks --output-dir ./generated +``` + +The four questions are project name, local engine, catalog and schema. The +generated project contains its own `databricks.yml`, `config/workflow.json`, +Skyulf job entry point and five job resources. It does not put a +`databricks.yml` in the Skyulf repository root. Follow the generated README +to build and place the matching Skyulf wheel in `dist/`, select real tables, +features, preprocessing/model configuration and temporal split, then provision +the source, target and admission tables. The generated JSON is an editable +starting point; there is no claim that arbitrary feature engineering can be +inferred from a table name. + +```powershell +databricks bundle validate --strict -t dev --profile +databricks bundle deploy -t dev --profile +databricks bundle run train -t dev --profile +``` + +Training pins a labeled Delta snapshot and temporal holdout. Skyulf logs the +fitted artifact and held-out metrics to MLflow and registers a concrete Unity +Catalog model version. Inspect that version and set `model_version` in the +config before deploying again and running `score`. The score job reads an +existing CDF-enabled Delta source, prepares the pinned local pipeline once, +and scores the initial bounded snapshot. Later runs read only new inserts +since the last committed Delta receipt. They require no date or source-version +input. An empty repeat is a no-op. Source updates and deletes are rejected +until a rescore policy is chosen. Keep the same admission control row for all +writers to the target. + +```powershell +databricks bundle run score -t dev --profile +# Add new rows to the source Delta table. +databricks bundle run score -t dev --profile +``` + +`compare` reads two configured concrete versions against the same pinned +holdout. It never changes aliases. With a separately initialized `@champion` +alias and a provisioned alias admission row, `stage` can assign an eligible +candidate to `@challenger`; `promote` then moves it to `@champion` and stores +the prior version as `@previous_champion`. These are explicit jobs, and they +recheck the comparison and expected champion version. The first candidate +does not become champion automatically. The scoring job continues to use its +configured concrete version until the operator changes it. Alias promotion +does not rewrite old prediction rows. + +The template has no schedule. Add a scoring schedule only after checking the +source's append policy and data permissions. Monthly retraining scheduling, +full-history rescores, Spark-native execution and endpoints are separate +extensions. See [the local SDK](databricks_local_sdk.md) for the underlying +configuration and [MLflow registry](mlflow_registry.md) for model resolution. diff --git a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md index 0315b28a9..1d3d72d6b 100644 --- a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md +++ b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md @@ -1,8 +1,8 @@ # SM-20: local-first Databricks Bundle, then Spark enhancement -Updated: 2026-09-23. Planning only; no generated project has been created -by this plan. SM-15L proved explicit-period writes and SM-15I proved -automatic new-row scoring. The generated Bundle still needs validation. +Updated: 2026-09-24. The first local-engine Bundle is implemented and validated; +see [SM-20a live evidence](21-sm20a-local-bundle-validation-report.md). SM-15L +proved explicit-period writes and SM-15I proved automatic new-row scoring. The [open queue](OPEN_QUEUE.md) owns status and task order. ## Outcome and engine boundary @@ -76,23 +76,18 @@ The SQL Connector is an alternative, not a required part of the first Bundle. then compares it without automatic promotion. The optional monthly schedule is wired in SM-28b after the Bundle exists. -The custom template should generate a project with these responsibilities: +The delivered custom template generates a project with these responsibilities: ```text templates/databricks/databricks_template_schema.json templates/databricks/template/{{.project_name}}/databricks.yml.tmpl -templates/databricks/template/{{.project_name}}/resources/train_job.yml.tmpl -templates/databricks/template/{{.project_name}}/resources/compare_job.yml.tmpl -templates/databricks/template/{{.project_name}}/resources/promote_job.yml.tmpl -templates/databricks/template/{{.project_name}}/resources/batch_job.yml.tmpl -templates/databricks/template/{{.project_name}}/src/train.py.tmpl -templates/databricks/template/{{.project_name}}/src/compare.py.tmpl -templates/databricks/template/{{.project_name}}/src/promote.py.tmpl -templates/databricks/template/{{.project_name}}/src/score_month.py.tmpl +templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml +templates/databricks/template/{{.project_name}}/src/workflow.py templates/databricks/template/{{.project_name}}/README.md.tmpl ``` -The generated Python files call Skyulf services; they do not copy FE, model, +The generated Python entry point calls Skyulf services; it does not copy FE, model, MLflow, comparison, promotion or Delta publication implementations. Separate train, compare, explicit-promote and score jobs preserve the decision boundary. The first verified cross-job diff --git a/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md b/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md new file mode 100644 index 000000000..5cc8f8c95 --- /dev/null +++ b/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md @@ -0,0 +1,89 @@ +# SM-20a local-engine Bundle validation - 2026-09-24 + +Status: **PASS** for the first bounded pandas/Polars Databricks Bundle. The +generated project, not only a direct SDK script, was initialized, strictly +validated, deployed and run through its own jobs in the `skyulf` workspace +profile. Target release remains 0.9.0. + +## Delivered contract + +`templates/databricks` asks for project name, local engine and existing UC +catalog/schema. It emits its own `databricks.yml`, editable workflow JSON, +one thin Skyulf entry point and five separate serverless jobs: `train`, +`compare`, `stage`, `promote` and `score`. Each job installs the matching +`skyulf-core` wheel and MLflow 3.16.1. The entry point delegates to the +existing Skyulf training, comparison, promotion and incremental scoring +services; it does not copy their feature engineering or model code. + +Training pins a Delta snapshot, bounded row/byte budget and temporal holdout. +Scoring pins a concrete registered model version and derives new source rows +from committed Delta receipts without per-run dates or source-version input. +The generated project has no schedule or automatic alias promotion. The first +`@champion` alias must be initialized explicitly before guarded staging and +promotion can operate. Production users must create the declared UC tables, +enable source CDF before new inserts and provision separate prediction/alias +admission rows as described in the generated README. + +## Local and template gates + +- `databricks bundle init templates/databricks --config-file ... --output-dir ...` + rendered the `skyulf_sm20a_r1` project with `engine=polars`. +- `databricks bundle validate --strict -t dev --profile skyulf` passed after + generation and after each test configuration change. +- Four focused tests passed. They pin engine propagation, no-date incremental + scoring, read-only comparison and the separate eligible stage gate. Ruff + lint and format checks passed for the new Python files. +- `mkdocs build --strict` passed for the new user guide page. + +## Isolated serverless rehearsal + +The test reused `workspace.skyulf_sm24a_20260923` and created only +`skyulf_sm20a_r1_*` tables/model under it, plus an owned dev Bundle workspace +folder. The one-time [data setup job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/91107508891891/runs/764189335699478?o=7474646244882000) +created an initial two-row CDF source, an empty prediction table and shared +score admission. It used real NYC taxi rows distinct from the training set. + +The first [Bundle training job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/899218432862214/runs/315074221066656?o=7474646244882000) +fit a Polars local pipeline and registered UC model version 1. The unchanged +[score job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/859114751278280/runs/623601582323720?o=7474646244882000) +predicted the two existing rows. After two new rows were appended, the same +[score job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/859114751278280/runs/863264817851057?o=7474646244882000) +predicted only those two. The verifier found four unique target keys, two +distinct two-row incremental receipts and one pinned model identity. A later +[empty replay](https://dbc-45604623-c18b.cloud.databricks.com/jobs/859114751278280/runs/764460864735699?o=7474646244882000) +returned `noop=true`, `input_count=0`, `output_count=0`, and unchanged target +Delta version 2. The strengthened verifier confirmed no later target commit. + +A second [Bundle training job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/899218432862214/runs/314248115042058?o=7474646244882000) +registered Polars candidate version 2 from the same pinned table version 0: +1,724 fit rows, 1,770 holdout rows and six labels unavailable by cutoff. Its +MLflow run `3d374999c4de42e0ade85c68fe554cb5` logged the full metrics and +comparison. Held-out RMSE was 2.088749 versus version 1's 2.252941; the +independent [compare job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/405452823167260/runs/202747732483469?o=7474646244882000) +returned `eligible=true` without moving an alias. A test-only bootstrap job +explicitly placed initial `@champion` on version 1 and provisioned the separate +alias admission row. The guarded [stage job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/34741568106407/runs/1089047629551174?o=7474646244882000) +placed version 2 on `@challenger`; the separate [promote job](https://dbc-45604623-c18b.cloud.databricks.com/jobs/733893149679423/runs/542805401182400?o=7474646244882000) +changed `@champion` from 1 to 2. The final +[alias verifier](https://dbc-45604623-c18b.cloud.databricks.com/jobs/1053643319015412/runs/423058698933542?o=7474646244882000) +confirmed `@champion=2`, `@previous_champion=1`, no `@challenger`, and all four +previous predictions still labeled model version 1. + +The first deploy failed locally because the CLI could not read the newly built +wheel under Windows ACLs; granting the CLI user read access resolved it. The +first alias verifier failed in test-only code because MLflow 3.16.1 returned +`RegisteredModel.aliases` as a mapping, rather than iterable alias objects. +That verifier was corrected and rerun successfully; no promotion rollback was +needed. Both failures remain recorded here rather than counted as passes. + +## Boundaries and next work + +The live run used Polars; pandas is covered by existing local/integration and +SM-15I live evidence, but this generated Bundle was not separately deployed +with pandas. The Bundle rehearsal did not force a remote Delta output failure; +the underlying SM-15I service has local failure/retry tests. The generated +project does not bootstrap the first champion, schedule retraining, perform +full-history rescores, distribute FE/model work with Spark, or create serving +endpoints. These remain explicit later tasks. Next is optional SM-28b monthly +retraining scheduling, followed by the other open-queue items in their listed +order. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index cfec90223..49c9ff2aa 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -22,14 +22,17 @@ UC promotion, conflict, rollback and restricted-principal denial passed; see and previous-champion aliases; see [its report](19-sm22c-lifecycle-alias-validation-report.md). SM-28a now trains from a pinned label-aware Delta snapshot and compares a registered candidate without promotion; see [its local and live report](20-sm28a-label-aware-retraining-report.md). -SM-20a is next. +SM-20a now generates and deploys the first local-engine Bundle. Its own jobs +passed Polars training, 2+2 incremental scoring/no-op, read-only comparison, +challenger staging and explicit promotion; see [the report](21-sm20a-local-bundle-validation-report.md). +SM-28b optional monthly retraining scheduling is next. ## Starting point - SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26, - SM-22a/b/c and SM-28a are complete. Start SM-20a from - [05-sm20-bundle-plan.md](05-sm20-bundle-plan.md), using the services in - [06-prebundle-model-lifecycle-plan.md](06-prebundle-model-lifecycle-plan.md). + SM-22a/b/c, SM-28a and SM-20a are complete. Start SM-28b from + [the open queue](OPEN_QUEUE.md), using the generated Bundle and the + [pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md). SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. A later [real NYC taxi rehearsal](15-sm15i-real-nyctaxi-live-report.md) diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index e74c7f33d..4d5a3a32a 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,8 +1,8 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26 and SM-22a/b/c/28a complete. SM-20a next. Target: 0.9.0.** -Next deliverable: the first working local-engine Bundle. Spark -expansion follows that Bundle. SM-15L +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a complete. SM-28b next. Target: 0.9.0.** +Next deliverable: optional monthly local retraining schedule. Spark +expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -12,7 +12,8 @@ The [SM-20 Bundle plan](05-sm20-bundle-plan.md) remains the packaging gate. Historical completion evidence is preserved in [OPEN_QUEUE_tamamlanmakaydi.md](OPEN_QUEUE_tamamlanmakaydi.md). SM-26 added a local MLflow package; SM-15L and SM-15I validated UC writers. -No Bundle has been generated. +The first local-engine Bundle passed generated-project validation and live jobs; +see [SM-20a evidence](21-sm20a-local-bundle-validation-report.md). Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; @@ -49,8 +50,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-22b | Explicit promotion and rollback | SM-22a | DONE | Version-checked alias changes, prior/new-version receipt, conflicts and permission tests; [live evidence](18-sm22b-live-validation-report.md) | | SM-22c | Challenger and previous-champion aliases | SM-22b | DONE | Validated challenger staging; guarded three-alias promotion/rollback; legacy receipts and partial-write tests; [local and UC evidence](19-sm22c-lifecycle-alias-validation-report.md) | | SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-22c, SM-24a | DONE | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion; [evidence](20-sm28a-label-aware-retraining-report.md) | -| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | READY | Package tested train/compare/promote/incremental-score services; validate, deploy and run | -| SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | WAIT | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | +| SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | DONE | Generated/deployed Polars Bundle; train/compare/stage/promote and 2+2 incremental score/no-op live; [evidence](21-sm20a-local-bundle-validation-report.md) | +| SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | READY | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | | SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | LATER | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | @@ -90,7 +91,8 @@ in [04-databricks-integration-plan.md](04-databricks-integration-plan.md). temporal holdout; compare it without automatic promotion. 8. **SM-20a:** generate, validate, deploy and run the first local-engine Bundle using the [two-run rehearsal](05-sm20-bundle-plan.md) without manual dates - or source versions. Package the already-tested lifecycle services. + or source versions. Package the already-tested lifecycle services. **DONE:** + [generated-project and live evidence](21-sm20a-local-bundle-validation-report.md). 9. **After SM-20a:** SM-28b wires optional monthly retraining; SM-27 adds explicit `full_rebuild` alongside default `incremental_append`. SM-15L's `period_update` remains an explicit backfill. @@ -161,6 +163,23 @@ SM-17 requires the full tracked scope above. Some algorithms may need an explici alternative backend rather than an equivalent native Spark implementation; that decision must not hide missing support. SM-19 streaming remains optional and parked. +## SM-20a closure record - 2026-09-24 + +Inspected branch `090` at the SM-28a baseline and added the custom template, +generated-workflow tests, Databricks Bundle guide and isolated rehearsal example. +`databricks bundle init templates/databricks --config-file ... --output-dir ...`, +`databricks bundle validate --strict -t dev --profile skyulf`, +`databricks bundle deploy -t dev --profile skyulf` and Bundle `run` commands for +train/compare/stage/promote/score all succeeded in the test workspace. The +score job passed 2 initial + 2 new rows, then returned a no-op with target +version unchanged. `python -m pytest tests/integration/test_sm20a_bundle_template.py` +passed four tests; Ruff lint/format and `mkdocs build --strict` passed. The +first local wheel upload and a test-only alias verifier failed, were diagnosed, +corrected and rerun; [the report](21-sm20a-local-bundle-validation-report.md) +retains those failure details and live run links. This Bundle uses Polars for +the live test, and remote forced-write failure was not repeated. SM-28b is next; +SM-27, broad Spark work and endpoints remain later. + ## Bir görevi kapatma kaydı Her DONE satırına aynı dosyada aşağıdaki bilgileri içeren tarihli kayıt ekle: diff --git a/mkdocs.yml b/mkdocs.yml index 72b04f937..2e51e287b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -81,6 +81,7 @@ nav: - MLflow Registry (Development): user_guide/mlflow_registry.md - Databricks Batch (Development): user_guide/databricks_batch.md - Databricks Local SDK (Development): user_guide/databricks_local_sdk.md + - Databricks Local Bundle (Development): user_guide/databricks_bundle.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/skyulf-core/examples/databricks_local_sm20a_rehearsal.py b/skyulf-core/examples/databricks_local_sm20a_rehearsal.py new file mode 100644 index 000000000..69eb7a4ed --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm20a_rehearsal.py @@ -0,0 +1,140 @@ +# Databricks notebook source +"""Provision and verify the isolated two-run SM-20a Bundle rehearsal.""" + +import json +from typing import Any + +from pyspark.sql import functions as F # ty: ignore[unresolved-import] + +from skyulf.integrations.databricks.delta import table_identity +from skyulf.integrations.mlflow.promotion import alias_resource_id + +SCHEMA = "workspace.skyulf_sm24a_20260923" +RECORDS = "workspace.skyulf_nyctaxi_e2e_20260923.taxi_records" +SOURCE = f"{SCHEMA}.skyulf_sm20a_r1_source" +TARGET = f"{SCHEMA}.skyulf_sm20a_r1_predictions" +CONTROL = f"{SCHEMA}.skyulf_sm20a_r1_score_admission" +ALIAS_CONTROL = f"{SCHEMA}.skyulf_sm20a_r1_alias_admission" +MODEL = f"{SCHEMA}.skyulf_sm20a_r1_model" +FEATURES = ("trip_distance", "trip_duration_minutes", "pickup_hour", "pickup_weekday") + + +def _rows(spark: Any, first: int, last: int): + """Select disjoint real taxi keys without changing their raw features.""" + return ( + spark.table(RECORDS) + .where(F.col("split_index").between(first, last)) + .select("entity_id", *FEATURES) + ) + + +def setup(spark: Any) -> None: + """Create new append-only scoring tables and one shared admission row.""" + for table in (SOURCE, TARGET, CONTROL): + if spark.catalog.tableExists(table): + raise ValueError(f"Test table already exists: {table}") + initial = _rows(spark, 3701, 3702) + if initial.count() != 2: + raise AssertionError("Expected two real taxi rows for bootstrap.") + initial.write.format("delta").saveAsTable(SOURCE) + spark.sql(f"ALTER TABLE {SOURCE} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") + spark.sql( + f"CREATE TABLE {TARGET} (entity_id STRING, prediction DOUBLE, run_id STRING, " + "model_name STRING, model_version STRING) USING DELTA" + ) + spark.sql(f"CREATE TABLE {CONTROL} (target_id STRING, owner STRING) USING DELTA") + spark.sql( + f"INSERT INTO {CONTROL} SELECT :target_id, CAST(NULL AS STRING)", + args={"target_id": table_identity(spark, TARGET)}, + ).collect() + print(json.dumps({"source": SOURCE, "initial_rows": 2, "target": TARGET})) + + +def append(spark: Any) -> None: + """Add exactly two unseen keys after the first Bundle scoring job.""" + if spark.table(SOURCE).count() != 2 or spark.table(TARGET).count() != 2: + raise AssertionError("First scoring run must commit exactly two predictions.") + incoming = _rows(spark, 3703, 3704) + if incoming.count() != 2: + raise AssertionError("Expected two new real taxi rows.") + incoming.write.format("delta").mode("append").saveAsTable(SOURCE) + print(json.dumps({"source_rows": spark.table(SOURCE).count()})) + + +def bootstrap_alias(spark: Any) -> None: + """Explicitly establish the first champion and its separate shared admission.""" + import mlflow # noqa: PLC0415 - test-only Databricks MLflow boundary + + if spark.catalog.tableExists(ALIAS_CONTROL): + raise ValueError("Test alias admission table already exists.") + spark.sql(f"CREATE TABLE {ALIAS_CONTROL} (target_id STRING, owner STRING) USING DELTA") + spark.sql( + f"INSERT INTO {ALIAS_CONTROL} SELECT :target_id, CAST(NULL AS STRING)", + args={"target_id": alias_resource_id(MODEL)}, + ).collect() + client = mlflow.MlflowClient(tracking_uri="databricks", registry_uri="databricks-uc") + client.set_registered_model_alias(MODEL, "champion", "1") + if str(client.get_model_version_by_alias(MODEL, "champion").version) != "1": + raise AssertionError("Initial champion alias must point to version 1.") + print(json.dumps({"model": MODEL, "champion_version": "1"})) + + +def verify(spark: Any) -> None: + """Confirm two commits produced four unique, pinned-model predictions.""" + source = spark.table(SOURCE) + target = spark.table(TARGET) + if source.count() != 4 or target.count() != 4: + raise AssertionError("Second run must append only two new predictions.") + if target.select("entity_id").distinct().count() != 4: + raise AssertionError("Prediction keys must remain unique.") + if target.select("model_name", "model_version").distinct().count() != 1: + raise AssertionError("Both runs must pin the same model identity.") + identity = target.select("model_name", "model_version").first() + if identity.model_name != MODEL or identity.model_version != "1": + raise AssertionError("Predictions must use the configured concrete UC model version.") + if target.select("run_id").distinct().count() != 2: + raise AssertionError("The two source versions need distinct commit receipts.") + history = spark.sql(f"DESCRIBE HISTORY {TARGET}").select("version", "userMetadata").collect() + receipts = [ + (row.version, json.loads(row.userMetadata)) + for row in history + if row.userMetadata and '"skyulf_mode": "incremental_append"' in row.userMetadata + ] + if len(receipts) != 2 or sorted(receipt["input_count"] for _, receipt in receipts) != [2, 2]: + raise AssertionError("Expected two committed 2-row incremental receipts.") + if max(row.version for row in history) != max(version for version, _ in receipts): + raise AssertionError("The no-input replay must not create another target commit.") + print(json.dumps({"source_rows": 4, "prediction_rows": 4, "receipts": receipts})) + + +def verify_alias(spark: Any) -> None: + """Confirm promotion changed aliases without rewriting historical predictions.""" + import mlflow # noqa: PLC0415 - test-only Databricks MLflow boundary + + client = mlflow.MlflowClient(tracking_uri="databricks", registry_uri="databricks-uc") + aliases = { + str(alias): str(version) + for alias, version in client.get_registered_model(MODEL).aliases.items() + } + if aliases.get("champion") != "2" or aliases.get("previous_champion") != "1": + raise AssertionError("Promotion aliases did not reflect versions 2 and 1.") + if "challenger" in aliases: + raise AssertionError("Promoted candidate must no longer hold @challenger.") + prediction_versions = [ + row.model_version + for row in spark.table(TARGET).select("model_version").distinct().collect() + ] + if prediction_versions != ["1"]: + raise AssertionError("Existing predictions must retain their pinned model version.") + print(json.dumps({"aliases": aliases, "prediction_versions": prediction_versions})) + + +if __name__ == "__main__": + phase = globals()["dbutils"].widgets.get("phase") + { + "setup": setup, + "append": append, + "bootstrap_alias": bootstrap_alias, + "verify": verify, + "verify_alias": verify_alias, + }[phase](globals()["spark"]) diff --git a/templates/databricks/databricks_template_schema.json b/templates/databricks/databricks_template_schema.json new file mode 100644 index 000000000..740827d79 --- /dev/null +++ b/templates/databricks/databricks_template_schema.json @@ -0,0 +1,33 @@ +{ + "welcome_message": "Create a bounded Skyulf local-engine Databricks Bundle. Edit config/workflow.json for your data before running jobs.", + "properties": { + "project_name": { + "order": 1, + "type": "string", + "default": "skyulf_local", + "description": "Bundle name (letters, digits and underscores)", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "engine": { + "order": 2, + "type": "string", + "default": "pandas", + "description": "Local feature and model engine", + "enum": ["pandas", "polars"] + }, + "catalog": { + "order": 3, + "type": "string", + "default": "workspace", + "description": "Existing Unity Catalog catalog (simple identifier)", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "schema": { + "order": 4, + "type": "string", + "default": "default", + "description": "Existing Unity Catalog schema (simple identifier)", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + } + } +} diff --git a/templates/databricks/template/{{.project_name}}/README.md.tmpl b/templates/databricks/template/{{.project_name}}/README.md.tmpl new file mode 100644 index 000000000..f19b22d86 --- /dev/null +++ b/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -0,0 +1,52 @@ +# {{.project_name}} + +This is a Skyulf 0.9.0 local-engine Databricks Bundle. The selected fit and +prediction engine is **{{.engine}}**. Spark is used to read bounded Delta rows +and publish the prediction table; Skyulf runs feature engineering and model +prediction on the selected local engine. + +## Before the first run + +1. Put the matching, trusted `skyulf_core-0.9.0-py3-none-any.whl` in `dist/`. + From a Skyulf source checkout, run `uv build --wheel --no-build-isolation + --out-dir /dist skyulf-core`. Rebuild the wheel whenever the + source changes. The serverless job also installs MLflow 3.16.1. +2. Edit `config/workflow.json`: set real training and scoring tables, features, + temporal split, preprocessing/model config, memory bounds and the concrete + training Delta version. The generated values are examples, not a dataset. +3. Create the source and empty prediction Delta tables. Enable Change Data + Feed on the scoring source **before** new rows arrive. The prediction table + needs `row_keys`, `prediction`, `run_id`, `model_name`, and `model_version` + with types matching the Skyulf output. Create the separate score admission + table with `(target_id STRING, owner STRING)` and one row whose `target_id` + is the prediction table's Delta identity and `owner` is null. If using the + stage/promote jobs, create a separate alias admission table with the same + columns and one row with `target_id` equal to + `skyulf.integrations.mlflow.promotion.alias_resource_id(model_name)`. +4. Authenticate the Databricks CLI, then run `databricks bundle validate + --strict -t dev` and `databricks bundle deploy -t dev`. The CLI profile is + selected by `--profile`; no credentials are stored here. + +Run `databricks bundle run train -t dev` to train one candidate, log held-out +metrics and register its model. Inspect the resulting model version in Unity +Catalog, and set `model_version` in the JSON to that **concrete version** before +running `databricks bundle run score -t dev`. Redeploy after changing the +configuration. Each score run handles the initial bounded source snapshot or +only inserts since the last committed receipt. Run it again with no new rows +to see a no-op; no date or source-version argument is needed. Source updates +and deletes require a separate rescore policy. + +The first model has no champion by default. Once a champion alias has been +explicitly initialized, set `champion_version` and `candidate_version` to +concrete versions from the **same** pinned labeled holdout. The `compare` job +is read-only. `stage` and `promote` are separate manual jobs: they re-evaluate +the comparison and use the distributed alias admission row. Promotion requires +the matching candidate to have been staged as `@challenger`. Neither training +nor comparison changes aliases automatically. Keep scoring pinned to a +concrete `model_version` until you explicitly decide to move it; an alias +change does not rescore historical rows. + +The default jobs have no schedules. Add a scoring schedule after checking the +source append policy and table permissions. Optional retraining schedules, +full-history rescores, Spark feature engineering and endpoints are separate +future extensions. diff --git a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl new file mode 100644 index 000000000..286df2491 --- /dev/null +++ b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -0,0 +1,30 @@ +{ + "engine": "{{.engine}}", + "training_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_training", + "training_version": 0, + "score_source_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_source", + "prediction_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_predictions", + "score_admission_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_score_admission", + "alias_admission_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_alias_admission", + "model_name": "{{.catalog}}.{{.schema}}.{{.project_name}}_model", + "model_version": "1", + "champion_version": null, + "candidate_version": "2", + "row_keys": ["entity_id"], + "input_columns": ["feature_value"], + "target_column": "target", + "event_column": "event_time", + "label_time_column": "label_at", + "start": "2025-01-01T00:00:00+00:00", + "holdout_start": "2025-02-01T00:00:00+00:00", + "cutoff": "2025-03-01T00:00:00+00:00", + "max_rows": 10000, + "max_bytes": 67108864, + "metric": "heldout_rmse", + "min_improvement": 0.0, + "quality_threshold": null, + "pipeline": { + "preprocessing": [], + "modeling": {"type": "linear_regression"} + } +} diff --git a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl new file mode 100644 index 000000000..b0db21bc2 --- /dev/null +++ b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl @@ -0,0 +1,16 @@ +bundle: + name: {{.project_name}} + +include: + - resources/*.yml + +sync: + include: + - dist/*.whl + - config/workflow.json + - src/workflow.py + +targets: + dev: + default: true + mode: development diff --git a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml new file mode 100644 index 000000000..113e58560 --- /dev/null +++ b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml @@ -0,0 +1,88 @@ +resources: + jobs: + train: + name: ${bundle.name}_train + tasks: + - task_key: train + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: train + config_path: ${workspace.file_path}/config/workflow.json + experiment_name: ${workspace.root_path}/experiment + environment_key: skyulf + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 + compare: + name: ${bundle.name}_compare + tasks: + - task_key: compare + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: compare + config_path: ${workspace.file_path}/config/workflow.json + environment_key: skyulf + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 + stage: + name: ${bundle.name}_stage + tasks: + - task_key: stage + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: stage + config_path: ${workspace.file_path}/config/workflow.json + environment_key: skyulf + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 + promote: + name: ${bundle.name}_promote + tasks: + - task_key: promote + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: promote + config_path: ${workspace.file_path}/config/workflow.json + environment_key: skyulf + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 + score: + name: ${bundle.name}_score + tasks: + - task_key: score + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: score + config_path: ${workspace.file_path}/config/workflow.json + environment_key: skyulf + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 diff --git a/templates/databricks/template/{{.project_name}}/src/workflow.py b/templates/databricks/template/{{.project_name}}/src/workflow.py new file mode 100644 index 000000000..6c67eed0e --- /dev/null +++ b/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -0,0 +1,194 @@ +# Databricks notebook source +"""Run one bounded Skyulf local training, comparison, alias or scoring action.""" + +import json +import tempfile +from dataclasses import asdict +from datetime import datetime +from pathlib import Path +from typing import Any + +import polars as pl + +from skyulf.integrations.databricks import ( + InputSource, + LocalTrainingSpec, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + prepare_local_workflow, + read_training_snapshot, + run_incremental_local_batch, + split_labeled_snapshot, + train_local_candidate, +) +from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission +from skyulf.integrations.mlflow.promotion import ( + DeltaAliasAdmission, + promote_candidate, + stage_challenger, +) +from skyulf.integrations.mlflow.registry import resolve_model +from skyulf.integrations.mlflow.validation import compare_registered_local_models + + +def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: + """Keep the evaluation split and source snapshot identical across actions.""" + return LocalTrainingSpec( + table=config["training_table"], + version=config["training_version"], + start=datetime.fromisoformat(config["start"]), + holdout_start=datetime.fromisoformat(config["holdout_start"]), + cutoff=datetime.fromisoformat(config["cutoff"]), + event_column=config["event_column"], + label_time_column=config["label_time_column"], + row_keys=tuple(config["row_keys"]), + input_columns=tuple(config["input_columns"]), + target_column=config["target_column"], + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ) + + +def _comparison(spark: Any, config: dict[str, Any]) -> tuple[Any, Any]: + """Evaluate two pinned registry versions on one pinned held-out frame.""" + spec = _training_spec(config) + frame = read_training_snapshot(spark, spec) + _, heldout, _ = split_labeled_snapshot(frame, spec) + if config["engine"] == "polars": + heldout = pl.from_pandas(heldout) + model_name = config["model_name"] + tracking_uri = config.get("tracking_uri", "databricks") + registry_uri = config.get("registry_uri", "databricks-uc") + candidate = resolve_model( + model_name, + version=config["candidate_version"], + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + champion = resolve_model( + model_name, + version=config["champion_version"], + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + report = compare_registered_local_models( + candidate, + champion, + heldout, + target_column=spec.target_column, + dataset_id=spec.dataset_id, + metric=config["metric"], + min_improvement=config["min_improvement"], + max_rows=spec.max_rows, + max_bytes=spec.max_bytes, + quality_threshold=config.get("quality_threshold"), + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + return report, heldout + + +def run_action( + spark: Any, + config: dict[str, Any], + action: str, + *, + experiment_name: str | None = None, + artifact_path: str | Path | None = None, +) -> Any: + """Delegate each explicit job action to the corresponding Skyulf service.""" + tracking_uri = config.get("tracking_uri", "databricks") + registry_uri = config.get("registry_uri", "databricks-uc") + if action == "train": + if experiment_name is None or artifact_path is None: + raise ValueError("Training needs an experiment and temporary artifact path.") + return train_local_candidate( + spark, + _training_spec(config), + config["pipeline"], + model_name=config["model_name"], + tracking_uri=tracking_uri, + registry_uri=registry_uri, + experiment_name=experiment_name, + run_name="candidate_training", + artifact_path=artifact_path, + metric=config["metric"], + min_improvement=config["min_improvement"], + engine=config["engine"], + champion_version=config.get("champion_version"), + quality_threshold=config.get("quality_threshold"), + ) + if action == "score": + scoring = LocalWorkflowConfig( + runtime="databricks", + engine=config["engine"], + source=InputSource( + kind="uc_table", + table=config["score_source_table"], + read_mode="incremental", + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ), + model=ModelSelection( + kind="local_pipeline", + name=config["model_name"], + version=config["model_version"], + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ), + sink=OutputSink(kind="uc_delta", table=config["prediction_table"]), + ) + prepared = prepare_local_workflow(scoring) + return run_incremental_local_batch( + spark, + prepared, + row_keys=tuple(config["row_keys"]), + admission=DeltaTableAdmission(spark, config["score_admission_table"]), + ) + if action in {"compare", "stage", "promote"}: + report, heldout = _comparison(spark, config) + if action == "compare": + return report + if not report.eligible: + raise ValueError(f"Candidate is not eligible for {action}: {report.reason}.") + options = { + "target_column": config["target_column"], + "expected_champion_version": config["champion_version"], + "admission": DeltaAliasAdmission(spark, config["alias_admission_table"]), + "max_rows": config["max_rows"], + "max_bytes": config["max_bytes"], + "tracking_uri": tracking_uri, + "registry_uri": registry_uri, + } + if action == "stage": + return stage_challenger( + report, + heldout, + expected_challenger_version=config.get("expected_challenger_version"), + **options, + ) + return promote_candidate(report, heldout, **options) + raise ValueError(f"Unknown workflow action: {action}.") + + +def main() -> None: + """Read deployed configuration and job widgets only at the notebook boundary.""" + widgets = globals()["dbutils"].widgets + config = json.loads(Path(widgets.get("config_path")).read_text(encoding="utf-8")) + action = widgets.get("action") + with tempfile.TemporaryDirectory(prefix="skyulf-bundle-") as directory: + result = run_action( + globals()["spark"], + config, + action, + experiment_name=widgets.get("experiment_name") if action == "train" else None, + artifact_path=Path(directory) / "artifact" if action == "train" else None, + ) + output = json.dumps(asdict(result), default=str, allow_nan=False) + print(output) + globals()["dbutils"].notebook.exit(output) + + +if __name__ == "__main__": + main() diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py new file mode 100644 index 000000000..3497e518c --- /dev/null +++ b/tests/integration/test_sm20a_bundle_template.py @@ -0,0 +1,121 @@ +"""The generated local Bundle delegates to Skyulf's verified services.""" + +import importlib.util +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +WORKFLOW = ( + Path(__file__).resolve().parents[2] + / "templates/databricks/template/{{.project_name}}/src/workflow.py" +) + + +def _workflow(): + """Load the source copied unchanged into every generated project.""" + spec = importlib.util.spec_from_file_location("sm20a_workflow", WORKFLOW) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _config(): + """Keep a concrete, bounded source and model selection in each test.""" + return { + "engine": "polars", + "training_table": "workspace.test.training", + "training_version": 0, + "score_source_table": "workspace.test.source", + "prediction_table": "workspace.test.predictions", + "score_admission_table": "workspace.test.score_admission", + "alias_admission_table": "workspace.test.alias_admission", + "model_name": "workspace.test.model", + "model_version": "1", + "champion_version": "1", + "candidate_version": "2", + "row_keys": ["entity_id"], + "input_columns": ["x"], + "target_column": "target", + "event_column": "event_time", + "label_time_column": "label_at", + "start": "2026-01-01T00:00:00+00:00", + "holdout_start": "2026-02-01T00:00:00+00:00", + "cutoff": "2026-03-01T00:00:00+00:00", + "max_rows": 100, + "max_bytes": 100_000, + "metric": "heldout_rmse", + "min_improvement": 0.0, + "quality_threshold": None, + "pipeline": {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + } + + +def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, tmp_path): + """A training job must only produce a candidate with the chosen fit engine.""" + workflow = _workflow() + train = Mock(return_value=SimpleNamespace(model_version="2")) + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr(workflow, "promote_candidate", Mock(side_effect=AssertionError("promoted"))) + result = workflow.run_action( + object(), + _config(), + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.model_version == "2" + assert train.call_args.kwargs["engine"] == "polars" + assert train.call_args.args[1].version == 0 + + +def test_score_uses_incremental_service_without_period_or_source_version(monkeypatch): + """Recurring scoring must derive new inserts from committed Delta receipts.""" + workflow = _workflow() + prepare = Mock(return_value=object()) + score = Mock(return_value=SimpleNamespace(noop=False, input_count=2)) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "run_incremental_local_batch", score) + monkeypatch.setattr(workflow, "DeltaTableAdmission", Mock(return_value=object())) + result = workflow.run_action(object(), _config(), "score") + assert result.input_count == 2 + assert score.call_args.kwargs["row_keys"] == ("entity_id",) + assert "period_start" not in score.call_args.kwargs + assert "source_version" not in score.call_args.kwargs + assert prepare.call_args.args[0].engine == "polars" + + +def test_compare_is_read_only_and_stage_does_not_promote(monkeypatch): + """An eligible comparison must still need a separate staging and promotion job.""" + workflow = _workflow() + report = SimpleNamespace(eligible=True, reason="eligible") + heldout = object() + monkeypatch.setattr(workflow, "_comparison", Mock(return_value=(report, heldout))) + stage = Mock(return_value=SimpleNamespace(kind="challenger")) + promote = Mock(side_effect=AssertionError("promoted without approval")) + monkeypatch.setattr(workflow, "stage_challenger", stage) + monkeypatch.setattr(workflow, "promote_candidate", promote) + monkeypatch.setattr(workflow, "DeltaAliasAdmission", Mock(return_value=object())) + assert workflow.run_action(object(), _config(), "compare") is report + promote.assert_not_called() + result = workflow.run_action(object(), _config(), "stage") + assert result.kind == "challenger" + assert stage.call_args.kwargs["expected_champion_version"] == "1" + promote.assert_not_called() + + +def test_ineligible_candidate_cannot_reach_alias_writer(monkeypatch): + """An inferior candidate cannot stage or promote through the Bundle entry point.""" + workflow = _workflow() + monkeypatch.setattr( + workflow, + "_comparison", + Mock(return_value=(SimpleNamespace(eligible=False, reason="inferior"), object())), + ) + promote = Mock() + monkeypatch.setattr(workflow, "promote_candidate", promote) + with pytest.raises(ValueError, match="not eligible"): + workflow.run_action(object(), _config(), "promote") + promote.assert_not_called() From b4e6cae48d59b953592a9756de4839155c8f18ae Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 15:35:51 +0300 Subject: [PATCH 46/85] feat: add company-target local bundle variant Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 + docs/user_guide/databricks_bundle.md | 39 ++- .../22-sm20p-production-bundle-plan.md | 135 +++++++++++ initiatives/spark_and_mlflow/HANDOFF.md | 12 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 10 +- .../databricks_template_schema.json | 89 ++++++- .../examples/company-init.example.json | 14 ++ .../template/{{.project_name}}/README.md.tmpl | 46 +++- .../config/workflow.json.tmpl | 12 +- .../{{.project_name}}/databricks.yml.tmpl | 68 ++++++ .../resources/workflow.jobs.yml | 88 ------- .../resources/workflow.jobs.yml.tmpl | 223 ++++++++++++++++++ .../{{.project_name}}/src/workflow.py | 58 +++++ .../integration/test_sm20a_bundle_template.py | 142 +++++++++++ 14 files changed, 829 insertions(+), 112 deletions(-) create mode 100644 initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md create mode 100644 templates/databricks/examples/company-init.example.json delete mode 100644 templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml create mode 100644 templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 893c08379..95b34f3e7 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -10,6 +10,11 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed +- The local-engine Bundle template now separates personal serverless `dev` + from company `test/syst/prod` targets. Company jobs render policy-backed + clusters with a `PayingRegNo` tag, target catalogs and schema-bound UC + outputs. Personal and company target shapes passed strict CLI validation; + company policy execution and workspace access remain unverified. - Prediction Delta targets use `run_id`, `model_name` and `model_version` metadata columns. Existing test targets with the former `__skyulf_*` schema require a new target; the writer does not migrate tables. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index e4e3e7157..40ff5afe2 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -15,7 +15,13 @@ Generate a project from a Skyulf checkout: databricks bundle init templates/databricks --output-dir ./generated ``` -The four questions are project name, local engine, catalog and schema. The +Choose `personal` for a serverless `dev` target, or `company` for +policy-backed `test`, `syst` and `prod` targets. Personal mode asks for project +name, local engine, catalog and schema. Company mode asks for the workspace +host, target catalogs, input/metadata/result schemas, approved cluster policy +and `PayingRegNo`. Supply reviewed answers with `bundle init --config-file` +when the team has them; the company examples in the questionnaire are not +verified production settings. The generated project contains its own `databricks.yml`, `config/workflow.json`, Skyulf job entry point and five job resources. It does not put a `databricks.yml` in the Skyulf repository root. Follow the generated README @@ -25,6 +31,30 @@ the source, target and admission tables. The generated JSON is an editable starting point; there is no claim that arbitrary feature engineering can be inferred from a table name. +For company mode, copy and review +`templates/databricks/examples/company-init.example.json`, especially its +placeholder host and policy/tag values, then initialize with: + +```powershell +databricks bundle init templates/databricks --config-file --output-dir ./generated +``` + +| Job | Purpose | Normal cadence | +| --- | --- | --- | +| `train` | Fit and register a candidate with held-out MLflow metrics | When labeled data warrants a new model | +| `compare` | Read-only candidate/champion check | During model review | +| `stage` | Assign an eligible `@challenger` | Explicit release step | +| `promote` | Move staged candidate to `@champion` | Explicit approval step | +| `score` | Append predictions for new source inserts | Every scoring run | + +Only `score` is needed for recurring inference. A generated project has one +prediction table per model. Its existing labeled/source tables are inputs; the +score and alias admission tables are internal coordination state in the +metadata schema. They are not additional prediction outputs. Company `test` +adds a per-user suffix to output/model/control names, while `syst` and `prod` +use stable names in their respective catalogs. The notebook verifies that +these writes stay in the active target's catalog and schema. + ```powershell databricks bundle validate --strict -t dev --profile databricks bundle deploy -t dev --profile @@ -63,3 +93,10 @@ source's append policy and data permissions. Monthly retraining scheduling, full-history rescores, Spark-native execution and endpoints are separate extensions. See [the local SDK](databricks_local_sdk.md) for the underlying configuration and [MLflow registry](mlflow_registry.md) for model resolution. + +The personal `dev` Bundle was live-tested on serverless compute. Company +targets are generated but have not been validated or run in the company +workspace. Before a company rollout, verify host/catalog/policy/tag values, +validate each target with its own CLI profile and perform an isolated `test` +run. A different company workspace per target requires editing each target's +`workspace.host` after initialization. diff --git a/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md b/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md new file mode 100644 index 000000000..9faa2a3e8 --- /dev/null +++ b/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md @@ -0,0 +1,135 @@ +# SM-20P production Bundle implementation plan + +Updated: 2026-09-24. SM-20a is a live-validated **test/development Bundle +template**, not a company production deployment. This plan compares it with +`C:\Users\Murat\Downloads\codes-main (2)\codes-main\dbml-mlops-template` +and defines the work needed before calling a Skyulf-generated project +production-ready. No company production workspace has been deployed to. + +**Goal:** Generate a small-data Skyulf project that can be promoted through +test, system test and production environments without changing its ML code or +silently reusing test tables in production. + +**Architecture:** Keep Skyulf Core as the training/inference implementation. +Use Databricks Bundle targets and explicit target-specific catalog/schema +bindings. Keep recurring scoring separate from candidate training and manual +alias approval. Give production one prediction table for each model; keep +admission controls in a metadata schema and provision them once. + +**Tech stack:** Databricks Declarative Automation Bundles, serverless Python +jobs for the personal `dev` target, company-policy job clusters for +`test/syst/prod`, Unity Catalog Delta, Skyulf Core 0.9.0, MLflow 3.16.1. + +**Current status:** Target-specific name binding and both generated compute +variants have local tests and strict CLI shape validation. Company policy, +catalog permissions, cluster runtime and end-to-end execution are unverified. +The supplied company catalog/schema examples appear plausible to the user but +are not confirmed workspace settings. The CLI profile and `PayingRegNo` must be +verified with the company team before any company deployment. + +## What the company reference does differently + +| Concern | Company reference | SM-20a today | SM-20P decision | +| --- | --- | --- | --- | +| Environments | `ci/test/syst/prod` targets and catalog mapping | One `dev` target | Add `test/syst/prod` targets with explicit catalog mapping; retain `dev` for compatibility until migration | +| Isolation | Developer suffix on shared targets, empty suffix on shared production | Bundle workspace is isolated, UC table names are manually chosen | Separate non-prod names and control rows; fixed names in production | +| Data roles | Distinct raw/refined, metadata and result schemas | One initial catalog/schema prompt; JSON edited afterward | Ask for input, metadata and result schema mapping; allow explicit full table overrides | +| Compute | Company job clusters, policy lookup and cost tag | Serverless environment 4 | Personal `dev` is serverless; company targets use policy lookup and `PayingRegNo`, without a hardcoded policy ID | +| Workflow | Independent jobs plus an optional orchestration DAG | Independent train/compare/stage/promote/score jobs | Keep independent jobs; add a safe train→compare orchestration only if useful, never auto-promote | +| Extras | Feature store, endpoint, monitoring, dashboards, online store | None | Keep optional and later; do not generate unusable resources or 25 startup questions for the first small-data path | + +The company template's `databricks_template_schema.json` is a *questionnaire* +for `bundle init`, not the training or inference runtime configuration. Its +regression Bundle uses target variables such as `catalog_name` and +`resource_suffix`. Synced YAML/JSON files are not automatically rewritten with +target variable values; the job passes those values to its notebook. SM-20P +must preserve this distinction or it could write a test table from a prod job. + +## Resource contract + +One production model can use these UC objects, possibly in different schemas: + +| Object | Example role | Created by Skyulf project? | +| --- | --- | --- | +| Training table | Existing labeled input | No | +| Scoring source | Existing append-only input with CDF | No; only validate CDF and keys | +| Registered model | `metadata.customer_model` | Training registers it | +| Prediction table | `mlresult.customer_predictions` | One-time explicit setup, then score appends to the same table | +| Score admission table | `metadata.customer_score_admission` | One-time internal control table, not a second prediction output | +| Alias admission table | `metadata.customer_alias_admission` | One-time internal control table only if alias jobs are enabled | + +The two admission tables hold ownership/coordination rows. They do not contain +features or predictions and should live in an operations/metadata schema. +The SM-20a `skyulf_sm20a_r1_*` prefix was a unique live-test namespace, not a +required production naming convention. A production project should not ask an +operator to run every job in sequence for each new batch: the score job alone +handles each new source increment; candidate training is separate, and stage +and promote are deliberate review actions. + +## Implementation tasks + +### P1. Target-specific binding and generation + +**Files:** `templates/databricks/databricks_template_schema.json`, generated +`databricks.yml`, `config/workflow.json`, `resources/workflow.jobs.yml`, +`src/workflow.py`; extend `tests/integration/test_sm20a_bundle_template.py`. + +- [x] Define separate personal and company questionnaires. Personal has only + project/engine/catalog/schema; company adds host, test/syst/prod catalogs, + input/metadata/result schemas, policy lookup and cost tag. The company + example values require review. +- [x] Add target-specific Bundle variables and distinct workspace roots. + Non-prod has a per-developer suffix; production has no suffix. Production + must never inherit a test catalog; the company workspace host must be + explicitly reviewed for every target. +- [x] Resolve table/model names from the active target at the notebook boundary + before invoking Skyulf; test that the same generated source maps to disjoint + test/syst/prod identities. Allow an existing fully qualified source table + when training and scoring inputs are owned by another team. +- [x] `bundle init` both variants and `bundle validate --strict` the generated + personal `dev` and company `test/syst/prod` shapes. Company validation used + a **dummy policy ID and personal workspace host**, solely to validate Bundle + syntax. It does not prove company policy/compute, catalog access or execution. +- [ ] Confirm the actual company profiles, host/catalog mappings, policy and + tag, then validate against those profiles. No company deployment until then. + +### P2. One-time provisioning and normal job usage + +**Files:** generated `src/workflow.py`, `resources/workflow.jobs.yml`, README, +new focused provisioning tests and a revised Databricks user guide. + +- [ ] Provide one explicit setup/preflight action that checks input tables, + CDF, key/feature schema, permissions, local size budget and pinned model + output schema; then creates only the approved empty prediction table and + internal admission rows if absent. Never overwrite existing tables. +- [ ] Keep `score` as the only routine inference job. Add an optional paused + schedule (SM-28b owns cadence); no manual month or source version per run. +- [ ] Keep `train` separate. `compare` is read-only. `stage` and `promote` stay + manual with expected-version checks; no all-in-one automatic promotion. +- [ ] Explain that a new model version does not automatically rewrite earlier + predictions. Full-history rescore is SM-27, not a side effect of promotion. + +### P3. Company compute and deployment gate + +**Files:** generated target resources, docs, a new live validation report. + +- [x] Use serverless in the personal workspace and a looked-up cluster policy + plus `PayingRegNo` tag for company targets, per the user's direction. No + policy ID or credentials are stored in generated files. +- [ ] Validate the generated project against the designated **test** profile; + deploy and run setup, train, score initial/new-row/no-op and alias jobs in an + isolated test area. Check target model identity, row counts and Delta history. +- [ ] Validate `syst` and `prod` target configuration read-only with their + designated profiles. Actual deployment/compute in those environments needs + the user's environment details and explicit rollout decision. Do not mark + production-ready based only on the personal `skyulf` workspace. + +## Exit criteria and current gaps + +SM-20a already proves the Skyulf services and five Bundle jobs on personal +serverless compute. SM-20P closes the target mapping, provisioning and +company-compute gaps. The company reference's feature store, online serving, +monitoring, dashboard and cleanup resources are not implied by this small-data +Bundle; they remain separately tracked optional work. The current template +should be described as a validated starting point until P1-P3 pass in the +intended company environment. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 49c9ff2aa..eb85d08f9 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -25,12 +25,20 @@ registered candidate without promotion; see [its local and live report](20-sm28a SM-20a now generates and deploys the first local-engine Bundle. Its own jobs passed Polars training, 2+2 incremental scoring/no-op, read-only comparison, challenger staging and explicit promotion; see [the report](21-sm20a-local-bundle-validation-report.md). -SM-28b optional monthly retraining scheduling is next. +SM-20P now hardens the Bundle for a company environment before SM-28b. The +personal `dev` shape remains serverless; generated company `test/syst/prod` +targets use a looked-up job-cluster policy and `PayingRegNo`. Both templates +rendered, personal strict CLI validation passed, and company target shapes +passed strict CLI validation with a dummy policy ID in the personal workspace. +This is not a company deployment or policy execution check. Company profile, +host, catalog, schema, policy and cost-tag values still need confirmation; +one-time provisioning/preflight is open. See +[the production hardening plan](22-sm20p-production-bundle-plan.md). ## Starting point - SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26, - SM-22a/b/c, SM-28a and SM-20a are complete. Start SM-28b from + SM-22a/b/c, SM-28a and SM-20a are complete. Continue SM-20P from [the open queue](OPEN_QUEUE.md), using the generated Bundle and the [pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md). SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 4d5a3a32a..c709e05fa 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,7 +1,8 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a complete. SM-28b next. Target: 0.9.0.** -Next deliverable: optional monthly local retraining schedule. Spark +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a complete. SM-20P active before SM-28b. Target: 0.9.0.** +Next deliverable: production-target Bundle hardening, then optional monthly +local retraining schedule. Spark expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -51,6 +52,7 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-22c | Challenger and previous-champion aliases | SM-22b | DONE | Validated challenger staging; guarded three-alias promotion/rollback; legacy receipts and partial-write tests; [local and UC evidence](19-sm22c-lifecycle-alias-validation-report.md) | | SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-22c, SM-24a | DONE | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion; [evidence](20-sm28a-label-aware-retraining-report.md) | | SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | DONE | Generated/deployed Polars Bundle; train/compare/stage/promote and 2+2 incremental score/no-op live; [evidence](21-sm20a-local-bundle-validation-report.md) | +| SM-20P | Company Bundle target and provisioning hardening | SM-20a | ACTIVE | Personal serverless and company policy-backed target shapes generated and validated locally; one-time setup and real company test profile/policy gate remain; [plan](22-sm20p-production-bundle-plan.md) | | SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | READY | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | @@ -61,7 +63,9 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-24c | Spark batch workflow adapter | SM-20a, existing Spark sink | LATER | Expose tested Spark runner after first local Bundle | | SM-20b | Spark Bundle enhancement | SM-24c, selected SM-17 slices | LATER | Add tested Spark engine choice while preserving local variant | -SM-22a/b/c and SM-28a are now prerequisites for the first Bundle. SM-28b only +SM-20P is the active production-readiness work after the first Bundle. Its +company profile/policy execution remains unverified. SM-22a/b/c and SM-28a +are prerequisites for the first Bundle. SM-28b only wires their optional monthly schedule after the Bundle exists. SM-27 remains post-Bundle and independent. Endpoint, feature lookup and monitoring remain optional; broad Spark expansion follows the local Bundle. diff --git a/templates/databricks/databricks_template_schema.json b/templates/databricks/databricks_template_schema.json index 740827d79..888946d45 100644 --- a/templates/databricks/databricks_template_schema.json +++ b/templates/databricks/databricks_template_schema.json @@ -1,5 +1,5 @@ { - "welcome_message": "Create a bounded Skyulf local-engine Databricks Bundle. Edit config/workflow.json for your data before running jobs.", + "welcome_message": "Create a bounded Skyulf local-engine Databricks Bundle. Choose personal serverless or company policy-backed targets, then edit config/workflow.json for your data.", "properties": { "project_name": { "order": 1, @@ -15,19 +15,98 @@ "description": "Local feature and model engine", "enum": ["pandas", "polars"] }, - "catalog": { + "deployment_mode": { "order": 3, "type": "string", + "default": "personal", + "description": "Deployment profile", + "enum": ["personal", "company"] + }, + "catalog": { + "order": 4, + "type": "string", "default": "workspace", "description": "Existing Unity Catalog catalog (simple identifier)", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "company"}}} }, "schema": { - "order": 4, + "order": 5, "type": "string", "default": "default", "description": "Existing Unity Catalog schema (simple identifier)", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "company"}}} + }, + "company_host": { + "order": 6, + "type": "string", + "default": "https://example.invalid", + "description": "Company Databricks workspace host; verify before deployment", + "pattern": "^https://[^/]+$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "test_catalog": { + "order": 7, + "type": "string", + "default": "dpt_analytics_test", + "description": "Test Unity Catalog catalog; reference example, verify with the team", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "syst_catalog": { + "order": 8, + "type": "string", + "default": "dpt_analytics_syst", + "description": "System-test Unity Catalog catalog; reference example, verify with the team", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "prod_catalog": { + "order": 9, + "type": "string", + "default": "dpt_analytics_prod", + "description": "Production Unity Catalog catalog; reference example, verify with the team", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "input_schema": { + "order": 10, + "type": "string", + "default": "dsp_refined", + "description": "Existing labeled and scoring input schema", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "metadata_schema": { + "order": 11, + "type": "string", + "default": "dsp_metadata", + "description": "Registered model and internal admission schema", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "output_schema": { + "order": 12, + "type": "string", + "default": "dsp_mlresult", + "description": "One prediction table per model in this schema", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "cluster_policy_name": { + "order": 13, + "type": "string", + "default": "[32] Job ML - ML-JOB-Training-Inference-S2M", + "description": "Approved company job-cluster policy name; verify with the team", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + }, + "paying_reg_no": { + "order": 14, + "type": "string", + "default": "34BG", + "description": "Approved company PayingRegNo cost tag; verify with the team", + "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} } } } diff --git a/templates/databricks/examples/company-init.example.json b/templates/databricks/examples/company-init.example.json new file mode 100644 index 000000000..a42f946f8 --- /dev/null +++ b/templates/databricks/examples/company-init.example.json @@ -0,0 +1,14 @@ +{ + "project_name": "my_model", + "engine": "pandas", + "deployment_mode": "company", + "company_host": "https://example.invalid", + "test_catalog": "dpt_analytics_test", + "syst_catalog": "dpt_analytics_syst", + "prod_catalog": "dpt_analytics_prod", + "input_schema": "dsp_refined", + "metadata_schema": "dsp_metadata", + "output_schema": "dsp_mlresult", + "cluster_policy_name": "[32] Job ML - ML-JOB-Training-Inference-S2M", + "paying_reg_no": "34BG" +} diff --git a/templates/databricks/template/{{.project_name}}/README.md.tmpl b/templates/databricks/template/{{.project_name}}/README.md.tmpl index f19b22d86..ab3862a65 100644 --- a/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -3,14 +3,15 @@ This is a Skyulf 0.9.0 local-engine Databricks Bundle. The selected fit and prediction engine is **{{.engine}}**. Spark is used to read bounded Delta rows and publish the prediction table; Skyulf runs feature engineering and model -prediction on the selected local engine. +prediction on the selected local engine. This project was generated for the +**{{.deployment_mode}}** deployment profile. ## Before the first run 1. Put the matching, trusted `skyulf_core-0.9.0-py3-none-any.whl` in `dist/`. From a Skyulf source checkout, run `uv build --wheel --no-build-isolation --out-dir /dist skyulf-core`. Rebuild the wheel whenever the - source changes. The serverless job also installs MLflow 3.16.1. + source changes. The jobs also install MLflow 3.16.1. 2. Edit `config/workflow.json`: set real training and scoring tables, features, temporal split, preprocessing/model config, memory bounds and the concrete training Delta version. The generated values are examples, not a dataset. @@ -23,14 +24,45 @@ prediction on the selected local engine. stage/promote jobs, create a separate alias admission table with the same columns and one row with `target_id` equal to `skyulf.integrations.mlflow.promotion.alias_resource_id(model_name)`. -4. Authenticate the Databricks CLI, then run `databricks bundle validate - --strict -t dev` and `databricks bundle deploy -t dev`. The CLI profile is - selected by `--profile`; no credentials are stored here. +4. Authenticate the Databricks CLI, then validate and deploy the intended + target with `databricks bundle validate --strict -t --profile + ` and `databricks bundle deploy -t --profile `. + The CLI profile supplies credentials; none are stored here. -Run `databricks bundle run train -t dev` to train one candidate, log held-out +{{if eq .deployment_mode "personal"}} +The only target is `dev`, using serverless jobs. The initial catalog and schema +come from the two initialization questions. Use this mode in a personal +workspace for development and isolated live tests. +{{else}} +The company targets are `test`, `syst` and `prod`. They use the approved job +cluster policy and `PayingRegNo` cost tag supplied at initialization. Verify +the workspace host, three catalog mappings, schema names, policy name, tag and +CLI profile with your team before deployment. The questionnaire defaults are +examples from the supplied company reference, not confirmed production values. +`test` adds a per-user suffix to the registered model, prediction and internal +admission tables. `syst` and `prod` use stable names in distinct catalogs. +The input tables are existing tables; edit their full UC names if another team +owns them. If the three targets live in different workspaces, set each target's +`workspace.host` separately before validation. +{{end}} + +| Job | When to run | Effect | +| --- | --- | --- | +| `train` | New labeled data or model candidate | Fits and registers a candidate, logs held-out MLflow metrics | +| `compare` | Review a candidate | Read-only comparison with the current champion | +| `stage` | After an eligible comparison | Assigns the candidate to `@challenger` | +| `promote` | Explicit release decision | Moves the staged candidate to `@champion` | +| `score` | Each new source increment | Appends only new-row predictions to one target table | + +The project uses one prediction table per model. Its score and alias admission +tables are internal coordination tables in the metadata schema, not prediction +outputs. Normal recurring inference runs only `score`; training and alias jobs +have their own release cadence. + +Run `databricks bundle run train -t ` to train one candidate, log held-out metrics and register its model. Inspect the resulting model version in Unity Catalog, and set `model_version` in the JSON to that **concrete version** before -running `databricks bundle run score -t dev`. Redeploy after changing the +running `databricks bundle run score -t `. Redeploy after changing the configuration. Each score run handles the initial bounded source snapshot or only inserts since the last committed receipt. Run it again with no new rows to see a no-op; no date or source-version argument is needed. Source updates diff --git a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index 286df2491..4a9cf4812 100644 --- a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -1,12 +1,12 @@ { "engine": "{{.engine}}", - "training_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_training", + "training_table": "{catalog}.{input_schema}.{{.project_name}}_training", "training_version": 0, - "score_source_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_source", - "prediction_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_predictions", - "score_admission_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_score_admission", - "alias_admission_table": "{{.catalog}}.{{.schema}}.{{.project_name}}_alias_admission", - "model_name": "{{.catalog}}.{{.schema}}.{{.project_name}}_model", + "score_source_table": "{catalog}.{input_schema}.{{.project_name}}_source", + "prediction_table": "{catalog}.{output_schema}.{{.project_name}}_predictions{resource_suffix}", + "score_admission_table": "{catalog}.{metadata_schema}.{{.project_name}}_score_admission{resource_suffix}", + "alias_admission_table": "{catalog}.{metadata_schema}.{{.project_name}}_alias_admission{resource_suffix}", + "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", "model_version": "1", "champion_version": null, "candidate_version": "2", diff --git a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl index b0db21bc2..644b45e9f 100644 --- a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +++ b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl @@ -10,7 +10,75 @@ sync: - config/workflow.json - src/workflow.py +variables: + catalog: + description: Unity Catalog catalog for the active target +{{if eq .deployment_mode "personal"}} + default: {{.catalog}} +{{end}} + input_schema: + description: Existing labeled and scoring source tables +{{if eq .deployment_mode "personal"}} + default: {{.schema}} +{{else}} + default: {{.input_schema}} +{{end}} + output_schema: + description: Prediction Delta table +{{if eq .deployment_mode "personal"}} + default: {{.schema}} +{{else}} + default: {{.output_schema}} +{{end}} + metadata_schema: + description: Registered model and internal admission tables +{{if eq .deployment_mode "personal"}} + default: {{.schema}} +{{else}} + default: {{.metadata_schema}} +{{end}} + resource_suffix: + description: Non-production namespace suffix; empty for the initial dev project + default: "" +{{if eq .deployment_mode "company"}} + cluster_policy_id: + description: Approved job-cluster policy resolved in this workspace + lookup: + cluster_policy: "{{.cluster_policy_name}}" + paying_reg_no: + description: Approved PayingRegNo cost allocation tag + default: "{{.paying_reg_no}}" +{{end}} + targets: +{{if eq .deployment_mode "personal"}} dev: default: true mode: development +{{else}} + test: + default: true + mode: development + variables: + catalog: {{.test_catalog}} + resource_suffix: _${workspace.current_user.short_name} + workspace: + host: {{.company_host}} + root_path: ~/{{.project_name}}/test + syst: + mode: production + variables: + catalog: {{.syst_catalog}} + resource_suffix: "" + workspace: + host: {{.company_host}} + root_path: ~/{{.project_name}}/syst + prod: + mode: production + variables: + catalog: {{.prod_catalog}} + resource_suffix: "" + workspace: + host: {{.company_host}} + root_path: ~/{{.project_name}}/prod +{{end}} diff --git a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml deleted file mode 100644 index 113e58560..000000000 --- a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml +++ /dev/null @@ -1,88 +0,0 @@ -resources: - jobs: - train: - name: ${bundle.name}_train - tasks: - - task_key: train - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: train - config_path: ${workspace.file_path}/config/workflow.json - experiment_name: ${workspace.root_path}/experiment - environment_key: skyulf - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 - compare: - name: ${bundle.name}_compare - tasks: - - task_key: compare - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: compare - config_path: ${workspace.file_path}/config/workflow.json - environment_key: skyulf - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 - stage: - name: ${bundle.name}_stage - tasks: - - task_key: stage - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: stage - config_path: ${workspace.file_path}/config/workflow.json - environment_key: skyulf - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 - promote: - name: ${bundle.name}_promote - tasks: - - task_key: promote - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: promote - config_path: ${workspace.file_path}/config/workflow.json - environment_key: skyulf - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 - score: - name: ${bundle.name}_score - tasks: - - task_key: score - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: score - config_path: ${workspace.file_path}/config/workflow.json - environment_key: skyulf - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 diff --git a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl new file mode 100644 index 000000000..2bee26761 --- /dev/null +++ b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -0,0 +1,223 @@ +resources: + jobs: + train: + name: ${bundle.name}_train + tasks: + - task_key: train + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: train + config_path: ${workspace.file_path}/config/workflow.json + experiment_name: ${workspace.root_path}/experiment + catalog: ${var.catalog} + input_schema: ${var.input_schema} + output_schema: ${var.output_schema} + metadata_schema: ${var.metadata_schema} + resource_suffix: ${var.resource_suffix} +{{if eq .deployment_mode "personal"}} + environment_key: skyulf +{{else}} + job_cluster_key: skyulf + libraries: + - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - pypi: + package: mlflow==3.16.1 +{{end}} +{{if eq .deployment_mode "personal"}} + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 +{{else}} + job_clusters: + - job_cluster_key: skyulf + new_cluster: + spark_version: 17.3.x-cpu-ml-scala2.13 + node_type_id: m5d.2xlarge + policy_id: ${var.cluster_policy_id} + custom_tags: + PayingRegNo: ${var.paying_reg_no} + autoscale: + min_workers: 2 + max_workers: 4 +{{end}} + compare: + name: ${bundle.name}_compare + tasks: + - task_key: compare + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: compare + config_path: ${workspace.file_path}/config/workflow.json + catalog: ${var.catalog} + input_schema: ${var.input_schema} + output_schema: ${var.output_schema} + metadata_schema: ${var.metadata_schema} + resource_suffix: ${var.resource_suffix} +{{if eq .deployment_mode "personal"}} + environment_key: skyulf +{{else}} + job_cluster_key: skyulf + libraries: + - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - pypi: + package: mlflow==3.16.1 +{{end}} +{{if eq .deployment_mode "personal"}} + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 +{{else}} + job_clusters: + - job_cluster_key: skyulf + new_cluster: + spark_version: 17.3.x-cpu-ml-scala2.13 + node_type_id: m5d.2xlarge + policy_id: ${var.cluster_policy_id} + custom_tags: + PayingRegNo: ${var.paying_reg_no} + autoscale: + min_workers: 2 + max_workers: 4 +{{end}} + stage: + name: ${bundle.name}_stage + tasks: + - task_key: stage + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: stage + config_path: ${workspace.file_path}/config/workflow.json + catalog: ${var.catalog} + input_schema: ${var.input_schema} + output_schema: ${var.output_schema} + metadata_schema: ${var.metadata_schema} + resource_suffix: ${var.resource_suffix} +{{if eq .deployment_mode "personal"}} + environment_key: skyulf +{{else}} + job_cluster_key: skyulf + libraries: + - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - pypi: + package: mlflow==3.16.1 +{{end}} +{{if eq .deployment_mode "personal"}} + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 +{{else}} + job_clusters: + - job_cluster_key: skyulf + new_cluster: + spark_version: 17.3.x-cpu-ml-scala2.13 + node_type_id: m5d.2xlarge + policy_id: ${var.cluster_policy_id} + custom_tags: + PayingRegNo: ${var.paying_reg_no} + autoscale: + min_workers: 2 + max_workers: 4 +{{end}} + promote: + name: ${bundle.name}_promote + tasks: + - task_key: promote + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: promote + config_path: ${workspace.file_path}/config/workflow.json + catalog: ${var.catalog} + input_schema: ${var.input_schema} + output_schema: ${var.output_schema} + metadata_schema: ${var.metadata_schema} + resource_suffix: ${var.resource_suffix} +{{if eq .deployment_mode "personal"}} + environment_key: skyulf +{{else}} + job_cluster_key: skyulf + libraries: + - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - pypi: + package: mlflow==3.16.1 +{{end}} +{{if eq .deployment_mode "personal"}} + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 +{{else}} + job_clusters: + - job_cluster_key: skyulf + new_cluster: + spark_version: 17.3.x-cpu-ml-scala2.13 + node_type_id: m5d.2xlarge + policy_id: ${var.cluster_policy_id} + custom_tags: + PayingRegNo: ${var.paying_reg_no} + autoscale: + min_workers: 2 + max_workers: 4 +{{end}} + score: + name: ${bundle.name}_score + tasks: + - task_key: score + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: score + config_path: ${workspace.file_path}/config/workflow.json + catalog: ${var.catalog} + input_schema: ${var.input_schema} + output_schema: ${var.output_schema} + metadata_schema: ${var.metadata_schema} + resource_suffix: ${var.resource_suffix} +{{if eq .deployment_mode "personal"}} + environment_key: skyulf +{{else}} + job_cluster_key: skyulf + libraries: + - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - pypi: + package: mlflow==3.16.1 +{{end}} +{{if eq .deployment_mode "personal"}} + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 +{{else}} + job_clusters: + - job_cluster_key: skyulf + new_cluster: + spark_version: 17.3.x-cpu-ml-scala2.13 + node_type_id: m5d.2xlarge + policy_id: ${var.cluster_policy_id} + custom_tags: + PayingRegNo: ${var.paying_reg_no} + autoscale: + min_workers: 2 + max_workers: 4 +{{end}} diff --git a/templates/databricks/template/{{.project_name}}/src/workflow.py b/templates/databricks/template/{{.project_name}}/src/workflow.py index 6c67eed0e..61fb929ab 100644 --- a/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -2,6 +2,7 @@ """Run one bounded Skyulf local training, comparison, alias or scoring action.""" import json +import re import tempfile from dataclasses import asdict from datetime import datetime @@ -31,6 +32,50 @@ from skyulf.integrations.mlflow.registry import resolve_model from skyulf.integrations.mlflow.validation import compare_registered_local_models +_TABLE_FIELDS = ( + "training_table", + "score_source_table", + "prediction_table", + "score_admission_table", + "alias_admission_table", + "model_name", +) +_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") +_TABLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){2}\Z") + + +def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: + """Bind only UC object names to one validated Bundle target.""" + for name in ("catalog", "input_schema", "output_schema", "metadata_schema"): + if not _IDENTIFIER.fullmatch(bindings.get(name, "")): + raise ValueError(f"Invalid {name} for a Unity Catalog identifier.") + suffix = bindings.get("resource_suffix", "") + if suffix and (not suffix.startswith("_") or not _IDENTIFIER.fullmatch(suffix)): + raise ValueError("Invalid resource_suffix for a Unity Catalog identifier.") + resolved = config.copy() + for name in _TABLE_FIELDS: + value = config[name] + if type(value) is not str: + raise ValueError(f"{name} must be a string.") + for key, replacement in bindings.items(): + value = value.replace("{" + key + "}", replacement) + if not _TABLE_NAME.fullmatch(value): + raise ValueError(f"{name} must resolve to a three-part UC name.") + if name in { + "prediction_table", + "score_admission_table", + "alias_admission_table", + "model_name", + }: + schema = "output_schema" if name == "prediction_table" else "metadata_schema" + expected = f"{bindings['catalog']}.{bindings[schema]}." + if not value.startswith(expected): + raise ValueError(f"{name} must use the active target's {schema}.") + if suffix and not value.endswith(suffix): + raise ValueError(f"{name} must include the active target's resource_suffix.") + resolved[name] = value + return resolved + def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: """Keep the evaluation split and source snapshot identical across actions.""" @@ -176,6 +221,19 @@ def main() -> None: """Read deployed configuration and job widgets only at the notebook boundary.""" widgets = globals()["dbutils"].widgets config = json.loads(Path(widgets.get("config_path")).read_text(encoding="utf-8")) + config = resolve_target_config( + config, + { + name: widgets.get(name) + for name in ( + "catalog", + "input_schema", + "output_schema", + "metadata_schema", + "resource_suffix", + ) + }, + ) action = widgets.get("action") with tempfile.TemporaryDirectory(prefix="skyulf-bundle-") as directory: result = run_action( diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 3497e518c..0a3ec671b 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -1,6 +1,7 @@ """The generated local Bundle delegates to Skyulf's verified services.""" import importlib.util +import json from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -119,3 +120,144 @@ def test_ineligible_candidate_cannot_reach_alias_writer(monkeypatch): with pytest.raises(ValueError, match="not eligible"): workflow.run_action(object(), _config(), "promote") promote.assert_not_called() + + +def test_target_binding_separates_test_and_prod_outputs(): + """One generated workflow must never reuse a test prediction table in prod.""" + workflow = _workflow() + config = _config() + config.update( + training_table="{catalog}.{input_schema}.labeled_events", + score_source_table="shared.raw.events", + prediction_table="{catalog}.{output_schema}.predictions{resource_suffix}", + model_name="{catalog}.{metadata_schema}.model{resource_suffix}", + score_admission_table="{catalog}.{metadata_schema}.score_control{resource_suffix}", + alias_admission_table="{catalog}.{metadata_schema}.alias_control{resource_suffix}", + ) + shared = { + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + } + test_config = workflow.resolve_target_config( + config, {**shared, "catalog": "test_catalog", "resource_suffix": "_murat"} + ) + syst_config = workflow.resolve_target_config( + config, {**shared, "catalog": "syst_catalog", "resource_suffix": ""} + ) + prod_config = workflow.resolve_target_config( + config, {**shared, "catalog": "prod_catalog", "resource_suffix": ""} + ) + assert test_config["prediction_table"] == "test_catalog.mlresult.predictions_murat" + assert syst_config["prediction_table"] == "syst_catalog.mlresult.predictions" + assert prod_config["prediction_table"] == "prod_catalog.mlresult.predictions" + assert prod_config["score_source_table"] == "shared.raw.events" + assert test_config["model_name"] != prod_config["model_name"] + assert ( + len( + { + test_config["prediction_table"], + syst_config["prediction_table"], + prod_config["prediction_table"], + } + ) + == 3 + ) + assert config["prediction_table"] == "{catalog}.{output_schema}.predictions{resource_suffix}" + + +def test_target_binding_rejects_unsafe_catalog_before_any_job(): + """A malformed target parameter must fail before it reaches a UC operation.""" + workflow = _workflow() + with pytest.raises(ValueError, match="catalog"): + workflow.resolve_target_config( + _config(), + { + "catalog": "prod;DROP TABLE x", + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + "resource_suffix": "", + }, + ) + + +def test_target_binding_rejects_cross_environment_output(): + """A prod job cannot write a model or prediction into a test catalog.""" + workflow = _workflow() + config = _config() + config.update( + score_admission_table="prod_catalog.metadata.score_control", + alias_admission_table="prod_catalog.metadata.alias_control", + model_name="prod_catalog.metadata.model", + ) + config["prediction_table"] = "test_catalog.mlresult.predictions" + with pytest.raises(ValueError, match="prediction_table"): + workflow.resolve_target_config( + config, + { + "catalog": "prod_catalog", + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + "resource_suffix": "", + }, + ) + + +def test_target_binding_rejects_cross_environment_model(): + """A prod train job cannot register a model in a test catalog.""" + workflow = _workflow() + config = _config() + config.update( + prediction_table="prod_catalog.mlresult.predictions", + score_admission_table="prod_catalog.metadata.score_control", + alias_admission_table="prod_catalog.metadata.alias_control", + ) + config["model_name"] = "test_catalog.metadata.model" + with pytest.raises(ValueError, match="model_name"): + workflow.resolve_target_config( + config, + { + "catalog": "prod_catalog", + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + "resource_suffix": "", + }, + ) + + +def test_generated_config_keeps_company_output_in_each_target(): + """The actual JSON template must bind its outputs separately in every target.""" + workflow = _workflow() + template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" + config = json.loads( + template.read_text(encoding="utf-8") + .replace("{{.project_name}}", "customer_model") + .replace("{{.engine}}", "pandas") + ) + outputs = {} + for target, catalog, suffix in ( + ("test", "test_catalog", "_murat"), + ("syst", "syst_catalog", ""), + ("prod", "prod_catalog", ""), + ): + bound = workflow.resolve_target_config( + config, + { + "catalog": catalog, + "input_schema": "dsp_refined", + "output_schema": "dsp_mlresult", + "metadata_schema": "dsp_metadata", + "resource_suffix": suffix, + }, + ) + assert bound["score_source_table"] == f"{catalog}.dsp_refined.customer_model_source" + assert bound["model_name"] == f"{catalog}.dsp_metadata.customer_model_model{suffix}" + outputs[target] = bound["prediction_table"] + assert outputs == { + "test": "test_catalog.dsp_mlresult.customer_model_predictions_murat", + "syst": "syst_catalog.dsp_mlresult.customer_model_predictions", + "prod": "prod_catalog.dsp_mlresult.customer_model_predictions", + } From 6010a49c9c095113414677a5a7755ce6b27546d6 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 16:53:43 +0300 Subject: [PATCH 47/85] feat: reset Skyulf tests and validate generic local bundle Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 31 +-- docs/user_guide/databricks_bundle.md | 160 +++++++------- .../22-sm20p-production-bundle-plan.md | 5 + .../23-sm20-reset-and-generic-bundle-plan.md | 86 ++++++++ ...-clean-generic-bundle-validation-report.md | 70 ++++++ initiatives/spark_and_mlflow/HANDOFF.md | 26 ++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 13 +- .../databricks_local_sm20r_first_test.py | 124 +++++++++++ .../databricks_template_schema.json | 105 ++++----- .../examples/company-init.example.json | 14 -- .../examples/policy-init.example.json | 13 ++ .../examples/serverless-init.example.json | 8 + .../template/{{.project_name}}/README.md.tmpl | 150 ++++++------- .../config/workflow.json.tmpl | 3 +- .../{{.project_name}}/databricks.yml.tmpl | 67 +++--- .../resources/workflow.jobs.yml.tmpl | 98 ++++++--- .../{{.project_name}}/src/workflow.py | 204 ++++++++++++++++-- .../integration/test_sm20a_bundle_template.py | 109 ++++++++++ 18 files changed, 939 insertions(+), 347 deletions(-) create mode 100644 initiatives/spark_and_mlflow/23-sm20-reset-and-generic-bundle-plan.md create mode 100644 initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md create mode 100644 skyulf-core/examples/databricks_local_sm20r_first_test.py delete mode 100644 templates/databricks/examples/company-init.example.json create mode 100644 templates/databricks/examples/policy-init.example.json create mode 100644 templates/databricks/examples/serverless-init.example.json diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 95b34f3e7..15edbac36 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -10,11 +10,15 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed -- The local-engine Bundle template now separates personal serverless `dev` - from company `test/syst/prod` targets. Company jobs render policy-backed - clusters with a `PayingRegNo` tag, target catalogs and schema-bound UC - outputs. Personal and company target shapes passed strict CLI validation; - company policy execution and workspace access remain unverified. +- The local-engine Bundle template exposes editable `dev/test/syst/prod` + targets with separate host/catalog bindings, a serverless or policy-backed + compute choice and optional champion/challenger jobs. The minimal path uses + one existing source reference, creates only three jobs on deployment, and + prepares one prediction and one internal score-control table at explicit + setup. The earlier isolated Skyulf test jobs and schemas were removed at + the user's request. A clean personal serverless run then trained a Polars + model, wrote 600 initial and 50 later predictions, and replayed without a + new commit. - Prediction Delta targets use `run_id`, `model_name` and `model_version` metadata columns. Existing test targets with the former `__skyulf_*` schema require a new target; the writer does not migrate tables. @@ -33,14 +37,15 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added -- A custom local-engine Databricks Bundle template now generates five separate - serverless jobs for candidate training, read-only comparison, challenger - staging, explicit promotion and automatic incremental scoring. It uses the - existing Skyulf Core services and an editable pandas/Polars configuration. - An isolated generated Bundle passed strict validation, deployment, Polars - train/compare/stage/promote jobs, two 2-row Delta scoring runs and a no-op - replay. Existing predictions retained their pinned model version after alias - promotion. Scheduling, Spark FE/model execution and endpoints remain separate. +- A custom local-engine Databricks Bundle template generates three default + jobs for candidate training, explicit output setup and automatic incremental + scoring. Read-only comparison, challenger staging and explicit promotion are + opt-in. It uses existing Skyulf Core services and an editable pandas/Polars + configuration. The earlier isolated lifecycle rehearsal passed + train/compare/stage/promote and 2+2-row incremental scoring; the later clean + generic rehearsal used one source table and proved 600+50-row scoring with a + no-op replay. Existing predictions retained their pinned model version after + alias promotion. Scheduling, Spark FE/model execution and endpoints remain separate. - Explicit MLflow champion promotion and rollback revalidate a pinned local model comparison, acquire shared admission, check the expected alias version and record durable transition receipts. Local registry tests and an isolated diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index 40ff5afe2..f3dc54527 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -1,59 +1,68 @@ # Local-engine Databricks Bundle -Skyulf's custom template creates a self-contained Databricks Bundle project -with separate jobs for candidate training, read-only model comparison, -challenger staging, explicit promotion and incremental batch scoring. Choose -`pandas` or `polars` when generating the project. The selected engine fits -feature engineering and the model, then applies the saved pipeline at scoring -time. Spark reads bounded Unity Catalog Delta rows and writes predictions; -this first Bundle does not distribute local feature engineering across Spark -workers. +The custom Skyulf template generates one editable Bundle with `dev`, `test`, +`syst` and `prod` targets. It fits and predicts with pandas or Polars. Spark +reads bounded Unity Catalog Delta rows and publishes predictions; local +feature engineering and model prediction are not distributed Spark work. -Generate a project from a Skyulf checkout: +Initialize a project from a Skyulf checkout: ```powershell databricks bundle init templates/databricks --output-dir ./generated ``` -Choose `personal` for a serverless `dev` target, or `company` for -policy-backed `test`, `syst` and `prod` targets. Personal mode asks for project -name, local engine, catalog and schema. Company mode asks for the workspace -host, target catalogs, input/metadata/result schemas, approved cluster policy -and `PayingRegNo`. Supply reviewed answers with `bundle init --config-file` -when the team has them; the company examples in the questionnaire are not -verified production settings. The -generated project contains its own `databricks.yml`, `config/workflow.json`, -Skyulf job entry point and five job resources. It does not put a -`databricks.yml` in the Skyulf repository root. Follow the generated README -to build and place the matching Skyulf wheel in `dist/`, select real tables, -features, preprocessing/model configuration and temporal split, then provision -the source, target and admission tables. The generated JSON is an editable -starting point; there is no claim that arbitrary feature engineering can be -inferred from a table name. - -For company mode, copy and review -`templates/databricks/examples/company-init.example.json`, especially its -placeholder host and policy/tag values, then initialize with: +The short path asks for project name, engine, serverless or policy-backed job +compute, optional champion/challenger lifecycle and the existing `dev` +catalog/schema. Serverless and no lifecycle are the defaults. Reviewable +noninteractive examples are in `templates/databricks/examples/`. The generated +project has its own `databricks.yml`; Skyulf's root has no Bundle config. -```powershell -databricks bundle init templates/databricks --config-file --output-dir ./generated -``` +`dev` uses the selected CLI profile's workspace host. `test`, `syst` and +`prod` each have a different placeholder host and catalog in the generated +file. Edit each target's host, catalog and input/output/metadata schema +bindings, then validate with its designated profile. No Danske, Danica or +personal-workspace value is built into those three targets. Policy-backed +compute uses the policy name, runtime, node type and cost tag supplied at +initialization. Serverless compute needs none of those fields. + +## What is created -| Job | Purpose | Normal cadence | +`bundle deploy` creates only three jobs by default and uploads their code: + +| Job | Purpose | UC objects created when run | | --- | --- | --- | -| `train` | Fit and register a candidate with held-out MLflow metrics | When labeled data warrants a new model | -| `compare` | Read-only candidate/champion check | During model review | -| `stage` | Assign an eligible `@challenger` | Explicit release step | -| `promote` | Move staged candidate to `@champion` | Explicit approval step | -| `score` | Append predictions for new source inserts | Every scoring run | - -Only `score` is needed for recurring inference. A generated project has one -prediction table per model. Its existing labeled/source tables are inputs; the -score and alias admission tables are internal coordination state in the -metadata schema. They are not additional prediction outputs. Company `test` -adds a per-user suffix to output/model/control names, while `syst` and `prod` -use stable names in their respective catalogs. The notebook verifies that -these writes stay in the active target's catalog and schema. +| `train` | Fit one candidate and log held-out metrics | One registered model/version | +| `setup` | Verify source and pinned model, then prepare output | One prediction table and one internal score-control table, only if absent | +| `score` | Score the initial source, then new CDF inserts | Rows in the same prediction table | + +`compare`, `stage` and `promote` jobs are generated only with +`include_lifecycle=yes`. In that case `setup` also creates one alias-control +table. No schedule, endpoint or Unity Catalog table is created by deployment +alone. + +The six relevant configuration names have different roles: + +| Name | Meaning | +| --- | --- | +| `training_table` | Existing labeled input table, pinned to a Delta version for training | +| `score_source_table` | Existing CDF-enabled source of rows to predict | +| `prediction_table` | The one output table for this model | +| `score_admission_table` | Internal one-row Delta coordination table for safe incremental writes | +| `alias_admission_table` | Optional coordination table for champion/challenger changes | +| `model_name` | Registered Unity Catalog model, not a table | + +The first two references point to **the same existing table by default**. +Neither reference creates a table. Separate them only when labeled training +data and new scoring data have different lifecycles. If they stay together, +the first `score` run predicts all existing rows, including historical labeled +rows; review whether that is intended for your use case. + +## First run + +Build and place the matching Skyulf wheel in the generated project's `dist/`, +then edit `config/workflow.json` for real source columns, preprocessing, model, +temporal split and size limits. The JSON values are an example, not a dataset. +Enable Change Data Feed on the scoring source before later inserts arrive. ```powershell databricks bundle validate --strict -t dev --profile @@ -61,42 +70,29 @@ databricks bundle deploy -t dev --profile databricks bundle run train -t dev --profile ``` -Training pins a labeled Delta snapshot and temporal holdout. Skyulf logs the -fitted artifact and held-out metrics to MLflow and registers a concrete Unity -Catalog model version. Inspect that version and set `model_version` in the -config before deploying again and running `score`. The score job reads an -existing CDF-enabled Delta source, prepares the pinned local pipeline once, -and scores the initial bounded snapshot. Later runs read only new inserts -since the last committed Delta receipt. They require no date or source-version -input. An empty repeat is a no-op. Source updates and deletes are rejected -until a rescore policy is chosen. Keep the same admission control row for all -writers to the target. +Inspect the registered model version, put that concrete value in +`model_version`, redeploy the changed JSON, then run `setup` and `score`. +`setup` rejects a missing source, disabled CDF, unsuitable row keys, a model +output mismatch or an existing target/control schema mismatch before it +creates missing output state. It checks initial row count against `max_rows`; +`score` also checks decoded transfer bytes against `max_bytes`. Existing +tables are never overwritten. `score` first processes the current source +snapshot; later runs process only new inserts since the committed Delta +receipt. A repeat without new rows is a no-op. No monthly date or source +version is entered for each run. -```powershell -databricks bundle run score -t dev --profile -# Add new rows to the source Delta table. -databricks bundle run score -t dev --profile -``` +The first candidate does not become champion automatically. Optional +`compare` is read-only, `stage` assigns an eligible `@challenger`, and +`promote` explicitly moves it to `@champion` while retaining the prior +version as `@previous_champion`. Scoring stays pinned to its configured model +version; changing aliases does not rewrite old predictions. Full-history +rescore, schedules, online endpoints and Spark-native FE/model execution are +separate work. -`compare` reads two configured concrete versions against the same pinned -holdout. It never changes aliases. With a separately initialized `@champion` -alias and a provisioned alias admission row, `stage` can assign an eligible -candidate to `@challenger`; `promote` then moves it to `@champion` and stores -the prior version as `@previous_champion`. These are explicit jobs, and they -recheck the comparison and expected champion version. The first candidate -does not become champion automatically. The scoring job continues to use its -configured concrete version until the operator changes it. Alias promotion -does not rewrite old prediction rows. - -The template has no schedule. Add a scoring schedule only after checking the -source's append policy and data permissions. Monthly retraining scheduling, -full-history rescores, Spark-native execution and endpoints are separate -extensions. See [the local SDK](databricks_local_sdk.md) for the underlying -configuration and [MLflow registry](mlflow_registry.md) for model resolution. - -The personal `dev` Bundle was live-tested on serverless compute. Company -targets are generated but have not been validated or run in the company -workspace. Before a company rollout, verify host/catalog/policy/tag values, -validate each target with its own CLI profile and perform an isolated `test` -run. A different company workspace per target requires editing each target's -`workspace.host` after initialization. +The older SM-20a personal serverless rehearsal passed, but its jobs and test +schemas were removed at the user's request. The subsequent clean generic +`dev` rehearsal trained a Polars model from 600 real taxi rows, wrote 600 +initial and 50 later predictions to one table, and replayed without another +commit. The personal test resources remain available for inspection. The +`test`, `syst` and `prod` placeholders have not been deployed in a company +workspace. diff --git a/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md b/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md index 9faa2a3e8..7667f00e7 100644 --- a/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md +++ b/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md @@ -1,5 +1,10 @@ # SM-20P production Bundle implementation plan +Superseded by [SM-20R reset and generic Bundle plan](23-sm20-reset-and-generic-bundle-plan.md) +after the user's request for a reusable four-target project and a fresh +personal-workspace test. The company-shaped implementation was never deployed +to a company workspace. + Updated: 2026-09-24. SM-20a is a live-validated **test/development Bundle template**, not a company production deployment. This plan compares it with `C:\Users\Murat\Downloads\codes-main (2)\codes-main\dbml-mlops-template` diff --git a/initiatives/spark_and_mlflow/23-sm20-reset-and-generic-bundle-plan.md b/initiatives/spark_and_mlflow/23-sm20-reset-and-generic-bundle-plan.md new file mode 100644 index 000000000..b2b72a7f0 --- /dev/null +++ b/initiatives/spark_and_mlflow/23-sm20-reset-and-generic-bundle-plan.md @@ -0,0 +1,86 @@ +# SM-20R: clean workspace and generic first Bundle + +Updated: 2026-09-24. This replaces the company-shaped SM-20P template +direction in [the earlier plan](22-sm20p-production-bundle-plan.md). The user +asked for one editable Bundle for any organization, with `dev`, `test`, `syst` +and `prod` targets and a fresh, visible first test. Company-specific catalogs, +hosts, policy and cost tags are examples or later configuration, not defaults +in the reusable Skyulf template. + +## Verified reset of the personal workspace + +Profile: `skyulf`, host: +`https://dbc-45604623-c18b.cloud.databricks.com`. Before deletion, the CLI +listed ten `skyulf_sm20a_r1` jobs and no active runs. It listed exactly three +Skyulf-owned test schemas under `workspace`. The user explicitly requested +deleting the previously created jobs and schemas. All ten job deletes and the +following three forced schema deletes returned success: + +- `workspace.skyulf_sm16_20260922` +- `workspace.skyulf_sm24a_20260923` +- `workspace.skyulf_nyctaxi_e2e_20260923` + +Post-deletion `databricks jobs list --profile skyulf` was empty. +`databricks schemas list workspace --profile skyulf` returned only +`workspace.default` and `workspace.information_schema`. Those system schemas +were preserved. The deleted test schemas contained their test Delta tables and +registered models; prior live-test reports remain historical evidence only. +Workspace files and MLflow experiments were not part of this deletion check. + +## Minimal resource contract + +`bundle deploy` creates jobs and uploads files. It creates no Unity Catalog +source, prediction or control table and registers no model. A first-run setup +step should list its intended UC objects before creating anything. + +| Reference | Purpose | New UC object in first run? | +| --- | --- | --- | +| `training_table` | Existing labeled source for fitting | No | +| `score_source_table` | Existing rows to predict, CDF-enabled for later inserts | No; may equal training table | +| `prediction_table` | The single prediction output | Yes, once at explicit setup | +| `score_admission_table` | Internal coordination for safe incremental writes | Yes, once at explicit setup | +| `alias_admission_table` | Internal coordination for alias changes | Only if lifecycle is enabled | +| `model_name` | Registered UC model, not a table | Created by training | + +Default to one existing source table for both training and scoring. Users can +split the references when their data lifecycle requires it. Do not create a +second source table just to satisfy the template. Training uses a pinned labeled +snapshot; scoring initially sees the whole source and later only new inserts. +The operator must review whether scoring old labeled rows is intended. + +Default jobs: one-time `setup`, candidate `train`, recurring `score`. +`compare`, `stage` and `promote` are generated only when the user opts into +champion/challenger lifecycle. No schedule or endpoint is created by default. +Setup should never overwrite an existing table; it must validate source CDF, +keys, model output and an existing target/control schema before any write. + +## Generic target and compute contract + +- [x] One generated project exposes `dev`, `test`, `syst`, `prod`. `dev` is the + default and uses the CLI profile host supplied by the user. Other targets + each have a separate, conspicuous host/catalog placeholder and must be + edited before they can deploy. Never use the personal test host as the + implied company production host. +- [x] Ask only for project name, pandas/Polars engine, compute mode, optional + lifecycle and dev catalog/schema in the easy path. Serverless is the default + compute mode. Policy-backed classic compute is optional and configurable; + no company-specific policy or `PayingRegNo` in the generic defaults. +- [x] Pass active target catalog and schema variables into the Skyulf notebook. + Validate output/model/control names against the target before any write. +- [x] Render and strictly validate both compute modes and all four target + shapes. The two generated `dev` shapes passed strict CLI validation. The + other six shapes passed strict syntax validation only after substituting + temporary personal-workspace values for the placeholders. Personal `dev` is + the only live target until the other hosts, catalogs and profiles are supplied. +- [x] Update README, user guide, queue and 0.9.x changelog to state exactly + which jobs and UC objects are produced at each step. + +## First clean live rehearsal + +Completed in the isolated `workspace.skyulf_bundle_first_20260924` schema. +The [clean validation report](24-sm20r-clean-generic-bundle-validation-report.md) +records deployment, Polars training, explicit setup, 600 initial predictions, +50 later predictions, no-op replay, and the final 650-row verification. The +final inventory has one source table, one prediction table, one internal +score-control table, one registered model and three persistent Bundle jobs. +Optional lifecycle resources stayed absent. No non-dev target was deployed. diff --git a/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md b/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md new file mode 100644 index 000000000..ea23347d2 --- /dev/null +++ b/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md @@ -0,0 +1,70 @@ +# SM-20R clean generic Bundle validation + +Date: 2026-09-24. Personal profile: `skyulf`; target: `dev` only. The clean +schema is `workspace.skyulf_bundle_first_20260924`. This is a real-data, +serverless Polars fit/predict test using `samples.nyctaxi.trips`; it does not +exercise a company workspace or classic compute. + +## Reset and object inventory + +Before this run, ten earlier Skyulf test jobs and three earlier Skyulf test +schemas were deleted. `jobs list` then returned no persistent jobs, and the +`workspace` catalog listed only `default` and `information_schema`. + +Creating the fresh schema made no table. `bundle deploy` uploaded six files +and created exactly three persistent jobs: `skyulf_reset_dev_setup`, +`skyulf_reset_dev_train`, and `skyulf_reset_dev_score`. It created no table. +The source-preparation notebook created the one managed Delta input table +`skyulf_reset_dev_source` before training. The same source is pinned at Delta +version 1 for training and read incrementally for scoring. Source preparation +selected 600 unique real trips: 303 fit and 297 temporal holdout rows. + +| Step | Job or run | UC effect | Evidence | +| --- | --- | --- | --- | +| Prepare source | One-time `1121337641193762` | One CDF-enabled source table, 600 rows, version 1 | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/998376432225508/run/1121337641193762) | +| Deploy | Bundle `dev` | Three persistent jobs, zero tables | `bundle deploy` output: 3 created, 6 files uploaded | +| Train | `998255871992406` | UC model `skyulf_reset_dev_model` version 1 and MLflow run | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/402117143173384/run/998255871992406) | +| Setup | `447359392118318` | One empty prediction table and one internal score-control table | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/5775604932565/run/447359392118318) | +| First score | `630863655201312` | 600 predictions in the same table | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1089013339073761/run/630863655201312) | +| Append source | One-time `861959622894913` | 50 more source rows; source total 650 | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/352133155519821/run/861959622894913) | +| Second score | `858963997908575` | Only 50 new predictions | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1089013339073761/run/858963997908575) | +| Unchanged replay | `661436133664918` | No new prediction or target commit | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1089013339073761/run/661436133664918) | +| Final verification | One-time `523752795761361` | Read-only check: 650 unique predictions using model version 1 | [run](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/842299042681083/run/523752795761361) | + +The training run used Polars `SimpleImputer`, `StandardScaler` and a Skyulf +linear-regression model. The registered version was 1, with 297 held-out rows. +MLflow reported MAE `0.6844`, RMSE `2.5676`, R2 `0.9363`, MAPE `0.0621` +and explained variance `0.9363`. An independent `experiments get-run` query +confirmed all six held-out metrics persisted on MLflow run +`6c5c58c5d44045e89ae0054bbbec4a27`. The first score receipt reported +`input_count=600`, `output_count=600`, source end version 1, target commit +version 1, `noop=false`. The second score receipt reported source version 2, +`input_count=50`, `output_count=50`, target commit version 2 and `noop=false`. +The unchanged replay reported `input_count=0`, `output_count=0`, target commit +version still 2 and `noop=true`. + +After setup, an independent `tables list` showed exactly these three managed +tables in the schema: `skyulf_reset_dev_source`, +`skyulf_reset_dev_predictions`, `skyulf_reset_dev_score_admission`. No +alias-control table was created because lifecycle jobs were disabled. The +registered model is a UC model, not another table. + +## Scope and remaining checks + +The generic template renders `dev`, `test`, `syst`, `prod` with distinct target +bindings. Serverless and policy-cluster variants passed strict `dev` Bundle +validation. Six other target *shapes* passed strict validation using temporary +placeholder substitutions, not real company configuration. Only personal +serverless `dev` was deployed. The policy-backed cluster variant, optional +champion/challenger jobs, company hosts/catalogs and Spark-native work remain +unverified by this clean run. + +The final read-only notebook found 650 source and 650 prediction rows, 650 +distinct prediction keys, and only registered model version 1 in the output. +The final CLI inventory still listed exactly the three Bundle jobs and the +three tables above. These resources remain in the personal test workspace so +they can be inspected in the Databricks UI. + +Local regression tests: `13 passed` with a workspace-local pytest +temp directory. Ruff and Ty passed on the changed Python files; strict MkDocs +build passed with the existing unlisted segmentation-page notice. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index eb85d08f9..99d50ab3f 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -25,21 +25,25 @@ registered candidate without promotion; see [its local and live report](20-sm28a SM-20a now generates and deploys the first local-engine Bundle. Its own jobs passed Polars training, 2+2 incremental scoring/no-op, read-only comparison, challenger staging and explicit promotion; see [the report](21-sm20a-local-bundle-validation-report.md). -SM-20P now hardens the Bundle for a company environment before SM-28b. The -personal `dev` shape remains serverless; generated company `test/syst/prod` -targets use a looked-up job-cluster policy and `PayingRegNo`. Both templates -rendered, personal strict CLI validation passed, and company target shapes -passed strict CLI validation with a dummy policy ID in the personal workspace. -This is not a company deployment or policy execution check. Company profile, -host, catalog, schema, policy and cost-tag values still need confirmation; -one-time provisioning/preflight is open. See -[the production hardening plan](22-sm20p-production-bundle-plan.md). +The user requested a clean reset and a generic Bundle. The personal `skyulf` +workspace's ten SM-20a jobs and three Skyulf test schemas were deleted; post- +deletion job listing was empty and only default/system schemas remained. The +company-shaped SM-20P draft is superseded. SM-20R now generates one editable +`dev/test/syst/prod` project: serverless is the easy default, policy compute +and champion/challenger jobs are optional, and test/syst/prod have distinct +unconfigured host/catalog placeholders. Deployment itself creates no UC +tables. The clean personal test passed: one existing source, registered Polars +model version 1, one prediction table and one internal score-control table; +600 initial and 50 later predictions, followed by a no-op replay. The final +read-only check found 650 unique predictions. See [the live report](24-sm20r-clean-generic-bundle-validation-report.md) +and [the reset plan](23-sm20-reset-and-generic-bundle-plan.md). Those test +resources remain for inspection. Company targets are still placeholders. ## Starting point - SM-00 through SM-16, SM-15L, SM-15I, SM-24a, SM-25, SM-26, - SM-22a/b/c, SM-28a and SM-20a are complete. Continue SM-20P from - [the open queue](OPEN_QUEUE.md), using the generated Bundle and the + SM-22a/b/c, SM-28a and SM-20a/20R are complete. Continue SM-28b from + [the open queue](OPEN_QUEUE.md), using the generic Bundle and the [pre-Bundle lifecycle plan](06-prebundle-model-lifecycle-plan.md). SM-15I [live evidence](13-sm15i-live-validation-report.md) proves automatic 80+80 insert-only scoring with no date column or per-run version input. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index c709e05fa..32303250a 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,8 +1,7 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a complete. SM-20P active before SM-28b. Target: 0.9.0.** -Next deliverable: production-target Bundle hardening, then optional monthly -local retraining schedule. Spark +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a/20R complete. SM-28b is next. Target: 0.9.0.** +Next deliverable: optional monthly local retraining schedule. Spark expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -20,6 +19,7 @@ Durumlar: READY = başlanabilir; WAIT = önceki görev bekleniyor; LATER = son aşama; ACTIVE = yürütülüyor; BLOCKED = somut dış engel; DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. DEFERRED = user postponed this work; PARKED = do not implement until resumed. +SUPERSEDED = replaced by a later user-directed scope; not a completed feature. | Sıra | Görev | Bağımlılık | Durum | Kısa bitiş ölçütü | | --- | --- | --- | --- | --- | @@ -52,7 +52,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-22c | Challenger and previous-champion aliases | SM-22b | DONE | Validated challenger staging; guarded three-alias promotion/rollback; legacy receipts and partial-write tests; [local and UC evidence](19-sm22c-lifecycle-alias-validation-report.md) | | SM-28a | Label-aware retraining service | SM-22a, SM-22b, SM-22c, SM-24a | DONE | Pinned training snapshot, temporal holdout, candidate registration/comparison; no automatic promotion; [evidence](20-sm28a-label-aware-retraining-report.md) | | SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | DONE | Generated/deployed Polars Bundle; train/compare/stage/promote and 2+2 incremental score/no-op live; [evidence](21-sm20a-local-bundle-validation-report.md) | -| SM-20P | Company Bundle target and provisioning hardening | SM-20a | ACTIVE | Personal serverless and company policy-backed target shapes generated and validated locally; one-time setup and real company test profile/policy gate remain; [plan](22-sm20p-production-bundle-plan.md) | +| SM-20P | Company-shaped Bundle draft | SM-20a | SUPERSEDED | Replaced by the generic four-target SM-20R direction; no company workspace deployment | +| SM-20R | Reset personal tests; generic minimal Bundle | SM-20a | DONE | Ten test jobs and three schemas removed; four target shapes validated, personal dev deployed with three jobs; one source, one prediction, one internal control, one UC model; Polars 600+50-row scoring and no-op replay; [live evidence](24-sm20r-clean-generic-bundle-validation-report.md) | | SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | READY | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | @@ -63,8 +64,8 @@ DEFERRED = user postponed this work; PARKED = do not implement until resumed. | SM-24c | Spark batch workflow adapter | SM-20a, existing Spark sink | LATER | Expose tested Spark runner after first local Bundle | | SM-20b | Spark Bundle enhancement | SM-24c, selected SM-17 slices | LATER | Add tested Spark engine choice while preserving local variant | -SM-20P is the active production-readiness work after the first Bundle. Its -company profile/policy execution remains unverified. SM-22a/b/c and SM-28a +SM-20R replaces SM-20P after the user's reset and generic-template direction. +Company profile/policy execution remains unverified. SM-22a/b/c and SM-28a are prerequisites for the first Bundle. SM-28b only wires their optional monthly schedule after the Bundle exists. SM-27 remains post-Bundle and independent. Endpoint, feature lookup and monitoring remain diff --git a/skyulf-core/examples/databricks_local_sm20r_first_test.py b/skyulf-core/examples/databricks_local_sm20r_first_test.py new file mode 100644 index 000000000..b90ded635 --- /dev/null +++ b/skyulf-core/examples/databricks_local_sm20r_first_test.py @@ -0,0 +1,124 @@ +# Databricks notebook source +"""Prepare one real taxi source and verify the minimal generic Bundle rehearsal.""" + +import json +from typing import Any + +from pyspark.sql import Window # ty: ignore[unresolved-import] +from pyspark.sql import functions as F # ty: ignore[unresolved-import] + +SCHEMA = "workspace.skyulf_bundle_first_20260924" +SOURCE = f"{SCHEMA}.skyulf_reset_dev_source" +TARGET = f"{SCHEMA}.skyulf_reset_dev_predictions" +FEATURES = ("trip_distance", "trip_duration_minutes", "pickup_hour", "pickup_weekday") +SAMPLE = "samples.nyctaxi.trips" + + +def _rows(spark: Any) -> Any: + """Choose reproducible real trips with unique keys and completed labels.""" + raw = spark.table(SAMPLE) + duration = ( + F.unix_timestamp("tpep_dropoff_datetime") - F.unix_timestamp("tpep_pickup_datetime") + ) / F.lit(60.0) + clean = ( + raw.withColumn("trip_duration_minutes", duration) + .where(F.col("fare_amount").between(2.5, 100.0)) + .where(F.col("trip_distance").between(0.1, 30.0)) + .where(F.col("trip_duration_minutes").between(1.0, 120.0)) + .dropna( + subset=["tpep_pickup_datetime", "tpep_dropoff_datetime", "trip_distance", "fare_amount"] + ) + .withColumn( + "entity_id", + F.sha2( + F.to_json( + F.struct( + "tpep_pickup_datetime", + "tpep_dropoff_datetime", + "trip_distance", + "fare_amount", + "pickup_zip", + "dropoff_zip", + ) + ), + 256, + ), + ) + .withColumn("pickup_hour", F.hour("tpep_pickup_datetime").cast("double")) + .withColumn("pickup_weekday", F.dayofweek("tpep_pickup_datetime").cast("double")) + .select( + "entity_id", + F.col("tpep_pickup_datetime").alias("event_time"), + F.col("tpep_dropoff_datetime").alias("label_at"), + F.col("trip_distance").cast("double").alias("trip_distance"), + F.col("trip_duration_minutes").cast("double").alias("trip_duration_minutes"), + "pickup_hour", + "pickup_weekday", + F.col("fare_amount").cast("double").alias("target"), + ) + .orderBy("entity_id") + .limit(650) + .withColumn("split_index", F.row_number().over(Window.orderBy("entity_id"))) + ) + return clean + + +def prepare(spark: Any) -> dict[str, Any]: + """Create only the one CDF-enabled source table; Bundle setup owns outputs.""" + if spark.catalog.tableExists(SOURCE): + raise ValueError(f"Source already exists: {SOURCE}") + first = _rows(spark).where(F.col("split_index") <= 600).drop("split_index") + first.write.format("delta").saveAsTable(SOURCE) + spark.sql(f"ALTER TABLE {SOURCE} SET TBLPROPERTIES (delta.enableChangeDataFeed = true)") + source = spark.table(SOURCE) + rows = source.count() + fit = source.where(F.col("event_time") < F.lit("2016-02-01")).count() + heldout = source.where(F.col("event_time") >= F.lit("2016-02-01")).count() + if ( + rows != 600 + or fit < 50 + or heldout < 50 + or source.select("entity_id").distinct().count() != rows + ): + raise AssertionError( + "The first source must have 600 unique trips and both temporal splits." + ) + version = spark.sql(f"DESCRIBE HISTORY {SOURCE}").first().version + return { + "source": SOURCE, + "rows": rows, + "fit_rows": fit, + "heldout_rows": heldout, + "source_version": version, + } + + +def append(spark: Any) -> dict[str, Any]: + """Add 50 new keys only after the first 600 predictions are committed.""" + if spark.table(SOURCE).count() != 600 or spark.table(TARGET).count() != 600: + raise AssertionError("Initial scoring must commit 600 rows before the append.") + later = _rows(spark).where(F.col("split_index") > 600).drop("split_index") + if later.count() != 50: + raise AssertionError("Expected 50 deterministic new trips.") + later.write.format("delta").mode("append").saveAsTable(SOURCE) + return {"source": SOURCE, "source_rows": spark.table(SOURCE).count()} + + +def verify(spark: Any) -> dict[str, Any]: + """Confirm one target contains 600 original and 50 later pinned predictions.""" + source = spark.table(SOURCE) + target = spark.table(TARGET) + if source.count() != 650 or target.count() != 650: + raise AssertionError("Expected 650 source and prediction rows after the second score.") + if target.select("entity_id").distinct().count() != 650: + raise AssertionError("Predicted row keys must be unique.") + identities = target.select("model_name", "model_version").distinct().collect() + if len(identities) != 1 or identities[0].model_version != "1": + raise AssertionError("All predictions must use the first pinned UC model version.") + return {"source_rows": 650, "prediction_rows": 650, "model_version": "1"} + + +if __name__ == "__main__": + phase = globals()["dbutils"].widgets.get("phase") + result = {"prepare": prepare, "append": append, "verify": verify}[phase](globals()["spark"]) + globals()["dbutils"].notebook.exit(json.dumps(result)) diff --git a/templates/databricks/databricks_template_schema.json b/templates/databricks/databricks_template_schema.json index 888946d45..ac02bd598 100644 --- a/templates/databricks/databricks_template_schema.json +++ b/templates/databricks/databricks_template_schema.json @@ -1,5 +1,5 @@ { - "welcome_message": "Create a bounded Skyulf local-engine Databricks Bundle. Choose personal serverless or company policy-backed targets, then edit config/workflow.json for your data.", + "welcome_message": "Create a bounded Skyulf pandas/Polars Bundle. dev is ready for your CLI profile; edit test, syst and prod target settings before using them.", "properties": { "project_name": { "order": 1, @@ -12,101 +12,72 @@ "order": 2, "type": "string", "default": "pandas", - "description": "Local feature and model engine", + "description": "Local fit and prediction engine", "enum": ["pandas", "polars"] }, - "deployment_mode": { + "compute_mode": { "order": 3, "type": "string", - "default": "personal", - "description": "Deployment profile", - "enum": ["personal", "company"] + "default": "serverless", + "description": "Job compute mode for this project", + "enum": ["serverless", "policy_cluster"] }, - "catalog": { + "include_lifecycle": { "order": 4, "type": "string", - "default": "workspace", - "description": "Existing Unity Catalog catalog (simple identifier)", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "company"}}} + "default": "no", + "description": "Add optional compare, stage and promote jobs?", + "enum": ["no", "yes"] }, - "schema": { + "catalog": { "order": 5, "type": "string", - "default": "default", - "description": "Existing Unity Catalog schema (simple identifier)", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "company"}}} + "default": "workspace", + "description": "Existing dev Unity Catalog catalog", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, - "company_host": { + "schema": { "order": 6, "type": "string", - "default": "https://example.invalid", - "description": "Company Databricks workspace host; verify before deployment", - "pattern": "^https://[^/]+$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + "default": "default", + "description": "Existing dev Unity Catalog schema", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, - "test_catalog": { + "cluster_policy_name": { "order": 7, "type": "string", - "default": "dpt_analytics_test", - "description": "Test Unity Catalog catalog; reference example, verify with the team", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + "default": "REPLACE_WITH_APPROVED_POLICY", + "description": "Approved job-cluster policy name", + "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, - "syst_catalog": { + "spark_version": { "order": 8, "type": "string", - "default": "dpt_analytics_syst", - "description": "System-test Unity Catalog catalog; reference example, verify with the team", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + "default": "17.3.x-cpu-ml-scala2.13", + "description": "Approved Databricks ML Runtime for the job cluster", + "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, - "prod_catalog": { + "node_type_id": { "order": 9, "type": "string", - "default": "dpt_analytics_prod", - "description": "Production Unity Catalog catalog; reference example, verify with the team", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + "default": "REPLACE_WITH_NODE_TYPE", + "description": "Approved job-cluster node type", + "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, - "input_schema": { + "cost_tag_key": { "order": 10, "type": "string", - "default": "dsp_refined", - "description": "Existing labeled and scoring input schema", + "default": "CostCenter", + "description": "Approved cluster cost tag key", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, - "metadata_schema": { + "cost_tag_value": { "order": 11, "type": "string", - "default": "dsp_metadata", - "description": "Registered model and internal admission schema", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} - }, - "output_schema": { - "order": 12, - "type": "string", - "default": "dsp_mlresult", - "description": "One prediction table per model in this schema", - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} - }, - "cluster_policy_name": { - "order": 13, - "type": "string", - "default": "[32] Job ML - ML-JOB-Training-Inference-S2M", - "description": "Approved company job-cluster policy name; verify with the team", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} - }, - "paying_reg_no": { - "order": 14, - "type": "string", - "default": "34BG", - "description": "Approved company PayingRegNo cost tag; verify with the team", - "skip_prompt_if": {"properties": {"deployment_mode": {"const": "personal"}}} + "default": "REPLACE_WITH_COST_TAG", + "description": "Approved cluster cost tag value", + "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} } } } diff --git a/templates/databricks/examples/company-init.example.json b/templates/databricks/examples/company-init.example.json deleted file mode 100644 index a42f946f8..000000000 --- a/templates/databricks/examples/company-init.example.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "project_name": "my_model", - "engine": "pandas", - "deployment_mode": "company", - "company_host": "https://example.invalid", - "test_catalog": "dpt_analytics_test", - "syst_catalog": "dpt_analytics_syst", - "prod_catalog": "dpt_analytics_prod", - "input_schema": "dsp_refined", - "metadata_schema": "dsp_metadata", - "output_schema": "dsp_mlresult", - "cluster_policy_name": "[32] Job ML - ML-JOB-Training-Inference-S2M", - "paying_reg_no": "34BG" -} diff --git a/templates/databricks/examples/policy-init.example.json b/templates/databricks/examples/policy-init.example.json new file mode 100644 index 000000000..8e0787798 --- /dev/null +++ b/templates/databricks/examples/policy-init.example.json @@ -0,0 +1,13 @@ +{ + "project_name": "my_model", + "engine": "pandas", + "compute_mode": "policy_cluster", + "include_lifecycle": "yes", + "catalog": "REPLACE_DEV_CATALOG", + "schema": "REPLACE_DEV_SCHEMA", + "cluster_policy_name": "REPLACE_WITH_APPROVED_POLICY", + "spark_version": "17.3.x-cpu-ml-scala2.13", + "node_type_id": "REPLACE_WITH_NODE_TYPE", + "cost_tag_key": "CostCenter", + "cost_tag_value": "REPLACE_WITH_COST_TAG" +} diff --git a/templates/databricks/examples/serverless-init.example.json b/templates/databricks/examples/serverless-init.example.json new file mode 100644 index 000000000..a23b8b130 --- /dev/null +++ b/templates/databricks/examples/serverless-init.example.json @@ -0,0 +1,8 @@ +{ + "project_name": "my_model", + "engine": "pandas", + "compute_mode": "serverless", + "include_lifecycle": "no", + "catalog": "workspace", + "schema": "my_dev_schema" +} diff --git a/templates/databricks/template/{{.project_name}}/README.md.tmpl b/templates/databricks/template/{{.project_name}}/README.md.tmpl index ab3862a65..9e50e0cbc 100644 --- a/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -1,84 +1,90 @@ # {{.project_name}} -This is a Skyulf 0.9.0 local-engine Databricks Bundle. The selected fit and -prediction engine is **{{.engine}}**. Spark is used to read bounded Delta rows -and publish the prediction table; Skyulf runs feature engineering and model -prediction on the selected local engine. This project was generated for the -**{{.deployment_mode}}** deployment profile. +This Skyulf 0.9.0 Bundle fits and predicts with **{{.engine}}**. Spark reads +bounded Unity Catalog Delta rows and writes predictions. The selected job +compute mode is **{{.compute_mode}}**. `dev`, `test`, `syst` and `prod` use the +same Skyulf workflow code with different target bindings. -## Before the first run +## What deployment creates -1. Put the matching, trusted `skyulf_core-0.9.0-py3-none-any.whl` in `dist/`. - From a Skyulf source checkout, run `uv build --wheel --no-build-isolation - --out-dir /dist skyulf-core`. Rebuild the wheel whenever the - source changes. The jobs also install MLflow 3.16.1. -2. Edit `config/workflow.json`: set real training and scoring tables, features, - temporal split, preprocessing/model config, memory bounds and the concrete - training Delta version. The generated values are examples, not a dataset. -3. Create the source and empty prediction Delta tables. Enable Change Data - Feed on the scoring source **before** new rows arrive. The prediction table - needs `row_keys`, `prediction`, `run_id`, `model_name`, and `model_version` - with types matching the Skyulf output. Create the separate score admission - table with `(target_id STRING, owner STRING)` and one row whose `target_id` - is the prediction table's Delta identity and `owner` is null. If using the - stage/promote jobs, create a separate alias admission table with the same - columns and one row with `target_id` equal to - `skyulf.integrations.mlflow.promotion.alias_resource_id(model_name)`. -4. Authenticate the Databricks CLI, then validate and deploy the intended - target with `databricks bundle validate --strict -t --profile - ` and `databricks bundle deploy -t --profile `. - The CLI profile supplies credentials; none are stored here. +`bundle deploy` uploads the wheel, notebook and configuration, and creates +{{if eq .include_lifecycle "yes"}}six{{else}}three{{end}} jobs. It creates **no** +Unity Catalog table or registered model. The default jobs are: -{{if eq .deployment_mode "personal"}} -The only target is `dev`, using serverless jobs. The initial catalog and schema -come from the two initialization questions. Use this mode in a personal -workspace for development and isolated live tests. +| Job | Run it when | UC effect | +| --- | --- | --- | +| `train` | A labeled snapshot is ready | Registers one candidate model and logs MLflow metrics | +| `setup` | The model version and source are ready | Creates one empty prediction table and one score-control table if absent | +| `score` | New rows need predictions | Appends only new-row predictions to the same prediction table | + +{{if eq .include_lifecycle "yes"}} +The optional `compare`, `stage` and `promote` jobs are also generated. Setup +then creates a separate alias-control table. Those jobs review and explicitly +move `@challenger` and `@champion`; they never run as part of ordinary scoring. {{else}} -The company targets are `test`, `syst` and `prod`. They use the approved job -cluster policy and `PayingRegNo` cost tag supplied at initialization. Verify -the workspace host, three catalog mappings, schema names, policy name, tag and -CLI profile with your team before deployment. The questionnaire defaults are -examples from the supplied company reference, not confirmed production values. -`test` adds a per-user suffix to the registered model, prediction and internal -admission tables. `syst` and `prod` use stable names in distinct catalogs. -The input tables are existing tables; edit their full UC names if another team -owns them. If the three targets live in different workspaces, set each target's -`workspace.host` separately before validation. +The champion/challenger jobs and alias-control table are absent in this +minimal project. Generate with `include_lifecycle=yes` when needed. {{end}} -| Job | When to run | Effect | -| --- | --- | --- | -| `train` | New labeled data or model candidate | Fits and registers a candidate, logs held-out MLflow metrics | -| `compare` | Review a candidate | Read-only comparison with the current champion | -| `stage` | After an eligible comparison | Assigns the candidate to `@challenger` | -| `promote` | Explicit release decision | Moves the staged candidate to `@champion` | -| `score` | Each new source increment | Appends only new-row predictions to one target table | +`training_table` is the existing labeled input. `score_source_table` is the +existing input to predict; the generated config points both at **one table**. +You may give them different UC names when the labeled training data and new +inference data have different lifecycles. Neither is created by this Bundle. +`prediction_table` is the single model output table. `score_admission_table` +holds one internal ownership row so concurrent writers cannot silently +duplicate an increment. `model_name` is a registered UC model, not a table. + +## Prepare the project + +1. Build a matching, trusted wheel from a Skyulf checkout with `uv build + --wheel --no-build-isolation --out-dir /dist skyulf-core`. +2. Edit `config/workflow.json` for real source/model names, row keys, model + inputs, preprocessing, estimator, temporal split and size limits. The + generated JSON is an example, not a usable dataset. Enable Delta Change + Data Feed on the scoring source before new rows arrive. Check that the + source's initial rows are the rows you intend to score: the first `score` + run predicts **all** existing source rows, including labeled training rows + when one table is used for both purposes. +3. Authenticate a Databricks CLI profile and validate/deploy the `dev` target: -The project uses one prediction table per model. Its score and alias admission -tables are internal coordination tables in the metadata schema, not prediction -outputs. Normal recurring inference runs only `score`; training and alias jobs -have their own release cadence. + ```powershell + databricks bundle validate --strict -t dev --profile + databricks bundle deploy -t dev --profile + ``` + + `dev` uses the profile's workspace host and the catalog/schema chosen at + initialization. The three other targets contain **different placeholder + hosts and catalogs**. Replace each with an approved value and use its own + profile before validation or deployment. Credentials are never saved here. + The generated target variables also let each environment use different + input, output and metadata schemas. + +{{if eq .compute_mode "policy_cluster"}} +The selected policy-backed jobs look up the policy name supplied during +initialization. Confirm its runtime, node type and cost tag in each workspace. +An example init config lives in `templates/databricks/examples/policy-init.example.json` +in the Skyulf checkout. Its placeholders must be reviewed before use. +{{else}} +The generated jobs use Databricks serverless Python environment 4. Policy +clusters are a separate compute choice at project initialization. +{{end}} -Run `databricks bundle run train -t ` to train one candidate, log held-out -metrics and register its model. Inspect the resulting model version in Unity -Catalog, and set `model_version` in the JSON to that **concrete version** before -running `databricks bundle run score -t `. Redeploy after changing the -configuration. Each score run handles the initial bounded source snapshot or -only inserts since the last committed receipt. Run it again with no new rows -to see a no-op; no date or source-version argument is needed. Source updates -and deletes require a separate rescore policy. +## First run and later increments -The first model has no champion by default. Once a champion alias has been -explicitly initialized, set `champion_version` and `candidate_version` to -concrete versions from the **same** pinned labeled holdout. The `compare` job -is read-only. `stage` and `promote` are separate manual jobs: they re-evaluate -the comparison and use the distributed alias admission row. Promotion requires -the matching candidate to have been staged as `@challenger`. Neither training -nor comparison changes aliases automatically. Keep scoring pinned to a -concrete `model_version` until you explicitly decide to move it; an alias -change does not rescore historical rows. +1. Run `train` against a pinned labeled Delta version. It logs held-out MLflow + metrics and registers a concrete model version. +2. Put that concrete version in `model_version` in `config/workflow.json` and + redeploy. Run `setup`. Setup verifies the source, Change Data Feed, model + outputs, row keys and existing target/control schemas before writing. It + creates only missing output/control tables; it never overwrites existing + tables or creates the source. Its row check is bounded by `max_rows`; the + scoring job also enforces `max_bytes` on the local transfer. +3. Run `score`. Add new rows to the existing source Delta table and run `score` + again. An unchanged replay is a no-op. No date or source-version argument + is entered for each run. Source updates or deletes require a separate + rescore policy. -The default jobs have no schedules. Add a scoring schedule after checking the -source append policy and table permissions. Optional retraining schedules, -full-history rescores, Spark feature engineering and endpoints are separate -future extensions. +`score` always uses its configured concrete model version. Training a new +candidate or changing a registry alias does not rewrite old prediction rows. +There is no schedule, online endpoint or Spark-native FE/model execution in +this starting project. diff --git a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index 4a9cf4812..ba42a5b8e 100644 --- a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -1,6 +1,7 @@ { "engine": "{{.engine}}", - "training_table": "{catalog}.{input_schema}.{{.project_name}}_training", + "include_lifecycle": "{{.include_lifecycle}}", + "training_table": "{catalog}.{input_schema}.{{.project_name}}_source", "training_version": 0, "score_source_table": "{catalog}.{input_schema}.{{.project_name}}_source", "prediction_table": "{catalog}.{output_schema}.{{.project_name}}_predictions{resource_suffix}", diff --git a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl index 644b45e9f..072338cc3 100644 --- a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +++ b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl @@ -12,73 +12,72 @@ sync: variables: catalog: - description: Unity Catalog catalog for the active target -{{if eq .deployment_mode "personal"}} + description: Unity Catalog catalog selected by the active target default: {{.catalog}} -{{end}} input_schema: - description: Existing labeled and scoring source tables -{{if eq .deployment_mode "personal"}} + description: Existing training and scoring source schema default: {{.schema}} -{{else}} - default: {{.input_schema}} -{{end}} output_schema: - description: Prediction Delta table -{{if eq .deployment_mode "personal"}} + description: Prediction output schema default: {{.schema}} -{{else}} - default: {{.output_schema}} -{{end}} metadata_schema: - description: Registered model and internal admission tables -{{if eq .deployment_mode "personal"}} + description: Model and internal coordination schema default: {{.schema}} -{{else}} - default: {{.metadata_schema}} -{{end}} resource_suffix: - description: Non-production namespace suffix; empty for the initial dev project + description: Optional namespace suffix for shared development targets default: "" -{{if eq .deployment_mode "company"}} +{{if eq .compute_mode "policy_cluster"}} cluster_policy_id: - description: Approved job-cluster policy resolved in this workspace + description: Approved policy looked up in the active workspace lookup: cluster_policy: "{{.cluster_policy_name}}" - paying_reg_no: - description: Approved PayingRegNo cost allocation tag - default: "{{.paying_reg_no}}" + cost_tag_value: + description: Approved cluster cost allocation tag value + default: "{{.cost_tag_value}}" {{end}} targets: -{{if eq .deployment_mode "personal"}} dev: default: true mode: development -{{else}} + variables: + catalog: {{.catalog}} + input_schema: {{.schema}} + output_schema: {{.schema}} + metadata_schema: {{.schema}} + resource_suffix: "" + # Replace each placeholder before deploying outside dev. Hosts are distinct + # on purpose: a personal dev profile cannot become a production default. test: - default: true mode: development variables: - catalog: {{.test_catalog}} + catalog: REPLACE_TEST_CATALOG + input_schema: REPLACE_TEST_INPUT_SCHEMA + output_schema: REPLACE_TEST_OUTPUT_SCHEMA + metadata_schema: REPLACE_TEST_METADATA_SCHEMA resource_suffix: _${workspace.current_user.short_name} workspace: - host: {{.company_host}} + host: https://replace-test.example.invalid root_path: ~/{{.project_name}}/test syst: mode: production variables: - catalog: {{.syst_catalog}} + catalog: REPLACE_SYST_CATALOG + input_schema: REPLACE_SYST_INPUT_SCHEMA + output_schema: REPLACE_SYST_OUTPUT_SCHEMA + metadata_schema: REPLACE_SYST_METADATA_SCHEMA resource_suffix: "" workspace: - host: {{.company_host}} + host: https://replace-syst.example.invalid root_path: ~/{{.project_name}}/syst prod: mode: production variables: - catalog: {{.prod_catalog}} + catalog: REPLACE_PROD_CATALOG + input_schema: REPLACE_PROD_INPUT_SCHEMA + output_schema: REPLACE_PROD_OUTPUT_SCHEMA + metadata_schema: REPLACE_PROD_METADATA_SCHEMA resource_suffix: "" workspace: - host: {{.company_host}} + host: https://replace-prod.example.invalid root_path: ~/{{.project_name}}/prod -{{end}} diff --git a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl index 2bee26761..b5ba3b069 100644 --- a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +++ b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -1,5 +1,50 @@ resources: jobs: + setup: + name: ${bundle.name}_setup + max_concurrent_runs: 1 + tasks: + - task_key: setup + notebook_task: + notebook_path: ../src/workflow.py + base_parameters: + action: setup + config_path: ${workspace.file_path}/config/workflow.json + catalog: ${var.catalog} + input_schema: ${var.input_schema} + output_schema: ${var.output_schema} + metadata_schema: ${var.metadata_schema} + resource_suffix: ${var.resource_suffix} +{{if eq .compute_mode "serverless"}} + environment_key: skyulf +{{else}} + job_cluster_key: skyulf + libraries: + - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - pypi: + package: mlflow==3.16.1 +{{end}} +{{if eq .compute_mode "serverless"}} + environments: + - environment_key: skyulf + spec: + client: "4" + dependencies: + - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl + - mlflow==3.16.1 +{{else}} + job_clusters: + - job_cluster_key: skyulf + new_cluster: + spark_version: {{.spark_version}} + node_type_id: {{.node_type_id}} + policy_id: ${var.cluster_policy_id} + custom_tags: + {{.cost_tag_key}}: ${var.cost_tag_value} + autoscale: + min_workers: 2 + max_workers: 4 +{{end}} train: name: ${bundle.name}_train tasks: @@ -15,7 +60,7 @@ resources: output_schema: ${var.output_schema} metadata_schema: ${var.metadata_schema} resource_suffix: ${var.resource_suffix} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environment_key: skyulf {{else}} job_cluster_key: skyulf @@ -24,7 +69,7 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf spec: @@ -36,15 +81,16 @@ resources: job_clusters: - job_cluster_key: skyulf new_cluster: - spark_version: 17.3.x-cpu-ml-scala2.13 - node_type_id: m5d.2xlarge + spark_version: {{.spark_version}} + node_type_id: {{.node_type_id}} policy_id: ${var.cluster_policy_id} custom_tags: - PayingRegNo: ${var.paying_reg_no} + {{.cost_tag_key}}: ${var.cost_tag_value} autoscale: min_workers: 2 max_workers: 4 {{end}} +{{if eq .include_lifecycle "yes"}} compare: name: ${bundle.name}_compare tasks: @@ -59,7 +105,7 @@ resources: output_schema: ${var.output_schema} metadata_schema: ${var.metadata_schema} resource_suffix: ${var.resource_suffix} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environment_key: skyulf {{else}} job_cluster_key: skyulf @@ -68,7 +114,7 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf spec: @@ -80,11 +126,11 @@ resources: job_clusters: - job_cluster_key: skyulf new_cluster: - spark_version: 17.3.x-cpu-ml-scala2.13 - node_type_id: m5d.2xlarge + spark_version: {{.spark_version}} + node_type_id: {{.node_type_id}} policy_id: ${var.cluster_policy_id} custom_tags: - PayingRegNo: ${var.paying_reg_no} + {{.cost_tag_key}}: ${var.cost_tag_value} autoscale: min_workers: 2 max_workers: 4 @@ -103,7 +149,7 @@ resources: output_schema: ${var.output_schema} metadata_schema: ${var.metadata_schema} resource_suffix: ${var.resource_suffix} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environment_key: skyulf {{else}} job_cluster_key: skyulf @@ -112,7 +158,7 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf spec: @@ -124,11 +170,11 @@ resources: job_clusters: - job_cluster_key: skyulf new_cluster: - spark_version: 17.3.x-cpu-ml-scala2.13 - node_type_id: m5d.2xlarge + spark_version: {{.spark_version}} + node_type_id: {{.node_type_id}} policy_id: ${var.cluster_policy_id} custom_tags: - PayingRegNo: ${var.paying_reg_no} + {{.cost_tag_key}}: ${var.cost_tag_value} autoscale: min_workers: 2 max_workers: 4 @@ -147,7 +193,7 @@ resources: output_schema: ${var.output_schema} metadata_schema: ${var.metadata_schema} resource_suffix: ${var.resource_suffix} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environment_key: skyulf {{else}} job_cluster_key: skyulf @@ -156,7 +202,7 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf spec: @@ -168,17 +214,19 @@ resources: job_clusters: - job_cluster_key: skyulf new_cluster: - spark_version: 17.3.x-cpu-ml-scala2.13 - node_type_id: m5d.2xlarge + spark_version: {{.spark_version}} + node_type_id: {{.node_type_id}} policy_id: ${var.cluster_policy_id} custom_tags: - PayingRegNo: ${var.paying_reg_no} + {{.cost_tag_key}}: ${var.cost_tag_value} autoscale: min_workers: 2 max_workers: 4 +{{end}} {{end}} score: name: ${bundle.name}_score + max_concurrent_runs: 1 tasks: - task_key: score notebook_task: @@ -191,7 +239,7 @@ resources: output_schema: ${var.output_schema} metadata_schema: ${var.metadata_schema} resource_suffix: ${var.resource_suffix} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environment_key: skyulf {{else}} job_cluster_key: skyulf @@ -200,7 +248,7 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} -{{if eq .deployment_mode "personal"}} +{{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf spec: @@ -212,11 +260,11 @@ resources: job_clusters: - job_cluster_key: skyulf new_cluster: - spark_version: 17.3.x-cpu-ml-scala2.13 - node_type_id: m5d.2xlarge + spark_version: {{.spark_version}} + node_type_id: {{.node_type_id}} policy_id: ${var.cluster_policy_id} custom_tags: - PayingRegNo: ${var.paying_reg_no} + {{.cost_tag_key}}: ${var.cost_tag_value} autoscale: min_workers: 2 max_workers: 4 diff --git a/templates/databricks/template/{{.project_name}}/src/workflow.py b/templates/databricks/template/{{.project_name}}/src/workflow.py index 61fb929ab..b0874aa0f 100644 --- a/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -4,7 +4,7 @@ import json import re import tempfile -from dataclasses import asdict +from dataclasses import asdict, dataclass from datetime import datetime from pathlib import Path from typing import Any @@ -23,9 +23,11 @@ split_labeled_snapshot, train_local_candidate, ) +from skyulf.integrations.databricks.delta import table_identity from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission from skyulf.integrations.mlflow.promotion import ( DeltaAliasAdmission, + alias_resource_id, promote_candidate, stage_challenger, ) @@ -42,6 +44,25 @@ ) _IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") _TABLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){2}\Z") +_OUTPUT_TYPES = { + "float64": ("double", "DOUBLE"), + "int64": ("long", "BIGINT"), + "string": ("string", "STRING"), + "bool": ("boolean", "BOOLEAN"), +} + + +@dataclass(frozen=True, slots=True) +class ProvisionResult: + """Report the UC objects verified or created by one explicit setup run.""" + + source_table: str + prediction_table: str + prediction_created: bool + score_admission_table: str + score_admission_created: bool + alias_admission_table: str | None + alias_admission_created: bool def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: @@ -55,6 +76,8 @@ def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> d resolved = config.copy() for name in _TABLE_FIELDS: value = config[name] + if name == "alias_admission_table" and value is None: + continue if type(value) is not str: raise ValueError(f"{name} must be a string.") for key, replacement in bindings.items(): @@ -77,6 +100,158 @@ def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> d return resolved +def _scoring_config(config: dict[str, Any]) -> LocalWorkflowConfig: + """Bind the same pinned local model and source for setup and scoring.""" + return LocalWorkflowConfig( + runtime="databricks", + engine=config["engine"], + source=InputSource( + kind="uc_table", + table=config["score_source_table"], + read_mode="incremental", + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ), + model=ModelSelection( + kind="local_pipeline", + name=config["model_name"], + version=config["model_version"], + tracking_uri=config.get("tracking_uri", "databricks"), + registry_uri=config.get("registry_uri", "databricks-uc"), + ), + sink=OutputSink(kind="uc_delta", table=config["prediction_table"]), + ) + + +def _prediction_columns( + config: dict[str, Any], prepared: Any, source: Any +) -> tuple[tuple[str, str, str], ...]: + """Derive an exact Delta target schema from source keys and saved model outputs.""" + keys = tuple(config["row_keys"]) + inputs = tuple(prepared.artifact.manifest.input_columns) + if not keys or tuple(config["input_columns"]) != inputs: + raise ValueError("Configured keys or model inputs differ from the fitted model.") + names = (*keys, *inputs) + if any(not _IDENTIFIER.fullmatch(name) for name in names): + raise ValueError("Source keys and model inputs need simple column identifiers.") + if len({name.lower() for name in names}) != len(names): + raise ValueError("Source keys and model inputs must be distinct.") + if not set(names).issubset(source.columns): + raise ValueError("Scoring source lacks a row key or fitted model input column.") + columns = [] + for key in keys: + kind = source.schema[key].dataType.typeName() + if kind not in {"string", "long"}: + raise ValueError(f"Source row key {key!r} must be STRING or BIGINT.") + columns.append((key, kind, "STRING" if kind == "string" else "BIGINT")) + for output in prepared.preflight.output_schema: + if not _IDENTIFIER.fullmatch(output.name) or output.dtype not in _OUTPUT_TYPES: + raise ValueError("Saved model output has an unsupported name or type.") + kind, sql_type = _OUTPUT_TYPES[output.dtype] + columns.append((output.name, kind, sql_type)) + columns.extend((name, "string", "STRING") for name in ("run_id", "model_name", "model_version")) + if len({name.lower() for name, _, _ in columns}) != len(columns): + raise ValueError("Prediction columns collide with keys or metadata.") + return tuple(columns) + + +def _check_existing_table(spark: Any, name: str, columns: tuple[tuple[str, str, str], ...]) -> None: + """Reject an existing prediction target with a different schema.""" + actual = {field.name: field.dataType.typeName() for field in spark.table(name).schema.fields} + expected = {column: kind for column, kind, _ in columns} + if actual != expected: + raise ValueError(f"Existing prediction table {name} differs from the model output schema.") + + +def _check_existing_control(spark: Any, name: str, target_id: str) -> None: + """Require exactly one idle admission row bound to the intended resource.""" + frame = spark.table(name) + actual = {field.name: field.dataType.typeName() for field in frame.schema.fields} + if actual != {"target_id": "string", "owner": "string"}: + raise ValueError(f"Existing admission table {name} has an invalid schema.") + rows = frame.limit(2).collect() + if len(rows) != 1 or rows[0]["target_id"] != target_id or rows[0]["owner"] is not None: + raise ValueError(f"Existing admission table {name} is not idle for this resource.") + + +def _create_control(spark: Any, name: str, target_id: str) -> None: + """Create an admission table and its single row in one Delta CTAS statement.""" + spark.sql( + f"CREATE TABLE {name} USING DELTA AS " + "SELECT :target_id AS target_id, CAST(NULL AS STRING) AS owner", + args={"target_id": target_id}, + ).collect() + + +def provision_local_tables(spark: Any, config: dict[str, Any], prepared: Any) -> ProvisionResult: + """Preflight an existing source/model, then create only missing output state.""" + source_name = config["score_source_table"] + training_name = config["training_table"] + target_name = config["prediction_table"] + control_name = config["score_admission_table"] + lifecycle = config.get("include_lifecycle", "no") + if lifecycle not in {"no", "yes"}: + raise ValueError("include_lifecycle must be 'yes' or 'no'.") + for name in (source_name, training_name, target_name, control_name, config["model_name"]): + if not _TABLE_NAME.fullmatch(name): + raise ValueError("Setup needs valid three-part Unity Catalog names.") + if lifecycle == "yes" and not config.get("alias_admission_table"): + raise ValueError("Lifecycle setup needs an alias admission table.") + if lifecycle == "yes" and not _TABLE_NAME.fullmatch(config["alias_admission_table"]): + raise ValueError("Lifecycle setup needs a valid alias admission table name.") + if source_name == target_name: + raise ValueError("Prediction output must differ from the source table.") + for name in {source_name, training_name}: + if not spark.catalog.tableExists(name): + raise ValueError(f"Existing input source table is missing: {name}.") + if not prepared.preflight.ready: + raise ValueError("The pinned registered model failed Skyulf preflight.") + source = spark.table(source_name) + columns = _prediction_columns(config, prepared, source) + if ( + source.select(*config["row_keys"], *config["input_columns"]) + .limit(config["max_rows"] + 1) + .count() + > config["max_rows"] + ): + raise ValueError("Initial scoring source exceeds the configured max_rows budget.") + detail = spark.sql(f"DESCRIBE DETAIL {source_name}").first() + properties = detail["properties"] or {} + if not any( + key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" + for key, value in properties.items() + ): + raise ValueError("Scoring source must have Delta Change Data Feed enabled.") + target_exists = spark.catalog.tableExists(target_name) + control_exists = spark.catalog.tableExists(control_name) + if control_exists and not target_exists: + raise ValueError("Admission table exists while prediction target is missing.") + if target_exists: + _check_existing_table(spark, target_name, columns) + if control_exists: + _check_existing_control(spark, control_name, table_identity(spark, target_name)) + alias_name = config.get("alias_admission_table") if lifecycle == "yes" else None + alias_exists = bool(alias_name and spark.catalog.tableExists(alias_name)) + if alias_exists: + _check_existing_control(spark, alias_name, alias_resource_id(config["model_name"])) + if not target_exists: + definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) + spark.sql(f"CREATE TABLE {target_name} ({definition}) USING DELTA").collect() + if not control_exists: + _create_control(spark, control_name, table_identity(spark, target_name)) + if alias_name and not alias_exists: + _create_control(spark, alias_name, alias_resource_id(config["model_name"])) + return ProvisionResult( + source_name, + target_name, + not target_exists, + control_name, + not control_exists, + alias_name, + bool(alias_name and not alias_exists), + ) + + def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: """Keep the evaluation split and source snapshot identical across actions.""" return LocalTrainingSpec( @@ -164,27 +339,10 @@ def run_action( champion_version=config.get("champion_version"), quality_threshold=config.get("quality_threshold"), ) - if action == "score": - scoring = LocalWorkflowConfig( - runtime="databricks", - engine=config["engine"], - source=InputSource( - kind="uc_table", - table=config["score_source_table"], - read_mode="incremental", - max_rows=config["max_rows"], - max_bytes=config["max_bytes"], - ), - model=ModelSelection( - kind="local_pipeline", - name=config["model_name"], - version=config["model_version"], - tracking_uri=tracking_uri, - registry_uri=registry_uri, - ), - sink=OutputSink(kind="uc_delta", table=config["prediction_table"]), - ) - prepared = prepare_local_workflow(scoring) + if action in {"setup", "score"}: + prepared = prepare_local_workflow(_scoring_config(config)) + if action == "setup": + return provision_local_tables(spark, config, prepared) return run_incremental_local_batch( spark, prepared, @@ -192,6 +350,8 @@ def run_action( admission=DeltaTableAdmission(spark, config["score_admission_table"]), ) if action in {"compare", "stage", "promote"}: + if action != "compare" and config["alias_admission_table"] is None: + raise ValueError("Alias control is not configured; enable the lifecycle jobs first.") report, heldout = _comparison(spark, config) if action == "compare": return report diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 0a3ec671b..9d49d9ba0 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -236,6 +236,7 @@ def test_generated_config_keeps_company_output_in_each_target(): template.read_text(encoding="utf-8") .replace("{{.project_name}}", "customer_model") .replace("{{.engine}}", "pandas") + .replace("{{.include_lifecycle}}", "no") ) outputs = {} for target, catalog, suffix in ( @@ -261,3 +262,111 @@ def test_generated_config_keeps_company_output_in_each_target(): "syst": "syst_catalog.dsp_mlresult.customer_model_predictions", "prod": "prod_catalog.dsp_mlresult.customer_model_predictions", } + + +def test_minimal_generated_config_uses_one_existing_source(): + """Default training and scoring should reference one existing source table.""" + workflow = _workflow() + template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" + config = json.loads( + template.read_text(encoding="utf-8") + .replace("{{.project_name}}", "customer_model") + .replace("{{.engine}}", "pandas") + .replace("{{.include_lifecycle}}", "no") + ) + bound = workflow.resolve_target_config( + config, + { + "catalog": "test_catalog", + "input_schema": "input_schema", + "output_schema": "output_schema", + "metadata_schema": "metadata_schema", + "resource_suffix": "", + }, + ) + assert bound["training_table"] == bound["score_source_table"] + + +def test_setup_rejects_missing_source_without_creating_tables(): + """A wrong source reference must not create partial prediction resources.""" + workflow = _workflow() + spark = Mock() + spark.catalog.tableExists.return_value = False + with pytest.raises(ValueError, match="source"): + workflow.provision_local_tables(spark, _config(), object()) + spark.sql.assert_not_called() + + +def test_setup_creates_only_prediction_and_score_control(monkeypatch): + """First setup must leave inputs alone and create no alias table by default.""" + workflow = _workflow() + config = _config() + source = Mock() + source.columns = ["entity_id", "x"] + source.schema = { + "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) + } + source.select.return_value.limit.return_value.count.return_value = 2 + spark = Mock() + spark.catalog.tableExists.side_effect = lambda name: ( + name + in { + config["training_table"], + config["score_source_table"], + } + ) + spark.table.return_value = source + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + monkeypatch.setattr(workflow, "table_identity", Mock(return_value="prediction-id")) + prepared = SimpleNamespace( + artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), + preflight=SimpleNamespace( + ready=True, + output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), + ), + ) + result = workflow.provision_local_tables(spark, config, prepared) + statements = [call.args[0] for call in spark.sql.call_args_list] + creates = [statement for statement in statements if statement.startswith("CREATE TABLE")] + assert result.prediction_created and result.score_admission_created + assert result.alias_admission_table is None + assert len(creates) == 2 + assert creates[0].startswith(f"CREATE TABLE {config['prediction_table']} (") + assert creates[1].startswith(f"CREATE TABLE {config['score_admission_table']} USING DELTA") + + +def test_setup_replay_validates_existing_tables_without_creating_anything(monkeypatch): + """Rerunning setup must preserve the existing prediction and control tables.""" + workflow = _workflow() + config = _config() + source = Mock() + source.columns = ["entity_id", "x"] + source.schema = { + "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) + } + source.select.return_value.limit.return_value.count.return_value = 2 + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.table.return_value = source + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + monkeypatch.setattr(workflow, "table_identity", Mock(return_value="prediction-id")) + check_target = Mock() + check_control = Mock() + monkeypatch.setattr(workflow, "_check_existing_table", check_target) + monkeypatch.setattr(workflow, "_check_existing_control", check_control) + prepared = SimpleNamespace( + artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), + preflight=SimpleNamespace( + ready=True, + output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), + ), + ) + result = workflow.provision_local_tables(spark, config, prepared) + check_target.assert_called_once() + check_control.assert_called_once_with(spark, config["score_admission_table"], "prediction-id") + assert not result.prediction_created and not result.score_admission_created + assert all(not call.args[0].startswith("CREATE TABLE") for call in spark.sql.call_args_list) From b2403c085c6e568400721b1257535575b728d0b3 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 18:34:02 +0300 Subject: [PATCH 48/85] feat: simplify local Databricks bundle to two jobs Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 22 +- docs/user_guide/databricks_bundle.md | 51 +++-- ...-clean-generic-bundle-validation-report.md | 7 +- .../25-sm20s-two-job-bundle-plan.md | 47 +++++ ...26-sm20s-two-job-live-validation-report.md | 42 ++++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 5 +- .../integrations/databricks/admission.py | 32 ++- .../databricks/local_incremental.py | 6 +- .../integrations/test_batch_admission.py | 14 ++ .../integrations/test_local_delta_publish.py | 25 +++ .../databricks_template_schema.json | 21 +- .../examples/policy-init.example.json | 1 - .../examples/serverless-init.example.json | 1 - .../template/{{.project_name}}/README.md.tmpl | 39 ++-- .../config/workflow.json.tmpl | 4 - .../{{.project_name}}/databricks.yml.tmpl | 2 +- .../resources/workflow.jobs.yml.tmpl | 179 ---------------- .../{{.project_name}}/src/workflow.py | 197 ++---------------- .../integration/test_sm20a_bundle_template.py | 173 ++++++++------- 19 files changed, 343 insertions(+), 525 deletions(-) create mode 100644 initiatives/spark_and_mlflow/25-sm20s-two-job-bundle-plan.md create mode 100644 initiatives/spark_and_mlflow/26-sm20s-two-job-live-validation-report.md diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 15edbac36..9cac474fb 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -11,14 +11,13 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed - The local-engine Bundle template exposes editable `dev/test/syst/prod` - targets with separate host/catalog bindings, a serverless or policy-backed - compute choice and optional champion/challenger jobs. The minimal path uses - one existing source reference, creates only three jobs on deployment, and - prepares one prediction and one internal score-control table at explicit - setup. The earlier isolated Skyulf test jobs and schemas were removed at - the user's request. A clean personal serverless run then trained a Polars - model, wrote 600 initial and 50 later predictions, and replayed without a - new commit. + targets with separate host/catalog bindings and a serverless or policy-backed + compute choice. Its default now deploys only `train` and `score`; the first + score validates the source and pinned model and creates only its prediction + table. It uses explicit single-writer admission with serialized score runs, + while Core retains shared admission for multi-writer deployments. The + earlier three-job personal rehearsal trained a Polars model, wrote 600 + initial and 50 later predictions, and replayed without a new commit. - Prediction Delta targets use `run_id`, `model_name` and `model_version` metadata columns. Existing test targets with the former `__skyulf_*` schema require a new target; the writer does not migrate tables. @@ -37,10 +36,9 @@ execution, MLflow registry and Databricks delivery remain under development. ### Added -- A custom local-engine Databricks Bundle template generates three default - jobs for candidate training, explicit output setup and automatic incremental - scoring. Read-only comparison, challenger staging and explicit promotion are - opt-in. It uses existing Skyulf Core services and an editable pandas/Polars +- A custom local-engine Databricks Bundle template generates two default + jobs for candidate training and automatic incremental scoring, using + existing Skyulf Core services and an editable pandas/Polars configuration. The earlier isolated lifecycle rehearsal passed train/compare/stage/promote and 2+2-row incremental scoring; the later clean generic rehearsal used one source table and proved 600+50-row scoring with a diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index f3dc54527..b901954e1 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -12,8 +12,7 @@ databricks bundle init templates/databricks --output-dir ./generated ``` The short path asks for project name, engine, serverless or policy-backed job -compute, optional champion/challenger lifecycle and the existing `dev` -catalog/schema. Serverless and no lifecycle are the defaults. Reviewable +compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable noninteractive examples are in `templates/databricks/examples/`. The generated project has its own `databricks.yml`; Skyulf's root has no Bundle config. @@ -27,28 +26,25 @@ initialization. Serverless compute needs none of those fields. ## What is created -`bundle deploy` creates only three jobs by default and uploads their code: +`bundle deploy` creates only two jobs and uploads their code: | Job | Purpose | UC objects created when run | | --- | --- | --- | | `train` | Fit one candidate and log held-out metrics | One registered model/version | -| `setup` | Verify source and pinned model, then prepare output | One prediction table and one internal score-control table, only if absent | -| `score` | Score the initial source, then new CDF inserts | Rows in the same prediction table | +| `score` | Verify the source and pinned model, create output if absent, then score initial and later CDF inserts | One prediction table, only if absent; rows in that table | -`compare`, `stage` and `promote` jobs are generated only with -`include_lifecycle=yes`. In that case `setup` also creates one alias-control -table. No schedule, endpoint or Unity Catalog table is created by deployment -alone. +No schedule, endpoint or Unity Catalog table is created by deployment alone. +The starting Bundle has no alias lifecycle job. Skyulf Core's registry +comparison and promotion services remain available for a separately designed +champion/challenger workflow. -The six relevant configuration names have different roles: +The four relevant Unity Catalog names have different roles: | Name | Meaning | | --- | --- | | `training_table` | Existing labeled input table, pinned to a Delta version for training | | `score_source_table` | Existing CDF-enabled source of rows to predict | | `prediction_table` | The one output table for this model | -| `score_admission_table` | Internal one-row Delta coordination table for safe incremental writes | -| `alias_admission_table` | Optional coordination table for champion/challenger changes | | `model_name` | Registered Unity Catalog model, not a table | The first two references point to **the same existing table by default**. @@ -71,28 +67,29 @@ databricks bundle run train -t dev --profile ``` Inspect the registered model version, put that concrete value in -`model_version`, redeploy the changed JSON, then run `setup` and `score`. -`setup` rejects a missing source, disabled CDF, unsuitable row keys, a model -output mismatch or an existing target/control schema mismatch before it -creates missing output state. It checks initial row count against `max_rows`; -`score` also checks decoded transfer bytes against `max_bytes`. Existing -tables are never overwritten. `score` first processes the current source +`model_version`, redeploy the changed JSON, then run `score`. The first score +rejects a missing source, disabled CDF, unsuitable row keys, a model output +mismatch or an existing target schema mismatch before it creates the single +prediction table. It checks initial row count against `max_rows`; each score +also checks decoded transfer bytes against `max_bytes`. Existing tables are +never overwritten. The first score processes the current source snapshot; later runs process only new inserts since the committed Delta receipt. A repeat without new rows is a no-op. No monthly date or source version is entered for each run. -The first candidate does not become champion automatically. Optional -`compare` is read-only, `stage` assigns an eligible `@challenger`, and -`promote` explicitly moves it to `@champion` while retaining the prior -version as `@previous_champion`. Scoring stays pinned to its configured model -version; changing aliases does not rewrite old predictions. Full-history -rescore, schedules, online endpoints and Spark-native FE/model execution are -separate work. +The first candidate does not become champion automatically. Scoring stays +pinned to its configured model version; changing aliases does not rewrite old +predictions. `max_concurrent_runs: 1` serializes the generated score job, but +does not coordinate other jobs. Grant prediction-table writes only to this +job's identity. For multiple publishers, use Skyulf Core's shared admission +provider. Full-history rescore, schedules, online endpoints and Spark-native +FE/model execution are separate work. The older SM-20a personal serverless rehearsal passed, but its jobs and test schemas were removed at the user's request. The subsequent clean generic `dev` rehearsal trained a Polars model from 600 real taxi rows, wrote 600 initial and 50 later predictions to one table, and replayed without another commit. The personal test resources remain available for inspection. The -`test`, `syst` and `prod` placeholders have not been deployed in a company -workspace. +That rehearsal used the earlier three-job template; the two-job design needs +its own live validation. The `test`, `syst` and `prod` placeholders have not +been deployed in a company workspace. diff --git a/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md b/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md index ea23347d2..3aaaaaada 100644 --- a/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md +++ b/initiatives/spark_and_mlflow/24-sm20r-clean-generic-bundle-validation-report.md @@ -61,9 +61,10 @@ unverified by this clean run. The final read-only notebook found 650 source and 650 prediction rows, 650 distinct prediction keys, and only registered model version 1 in the output. -The final CLI inventory still listed exactly the three Bundle jobs and the -three tables above. These resources remain in the personal test workspace so -they can be inspected in the Databricks UI. +The final CLI inventory at the time listed exactly the three Bundle jobs and +the three tables above. SM-20S later removed those three old jobs and the old +prediction/control tables after its two-job validation; see +[SM-20S evidence](26-sm20s-two-job-live-validation-report.md). Local regression tests: `13 passed` with a workspace-local pytest temp directory. Ruff and Ty passed on the changed Python files; strict MkDocs diff --git a/initiatives/spark_and_mlflow/25-sm20s-two-job-bundle-plan.md b/initiatives/spark_and_mlflow/25-sm20s-two-job-bundle-plan.md new file mode 100644 index 000000000..e5662790d --- /dev/null +++ b/initiatives/spark_and_mlflow/25-sm20s-two-job-bundle-plan.md @@ -0,0 +1,47 @@ +# SM-20S: two-job, table-minimal local Bundle + +Updated: 2026-09-24. The user approved moving explicit `setup` into the first +`score` run and removing admission tables from the starting Bundle. The +single-writer boundary is intentional: one Bundle score job owns writes to one +prediction table, with `max_concurrent_runs: 1`. Other publishers must not +write that table. Existing admission-backed Core callers retain their stronger +cross-job coordination contract. + +## Contract + +- `train` is manual/on-demand and registers a candidate model with MLflow + metrics. It creates no UC table. +- `score` checks the existing CDF-enabled source and pinned model; if its + prediction table is missing, it creates exactly that table, then scores the + first source snapshot or only new inserts. A repeated run is a no-op. +- The default generated Bundle has two jobs and no `setup`, comparison, stage, + promotion or alias jobs. It creates no score/alias admission table. The + target Delta transaction receipt and pinned model version stay in place. +- Default inference uses a concrete model version. A new model requires an + explicit `model_version` configuration change and redeployment before scoring + switches versions. This keeps candidate training separate from activation. +- `max_concurrent_runs: 1` serializes this one Databricks job only. Access to + the prediction table must restrict other writers. The no-table option does + not promise cross-job coordination. The former shared admission path remains + available in Skyulf Core for multi-writer deployments. + +## Steps and evidence + +- [x] Add a focused failing Core test: a real local Delta initial/append/replay + cycle using an explicit single-writer provider, without a control table. +- [x] Add the minimal provider and document its external single-writer + precondition; keep existing admission validation for other callers. +- [x] Add failing generated-workflow tests for two job keys, no admission + table/alias configuration, and score creating only its missing prediction + table before invoking the Core incremental writer. +- [x] Refactor template config, workflow, prompts and job resources; keep both + pandas and Polars, serverless and policy-cluster render paths, and four + environment targets. +- [x] Update English Bundle guide, generated README, queue and changelog. +- [x] Verify focused tests, Ruff, Ty, generated strict Bundle validation and + strict docs build. Perform a bounded personal serverless first/append/replay + run, then inventory jobs and tables before claiming live parity. + +Evidence: [two-job personal live report](26-sm20s-two-job-live-validation-report.md). +Only the serverless `dev` target was strictly validated and run; the policy +variant was rendered and parsed but needs an approved policy for live validation. diff --git a/initiatives/spark_and_mlflow/26-sm20s-two-job-live-validation-report.md b/initiatives/spark_and_mlflow/26-sm20s-two-job-live-validation-report.md new file mode 100644 index 000000000..7919947d0 --- /dev/null +++ b/initiatives/spark_and_mlflow/26-sm20s-two-job-live-validation-report.md @@ -0,0 +1,42 @@ +# SM-20S two-job local Bundle validation + +Date: 2026-09-24. Personal Databricks profile: `skyulf`; `dev` target only. +This run reused the existing CDF-enabled real-taxi source and registered +Polars model version 1 in `workspace.skyulf_bundle_first_20260924`. The new +Bundle is `skyulf_twojob`; the test did not deploy to a company workspace. + +## Bundle and Delta results + +The serverless project passed `databricks bundle validate --strict`, then +deployed exactly two persistent jobs: `skyulf_twojob_train` +(`290396749537917`) and `skyulf_twojob_score` (`1046235940974377`). The +score job has `max_concurrent_runs: 1`. The policy-cluster template also +rendered as exactly these two job keys with that score limit; a real policy +cluster was not provisioned or run. Deployment itself created no UC table. + +| Step | Run | Result | +| --- | --- | --- | +| First score | [192862744456152](https://dbc-45604623-c18b.cloud.databricks.com/jobs/1046235940974377/runs/192862744456152?o=7474646244882000) | Created only `skyulf_twojob_predictions`; 650 inputs, 650 outputs, target commit 1 | +| Unchanged replay | [383783499229420](https://dbc-45604623-c18b.cloud.databricks.com/jobs/1046235940974377/runs/383783499229420?o=7474646244882000) | 0 inputs, `noop=true`, target commit stayed 1 | +| Append one source row | One-time run `1116828359967045` | Exactly one distinct `entity_id` appended to the existing source | +| Incremental score | [183922007779250](https://dbc-45604623-c18b.cloud.databricks.com/jobs/1046235940974377/runs/183922007779250?o=7474646244882000) | 1 input, 1 output, target commit 2 | +| Independent audit | One-time run `963251710081057` | 651 source rows, 651 prediction rows, 651 distinct prediction keys, one appended-row prediction, only model version 1 | +| Final code replay | [341978630819415](https://dbc-45604623-c18b.cloud.databricks.com/jobs/1046235940974377/runs/341978630819415?o=7474646244882000) | Redeployed final notebook; 0 inputs, `noop=true`, target commit stayed 2 | + +After the final replay, the prior three-job test's `setup`, `train`, and +`score` jobs and its old prediction and score-control tables were removed. +The final CLI inventory returned exactly the two `skyulf_twojob` jobs and two +managed Delta tables in the schema: existing `skyulf_reset_dev_source` and +new `skyulf_twojob_predictions`. The registered UC model remains a model, +not a table. The one-time append and audit notebooks were removed from the +new Bundle's workspace files after their runs finished. + +## Local checks and operational boundary + +Focused workflow/admission tests: 18 passed. A real local Delta test passed +first score, one-row append, and unchanged replay using +`SingleWriterAdmission` without a control table. Ruff lint/format, Ty, and +strict MkDocs build passed. The serverless test does not establish policy +cluster behavior or writer isolation: the no-table admission mode assumes a +single serialized score job and no other principal writing its target. A +deployment with multiple publishers must use Core's shared admission path. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 32303250a..21b0b1a3b 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a/20R complete. SM-28b is next. Target: 0.9.0.** +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a/20R/20S complete. SM-28b is next. Target: 0.9.0.** Next deliverable: optional monthly local retraining schedule. Spark expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring @@ -54,7 +54,8 @@ SUPERSEDED = replaced by a later user-directed scope; not a completed feature. | SM-20a | First local-engine Bundle/template | SM-24a, SM-15I, SM-22b, SM-22c, SM-28a | DONE | Generated/deployed Polars Bundle; train/compare/stage/promote and 2+2 incremental score/no-op live; [evidence](21-sm20a-local-bundle-validation-report.md) | | SM-20P | Company-shaped Bundle draft | SM-20a | SUPERSEDED | Replaced by the generic four-target SM-20R direction; no company workspace deployment | | SM-20R | Reset personal tests; generic minimal Bundle | SM-20a | DONE | Ten test jobs and three schemas removed; four target shapes validated, personal dev deployed with three jobs; one source, one prediction, one internal control, one UC model; Polars 600+50-row scoring and no-op replay; [live evidence](24-sm20r-clean-generic-bundle-validation-report.md) | -| SM-28b | Optional monthly retraining schedule | SM-20a, SM-28a | READY | Wire separate train/compare/explicit-promote/score jobs with label cutoff and pinned versions | +| SM-20S | Two-job, table-minimal local Bundle | SM-20R | DONE | First score creates only prediction output; no admission tables; 650+1 rows, replay no-op, final two jobs/two tables; [live evidence](26-sm20s-two-job-live-validation-report.md) | +| SM-28b | Optional monthly retraining schedule | SM-20S, SM-28a | READY | Design one optional scheduled workflow around pinned labels, candidate comparison and explicit activation; keep the two-job starter unchanged and decide shared-target writer admission before wiring scoring | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | | SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | LATER | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | diff --git a/skyulf-core/skyulf/integrations/databricks/admission.py b/skyulf-core/skyulf/integrations/databricks/admission.py index 302bb6e51..43e459e43 100644 --- a/skyulf-core/skyulf/integrations/databricks/admission.py +++ b/skyulf-core/skyulf/integrations/databricks/admission.py @@ -15,11 +15,12 @@ class BatchConflictError(RuntimeError): class PublishAdmission(Protocol): - """Hold an exclusive table lock until the commit receipt has been read. + """Control publication until the commit receipt has been read. - All publishers must use the same authority keyed by immutable Delta table ID. - Ownership must not expire while the context is active. This API does not - pass fencing tokens to Delta; time-limited distributed leases are unsupported. + Shared providers must use the same authority keyed by immutable Delta table + ID. ``SingleWriterAdmission`` instead relies on caller-enforced exclusive + write access and serialized job runs. This API does not pass fencing tokens + to Delta; time-limited distributed leases are unsupported. """ local_only: bool @@ -30,9 +31,9 @@ def hold(self, table_id: str) -> AbstractContextManager[None]: def validate_admission(spark: Any, admission: PublishAdmission | None) -> PublishAdmission: - """Reject absent admission or local locks on a distributed runtime before I/O.""" + """Require an explicit shared or externally enforced single-writer policy.""" if admission is None or not callable(getattr(admission, "hold", None)): - raise ValueError("A shared publish admission is required.") + raise ValueError("An explicit publish admission is required.") if admission.local_only: master = spark.sparkContext.master if master != "local" and not master.startswith("local["): @@ -40,6 +41,25 @@ def validate_admission(spark: Any, admission: PublishAdmission | None) -> Publis return admission +class SingleWriterAdmission: + """Opt in to table-free publication when one external writer is guaranteed. + + This provider does not lock. Use it only when one job owns all target writes, + its runs cannot overlap, and other principals cannot modify the target. + Delta receipts and transaction IDs still detect/replay committed increments, + but they do not replace cross-job admission if another writer is allowed. + """ + + local_only = False + + @contextmanager + def hold(self, table_id: str) -> Iterator[None]: + """Enter the caller's externally serialized single-writer scope.""" + if type(table_id) is not str or not table_id: + raise ValueError("Single-writer publication needs a target table ID.") + yield + + class LocalTableLock: """Use OS file locks for local Spark drivers sharing one lock directory. diff --git a/skyulf-core/skyulf/integrations/databricks/local_incremental.py b/skyulf-core/skyulf/integrations/databricks/local_incremental.py index 9f395c3f6..f12c24f65 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_incremental.py +++ b/skyulf-core/skyulf/integrations/databricks/local_incremental.py @@ -154,8 +154,10 @@ def run_incremental_local_batch( """Score the initial snapshot, then only inserts since the last target receipt. Source and target tables already exist. The source must have Delta CDF - enabled before subsequent changes. All target writers must share admission; - a target commit outside this protocol halts automatic scoring. + enabled before subsequent changes. Multiple target writers must share + admission. A sole writer may instead use explicit SingleWriterAdmission + when its job is serialized and no other writer can modify the target. + A target commit outside this protocol halts automatic scoring. """ inputs = _validate_prepared(prepared, row_keys, period_column) admission = validate_admission(spark, admission) diff --git a/skyulf-core/tests/integrations/test_batch_admission.py b/skyulf-core/tests/integrations/test_batch_admission.py index efbfb192f..4e7774427 100644 --- a/skyulf-core/tests/integrations/test_batch_admission.py +++ b/skyulf-core/tests/integrations/test_batch_admission.py @@ -3,6 +3,7 @@ import os import subprocess import sys +from types import SimpleNamespace def test_independent_process_cannot_enter_held_table_lock(tmp_path): @@ -31,3 +32,16 @@ def test_independent_process_cannot_enter_held_table_lock(tmp_path): assert child.stdout.strip() == "BUSY" with lock.hold("table-id"): assert (tmp_path / "locks").is_dir() + + +def test_explicit_single_writer_path_needs_no_control_table(tmp_path): + """A caller-controlled sole writer can publish without provisioning lock state.""" + from skyulf.integrations.databricks.admission import ( + SingleWriterAdmission, + validate_admission, + ) + + spark = SimpleNamespace(sparkContext=SimpleNamespace(master="spark://remote")) + provider = validate_admission(spark, SingleWriterAdmission()) + with provider.hold("prediction-table-id"): + assert list(tmp_path.iterdir()) == [] diff --git a/skyulf-core/tests/integrations/test_local_delta_publish.py b/skyulf-core/tests/integrations/test_local_delta_publish.py index da1630248..e39d81327 100644 --- a/skyulf-core/tests/integrations/test_local_delta_publish.py +++ b/skyulf-core/tests/integrations/test_local_delta_publish.py @@ -295,6 +295,31 @@ def test_incremental_local_batch_discovers_appends_without_period_inputs(local_d assert rows[2]["run_id"] != rows[1]["run_id"] +def test_incremental_single_writer_uses_receipts_without_control_table(local_delta_case): + """A sole writer can replay Delta receipts without provisioning lock state.""" + from skyulf.integrations.databricks import run_incremental_local_batch + from skyulf.integrations.databricks.admission import SingleWriterAdmission + + spark, source, target, prepared, _ = _prepared_incremental_case(local_delta_case) + admission = SingleWriterAdmission() + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 6, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + second = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + replay = run_incremental_local_batch( + spark, prepared, row_keys=("id",), period_column="event_time", admission=admission + ) + assert (first.input_count, second.input_count, replay.input_count) == (2, 1, 0) + assert replay.noop and replay.commit_version == second.commit_version + assert [row.id for row in spark.table(target).orderBy("id").collect()] == [1, 2, 3] + + def test_incremental_local_batch_does_not_require_a_date_column(local_delta_case): """New rows are found from Delta commits even when no event date exists.""" from skyulf.integrations.databricks import run_incremental_local_batch diff --git a/templates/databricks/databricks_template_schema.json b/templates/databricks/databricks_template_schema.json index ac02bd598..8ed776695 100644 --- a/templates/databricks/databricks_template_schema.json +++ b/templates/databricks/databricks_template_schema.json @@ -22,50 +22,43 @@ "description": "Job compute mode for this project", "enum": ["serverless", "policy_cluster"] }, - "include_lifecycle": { - "order": 4, - "type": "string", - "default": "no", - "description": "Add optional compare, stage and promote jobs?", - "enum": ["no", "yes"] - }, "catalog": { - "order": 5, + "order": 4, "type": "string", "default": "workspace", "description": "Existing dev Unity Catalog catalog", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, "schema": { - "order": 6, + "order": 5, "type": "string", "default": "default", "description": "Existing dev Unity Catalog schema", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, "cluster_policy_name": { - "order": 7, + "order": 6, "type": "string", "default": "REPLACE_WITH_APPROVED_POLICY", "description": "Approved job-cluster policy name", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "spark_version": { - "order": 8, + "order": 7, "type": "string", "default": "17.3.x-cpu-ml-scala2.13", "description": "Approved Databricks ML Runtime for the job cluster", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "node_type_id": { - "order": 9, + "order": 8, "type": "string", "default": "REPLACE_WITH_NODE_TYPE", "description": "Approved job-cluster node type", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "cost_tag_key": { - "order": 10, + "order": 9, "type": "string", "default": "CostCenter", "description": "Approved cluster cost tag key", @@ -73,7 +66,7 @@ "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "cost_tag_value": { - "order": 11, + "order": 10, "type": "string", "default": "REPLACE_WITH_COST_TAG", "description": "Approved cluster cost tag value", diff --git a/templates/databricks/examples/policy-init.example.json b/templates/databricks/examples/policy-init.example.json index 8e0787798..94a9fd8a0 100644 --- a/templates/databricks/examples/policy-init.example.json +++ b/templates/databricks/examples/policy-init.example.json @@ -2,7 +2,6 @@ "project_name": "my_model", "engine": "pandas", "compute_mode": "policy_cluster", - "include_lifecycle": "yes", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", "cluster_policy_name": "REPLACE_WITH_APPROVED_POLICY", diff --git a/templates/databricks/examples/serverless-init.example.json b/templates/databricks/examples/serverless-init.example.json index a23b8b130..aa26e4f83 100644 --- a/templates/databricks/examples/serverless-init.example.json +++ b/templates/databricks/examples/serverless-init.example.json @@ -2,7 +2,6 @@ "project_name": "my_model", "engine": "pandas", "compute_mode": "serverless", - "include_lifecycle": "no", "catalog": "workspace", "schema": "my_dev_schema" } diff --git a/templates/databricks/template/{{.project_name}}/README.md.tmpl b/templates/databricks/template/{{.project_name}}/README.md.tmpl index 9e50e0cbc..1e292cd83 100644 --- a/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -8,31 +8,28 @@ same Skyulf workflow code with different target bindings. ## What deployment creates `bundle deploy` uploads the wheel, notebook and configuration, and creates -{{if eq .include_lifecycle "yes"}}six{{else}}three{{end}} jobs. It creates **no** -Unity Catalog table or registered model. The default jobs are: +two jobs. It creates **no** Unity Catalog table or registered model. | Job | Run it when | UC effect | | --- | --- | --- | | `train` | A labeled snapshot is ready | Registers one candidate model and logs MLflow metrics | -| `setup` | The model version and source are ready | Creates one empty prediction table and one score-control table if absent | -| `score` | New rows need predictions | Appends only new-row predictions to the same prediction table | +| `score` | The model version is pinned and rows need predictions | Creates the prediction table if absent, then appends predictions for initial or new rows | -{{if eq .include_lifecycle "yes"}} -The optional `compare`, `stage` and `promote` jobs are also generated. Setup -then creates a separate alias-control table. Those jobs review and explicitly -move `@challenger` and `@champion`; they never run as part of ordinary scoring. -{{else}} -The champion/challenger jobs and alias-control table are absent in this -minimal project. Generate with `include_lifecycle=yes` when needed. -{{end}} +Champion/challenger management is available through Skyulf Core but has no +job in this starting Bundle. Training a candidate does not activate it for +scoring. Set `model_version` to a concrete registered version and redeploy +when you want scoring to use it. `training_table` is the existing labeled input. `score_source_table` is the existing input to predict; the generated config points both at **one table**. You may give them different UC names when the labeled training data and new inference data have different lifecycles. Neither is created by this Bundle. -`prediction_table` is the single model output table. `score_admission_table` -holds one internal ownership row so concurrent writers cannot silently -duplicate an increment. `model_name` is a registered UC model, not a table. +`prediction_table` is the single model output table. `model_name` is a +registered UC model, not a table. The Bundle creates no admission table. +The score job has `max_concurrent_runs: 1`; grant write access to the +prediction table only to this job's identity. Other jobs must not write it. +Skyulf Core's shared-admission option remains available when multiple jobs +need to publish to one target. ## Prepare the project @@ -74,12 +71,12 @@ clusters are a separate compute choice at project initialization. 1. Run `train` against a pinned labeled Delta version. It logs held-out MLflow metrics and registers a concrete model version. 2. Put that concrete version in `model_version` in `config/workflow.json` and - redeploy. Run `setup`. Setup verifies the source, Change Data Feed, model - outputs, row keys and existing target/control schemas before writing. It - creates only missing output/control tables; it never overwrites existing - tables or creates the source. Its row check is bounded by `max_rows`; the - scoring job also enforces `max_bytes` on the local transfer. -3. Run `score`. Add new rows to the existing source Delta table and run `score` + redeploy. Run `score`. It verifies the source, Change Data Feed, model + outputs, row keys and any existing target schema before writing. It creates + only the missing prediction table; it never overwrites an existing table + or creates the source. The initial row check is bounded by `max_rows`, and + scoring enforces `max_rows` and `max_bytes` for each local transfer. +3. Add new rows to the existing source Delta table and run `score` again. An unchanged replay is a no-op. No date or source-version argument is entered for each run. Source updates or deletes require a separate rescore policy. diff --git a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index ba42a5b8e..18e88e765 100644 --- a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -1,16 +1,12 @@ { "engine": "{{.engine}}", - "include_lifecycle": "{{.include_lifecycle}}", "training_table": "{catalog}.{input_schema}.{{.project_name}}_source", "training_version": 0, "score_source_table": "{catalog}.{input_schema}.{{.project_name}}_source", "prediction_table": "{catalog}.{output_schema}.{{.project_name}}_predictions{resource_suffix}", - "score_admission_table": "{catalog}.{metadata_schema}.{{.project_name}}_score_admission{resource_suffix}", - "alias_admission_table": "{catalog}.{metadata_schema}.{{.project_name}}_alias_admission{resource_suffix}", "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", "model_version": "1", "champion_version": null, - "candidate_version": "2", "row_keys": ["entity_id"], "input_columns": ["feature_value"], "target_column": "target", diff --git a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl index 072338cc3..a7681d2d3 100644 --- a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +++ b/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl @@ -21,7 +21,7 @@ variables: description: Prediction output schema default: {{.schema}} metadata_schema: - description: Model and internal coordination schema + description: Registered model schema default: {{.schema}} resource_suffix: description: Optional namespace suffix for shared development targets diff --git a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl index b5ba3b069..dc2f9d3b3 100644 --- a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +++ b/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -1,50 +1,5 @@ resources: jobs: - setup: - name: ${bundle.name}_setup - max_concurrent_runs: 1 - tasks: - - task_key: setup - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: setup - config_path: ${workspace.file_path}/config/workflow.json - catalog: ${var.catalog} - input_schema: ${var.input_schema} - output_schema: ${var.output_schema} - metadata_schema: ${var.metadata_schema} - resource_suffix: ${var.resource_suffix} -{{if eq .compute_mode "serverless"}} - environment_key: skyulf -{{else}} - job_cluster_key: skyulf - libraries: - - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - pypi: - package: mlflow==3.16.1 -{{end}} -{{if eq .compute_mode "serverless"}} - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 -{{else}} - job_clusters: - - job_cluster_key: skyulf - new_cluster: - spark_version: {{.spark_version}} - node_type_id: {{.node_type_id}} - policy_id: ${var.cluster_policy_id} - custom_tags: - {{.cost_tag_key}}: ${var.cost_tag_value} - autoscale: - min_workers: 2 - max_workers: 4 -{{end}} train: name: ${bundle.name}_train tasks: @@ -89,140 +44,6 @@ resources: autoscale: min_workers: 2 max_workers: 4 -{{end}} -{{if eq .include_lifecycle "yes"}} - compare: - name: ${bundle.name}_compare - tasks: - - task_key: compare - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: compare - config_path: ${workspace.file_path}/config/workflow.json - catalog: ${var.catalog} - input_schema: ${var.input_schema} - output_schema: ${var.output_schema} - metadata_schema: ${var.metadata_schema} - resource_suffix: ${var.resource_suffix} -{{if eq .compute_mode "serverless"}} - environment_key: skyulf -{{else}} - job_cluster_key: skyulf - libraries: - - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - pypi: - package: mlflow==3.16.1 -{{end}} -{{if eq .compute_mode "serverless"}} - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 -{{else}} - job_clusters: - - job_cluster_key: skyulf - new_cluster: - spark_version: {{.spark_version}} - node_type_id: {{.node_type_id}} - policy_id: ${var.cluster_policy_id} - custom_tags: - {{.cost_tag_key}}: ${var.cost_tag_value} - autoscale: - min_workers: 2 - max_workers: 4 -{{end}} - stage: - name: ${bundle.name}_stage - tasks: - - task_key: stage - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: stage - config_path: ${workspace.file_path}/config/workflow.json - catalog: ${var.catalog} - input_schema: ${var.input_schema} - output_schema: ${var.output_schema} - metadata_schema: ${var.metadata_schema} - resource_suffix: ${var.resource_suffix} -{{if eq .compute_mode "serverless"}} - environment_key: skyulf -{{else}} - job_cluster_key: skyulf - libraries: - - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - pypi: - package: mlflow==3.16.1 -{{end}} -{{if eq .compute_mode "serverless"}} - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 -{{else}} - job_clusters: - - job_cluster_key: skyulf - new_cluster: - spark_version: {{.spark_version}} - node_type_id: {{.node_type_id}} - policy_id: ${var.cluster_policy_id} - custom_tags: - {{.cost_tag_key}}: ${var.cost_tag_value} - autoscale: - min_workers: 2 - max_workers: 4 -{{end}} - promote: - name: ${bundle.name}_promote - tasks: - - task_key: promote - notebook_task: - notebook_path: ../src/workflow.py - base_parameters: - action: promote - config_path: ${workspace.file_path}/config/workflow.json - catalog: ${var.catalog} - input_schema: ${var.input_schema} - output_schema: ${var.output_schema} - metadata_schema: ${var.metadata_schema} - resource_suffix: ${var.resource_suffix} -{{if eq .compute_mode "serverless"}} - environment_key: skyulf -{{else}} - job_cluster_key: skyulf - libraries: - - whl: ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - pypi: - package: mlflow==3.16.1 -{{end}} -{{if eq .compute_mode "serverless"}} - environments: - - environment_key: skyulf - spec: - client: "4" - dependencies: - - ${workspace.file_path}/dist/skyulf_core-0.9.0-py3-none-any.whl - - mlflow==3.16.1 -{{else}} - job_clusters: - - job_cluster_key: skyulf - new_cluster: - spark_version: {{.spark_version}} - node_type_id: {{.node_type_id}} - policy_id: ${var.cluster_policy_id} - custom_tags: - {{.cost_tag_key}}: ${var.cost_tag_value} - autoscale: - min_workers: 2 - max_workers: 4 -{{end}} {{end}} score: name: ${bundle.name}_score diff --git a/templates/databricks/template/{{.project_name}}/src/workflow.py b/templates/databricks/template/{{.project_name}}/src/workflow.py index b0874aa0f..31803983d 100644 --- a/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -1,16 +1,14 @@ # Databricks notebook source -"""Run one bounded Skyulf local training, comparison, alias or scoring action.""" +"""Run one bounded Skyulf local training or incremental scoring action.""" import json import re import tempfile -from dataclasses import asdict, dataclass +from dataclasses import asdict from datetime import datetime from pathlib import Path from typing import Any -import polars as pl - from skyulf.integrations.databricks import ( InputSource, LocalTrainingSpec, @@ -18,28 +16,15 @@ ModelSelection, OutputSink, prepare_local_workflow, - read_training_snapshot, run_incremental_local_batch, - split_labeled_snapshot, train_local_candidate, ) -from skyulf.integrations.databricks.delta import table_identity -from skyulf.integrations.databricks.delta_admission import DeltaTableAdmission -from skyulf.integrations.mlflow.promotion import ( - DeltaAliasAdmission, - alias_resource_id, - promote_candidate, - stage_challenger, -) -from skyulf.integrations.mlflow.registry import resolve_model -from skyulf.integrations.mlflow.validation import compare_registered_local_models +from skyulf.integrations.databricks.admission import SingleWriterAdmission _TABLE_FIELDS = ( "training_table", "score_source_table", "prediction_table", - "score_admission_table", - "alias_admission_table", "model_name", ) _IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") @@ -52,19 +37,6 @@ } -@dataclass(frozen=True, slots=True) -class ProvisionResult: - """Report the UC objects verified or created by one explicit setup run.""" - - source_table: str - prediction_table: str - prediction_created: bool - score_admission_table: str - score_admission_created: bool - alias_admission_table: str | None - alias_admission_created: bool - - def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: """Bind only UC object names to one validated Bundle target.""" for name in ("catalog", "input_schema", "output_schema", "metadata_schema"): @@ -76,20 +48,13 @@ def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> d resolved = config.copy() for name in _TABLE_FIELDS: value = config[name] - if name == "alias_admission_table" and value is None: - continue if type(value) is not str: raise ValueError(f"{name} must be a string.") for key, replacement in bindings.items(): value = value.replace("{" + key + "}", replacement) if not _TABLE_NAME.fullmatch(value): raise ValueError(f"{name} must resolve to a three-part UC name.") - if name in { - "prediction_table", - "score_admission_table", - "alias_admission_table", - "model_name", - }: + if name in {"prediction_table", "model_name"}: schema = "output_schema" if name == "prediction_table" else "metadata_schema" expected = f"{bindings['catalog']}.{bindings[schema]}." if not value.startswith(expected): @@ -101,7 +66,7 @@ def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> d def _scoring_config(config: dict[str, Any]) -> LocalWorkflowConfig: - """Bind the same pinned local model and source for setup and scoring.""" + """Bind the pinned local model and source for incremental scoring.""" return LocalWorkflowConfig( runtime="databricks", engine=config["engine"], @@ -163,58 +128,21 @@ def _check_existing_table(spark: Any, name: str, columns: tuple[tuple[str, str, raise ValueError(f"Existing prediction table {name} differs from the model output schema.") -def _check_existing_control(spark: Any, name: str, target_id: str) -> None: - """Require exactly one idle admission row bound to the intended resource.""" - frame = spark.table(name) - actual = {field.name: field.dataType.typeName() for field in frame.schema.fields} - if actual != {"target_id": "string", "owner": "string"}: - raise ValueError(f"Existing admission table {name} has an invalid schema.") - rows = frame.limit(2).collect() - if len(rows) != 1 or rows[0]["target_id"] != target_id or rows[0]["owner"] is not None: - raise ValueError(f"Existing admission table {name} is not idle for this resource.") - - -def _create_control(spark: Any, name: str, target_id: str) -> None: - """Create an admission table and its single row in one Delta CTAS statement.""" - spark.sql( - f"CREATE TABLE {name} USING DELTA AS " - "SELECT :target_id AS target_id, CAST(NULL AS STRING) AS owner", - args={"target_id": target_id}, - ).collect() - - -def provision_local_tables(spark: Any, config: dict[str, Any], prepared: Any) -> ProvisionResult: - """Preflight an existing source/model, then create only missing output state.""" +def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any) -> bool: + """Preflight an existing source/model and create only a missing output table.""" source_name = config["score_source_table"] - training_name = config["training_table"] target_name = config["prediction_table"] - control_name = config["score_admission_table"] - lifecycle = config.get("include_lifecycle", "no") - if lifecycle not in {"no", "yes"}: - raise ValueError("include_lifecycle must be 'yes' or 'no'.") - for name in (source_name, training_name, target_name, control_name, config["model_name"]): + for name in (source_name, target_name, config["model_name"]): if not _TABLE_NAME.fullmatch(name): - raise ValueError("Setup needs valid three-part Unity Catalog names.") - if lifecycle == "yes" and not config.get("alias_admission_table"): - raise ValueError("Lifecycle setup needs an alias admission table.") - if lifecycle == "yes" and not _TABLE_NAME.fullmatch(config["alias_admission_table"]): - raise ValueError("Lifecycle setup needs a valid alias admission table name.") + raise ValueError("Scoring needs valid three-part Unity Catalog names.") if source_name == target_name: raise ValueError("Prediction output must differ from the source table.") - for name in {source_name, training_name}: - if not spark.catalog.tableExists(name): - raise ValueError(f"Existing input source table is missing: {name}.") + if not spark.catalog.tableExists(source_name): + raise ValueError(f"Existing input source table is missing: {source_name}.") if not prepared.preflight.ready: raise ValueError("The pinned registered model failed Skyulf preflight.") source = spark.table(source_name) columns = _prediction_columns(config, prepared, source) - if ( - source.select(*config["row_keys"], *config["input_columns"]) - .limit(config["max_rows"] + 1) - .count() - > config["max_rows"] - ): - raise ValueError("Initial scoring source exceeds the configured max_rows budget.") detail = spark.sql(f"DESCRIBE DETAIL {source_name}").first() properties = detail["properties"] or {} if not any( @@ -223,33 +151,19 @@ def provision_local_tables(spark: Any, config: dict[str, Any], prepared: Any) -> ): raise ValueError("Scoring source must have Delta Change Data Feed enabled.") target_exists = spark.catalog.tableExists(target_name) - control_exists = spark.catalog.tableExists(control_name) - if control_exists and not target_exists: - raise ValueError("Admission table exists while prediction target is missing.") if target_exists: _check_existing_table(spark, target_name, columns) - if control_exists: - _check_existing_control(spark, control_name, table_identity(spark, target_name)) - alias_name = config.get("alias_admission_table") if lifecycle == "yes" else None - alias_exists = bool(alias_name and spark.catalog.tableExists(alias_name)) - if alias_exists: - _check_existing_control(spark, alias_name, alias_resource_id(config["model_name"])) if not target_exists: + if ( + source.select(*config["row_keys"], *config["input_columns"]) + .limit(config["max_rows"] + 1) + .count() + > config["max_rows"] + ): + raise ValueError("Initial scoring source exceeds the configured max_rows budget.") definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) spark.sql(f"CREATE TABLE {target_name} ({definition}) USING DELTA").collect() - if not control_exists: - _create_control(spark, control_name, table_identity(spark, target_name)) - if alias_name and not alias_exists: - _create_control(spark, alias_name, alias_resource_id(config["model_name"])) - return ProvisionResult( - source_name, - target_name, - not target_exists, - control_name, - not control_exists, - alias_name, - bool(alias_name and not alias_exists), - ) + return not target_exists def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: @@ -270,45 +184,6 @@ def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: ) -def _comparison(spark: Any, config: dict[str, Any]) -> tuple[Any, Any]: - """Evaluate two pinned registry versions on one pinned held-out frame.""" - spec = _training_spec(config) - frame = read_training_snapshot(spark, spec) - _, heldout, _ = split_labeled_snapshot(frame, spec) - if config["engine"] == "polars": - heldout = pl.from_pandas(heldout) - model_name = config["model_name"] - tracking_uri = config.get("tracking_uri", "databricks") - registry_uri = config.get("registry_uri", "databricks-uc") - candidate = resolve_model( - model_name, - version=config["candidate_version"], - tracking_uri=tracking_uri, - registry_uri=registry_uri, - ) - champion = resolve_model( - model_name, - version=config["champion_version"], - tracking_uri=tracking_uri, - registry_uri=registry_uri, - ) - report = compare_registered_local_models( - candidate, - champion, - heldout, - target_column=spec.target_column, - dataset_id=spec.dataset_id, - metric=config["metric"], - min_improvement=config["min_improvement"], - max_rows=spec.max_rows, - max_bytes=spec.max_bytes, - quality_threshold=config.get("quality_threshold"), - tracking_uri=tracking_uri, - registry_uri=registry_uri, - ) - return report, heldout - - def run_action( spark: Any, config: dict[str, Any], @@ -317,7 +192,7 @@ def run_action( experiment_name: str | None = None, artifact_path: str | Path | None = None, ) -> Any: - """Delegate each explicit job action to the corresponding Skyulf service.""" + """Delegate training or scoring to Skyulf's existing services.""" tracking_uri = config.get("tracking_uri", "databricks") registry_uri = config.get("registry_uri", "databricks-uc") if action == "train": @@ -339,41 +214,15 @@ def run_action( champion_version=config.get("champion_version"), quality_threshold=config.get("quality_threshold"), ) - if action in {"setup", "score"}: + if action == "score": prepared = prepare_local_workflow(_scoring_config(config)) - if action == "setup": - return provision_local_tables(spark, config, prepared) + provision_prediction_table(spark, config, prepared) return run_incremental_local_batch( spark, prepared, row_keys=tuple(config["row_keys"]), - admission=DeltaTableAdmission(spark, config["score_admission_table"]), + admission=SingleWriterAdmission(), ) - if action in {"compare", "stage", "promote"}: - if action != "compare" and config["alias_admission_table"] is None: - raise ValueError("Alias control is not configured; enable the lifecycle jobs first.") - report, heldout = _comparison(spark, config) - if action == "compare": - return report - if not report.eligible: - raise ValueError(f"Candidate is not eligible for {action}: {report.reason}.") - options = { - "target_column": config["target_column"], - "expected_champion_version": config["champion_version"], - "admission": DeltaAliasAdmission(spark, config["alias_admission_table"]), - "max_rows": config["max_rows"], - "max_bytes": config["max_bytes"], - "tracking_uri": tracking_uri, - "registry_uri": registry_uri, - } - if action == "stage": - return stage_challenger( - report, - heldout, - expected_challenger_version=config.get("expected_challenger_version"), - **options, - ) - return promote_candidate(report, heldout, **options) raise ValueError(f"Unknown workflow action: {action}.") diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 9d49d9ba0..3e1543430 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -2,6 +2,7 @@ import importlib.util import json +import re from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -31,12 +32,9 @@ def _config(): "training_version": 0, "score_source_table": "workspace.test.source", "prediction_table": "workspace.test.predictions", - "score_admission_table": "workspace.test.score_admission", - "alias_admission_table": "workspace.test.alias_admission", "model_name": "workspace.test.model", "model_version": "1", "champion_version": "1", - "candidate_version": "2", "row_keys": ["entity_id"], "input_columns": ["x"], "target_column": "target", @@ -59,7 +57,6 @@ def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, workflow = _workflow() train = Mock(return_value=SimpleNamespace(model_version="2")) monkeypatch.setattr(workflow, "train_local_candidate", train) - monkeypatch.setattr(workflow, "promote_candidate", Mock(side_effect=AssertionError("promoted"))) result = workflow.run_action( object(), _config(), @@ -79,47 +76,22 @@ def test_score_uses_incremental_service_without_period_or_source_version(monkeyp score = Mock(return_value=SimpleNamespace(noop=False, input_count=2)) monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) monkeypatch.setattr(workflow, "run_incremental_local_batch", score) - monkeypatch.setattr(workflow, "DeltaTableAdmission", Mock(return_value=object())) + monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) result = workflow.run_action(object(), _config(), "score") assert result.input_count == 2 assert score.call_args.kwargs["row_keys"] == ("entity_id",) assert "period_start" not in score.call_args.kwargs assert "source_version" not in score.call_args.kwargs assert prepare.call_args.args[0].engine == "polars" + assert isinstance(score.call_args.kwargs["admission"], workflow.SingleWriterAdmission) -def test_compare_is_read_only_and_stage_does_not_promote(monkeypatch): - """An eligible comparison must still need a separate staging and promotion job.""" +def test_lifecycle_actions_are_not_bundle_entry_points(): + """The minimal Bundle must not accidentally mutate registry aliases.""" workflow = _workflow() - report = SimpleNamespace(eligible=True, reason="eligible") - heldout = object() - monkeypatch.setattr(workflow, "_comparison", Mock(return_value=(report, heldout))) - stage = Mock(return_value=SimpleNamespace(kind="challenger")) - promote = Mock(side_effect=AssertionError("promoted without approval")) - monkeypatch.setattr(workflow, "stage_challenger", stage) - monkeypatch.setattr(workflow, "promote_candidate", promote) - monkeypatch.setattr(workflow, "DeltaAliasAdmission", Mock(return_value=object())) - assert workflow.run_action(object(), _config(), "compare") is report - promote.assert_not_called() - result = workflow.run_action(object(), _config(), "stage") - assert result.kind == "challenger" - assert stage.call_args.kwargs["expected_champion_version"] == "1" - promote.assert_not_called() - - -def test_ineligible_candidate_cannot_reach_alias_writer(monkeypatch): - """An inferior candidate cannot stage or promote through the Bundle entry point.""" - workflow = _workflow() - monkeypatch.setattr( - workflow, - "_comparison", - Mock(return_value=(SimpleNamespace(eligible=False, reason="inferior"), object())), - ) - promote = Mock() - monkeypatch.setattr(workflow, "promote_candidate", promote) - with pytest.raises(ValueError, match="not eligible"): - workflow.run_action(object(), _config(), "promote") - promote.assert_not_called() + for action in ("compare", "stage", "promote", "setup"): + with pytest.raises(ValueError, match="Unknown workflow action"): + workflow.run_action(object(), _config(), action) def test_target_binding_separates_test_and_prod_outputs(): @@ -131,8 +103,6 @@ def test_target_binding_separates_test_and_prod_outputs(): score_source_table="shared.raw.events", prediction_table="{catalog}.{output_schema}.predictions{resource_suffix}", model_name="{catalog}.{metadata_schema}.model{resource_suffix}", - score_admission_table="{catalog}.{metadata_schema}.score_control{resource_suffix}", - alias_admission_table="{catalog}.{metadata_schema}.alias_control{resource_suffix}", ) shared = { "input_schema": "refined", @@ -187,8 +157,6 @@ def test_target_binding_rejects_cross_environment_output(): workflow = _workflow() config = _config() config.update( - score_admission_table="prod_catalog.metadata.score_control", - alias_admission_table="prod_catalog.metadata.alias_control", model_name="prod_catalog.metadata.model", ) config["prediction_table"] = "test_catalog.mlresult.predictions" @@ -211,8 +179,6 @@ def test_target_binding_rejects_cross_environment_model(): config = _config() config.update( prediction_table="prod_catalog.mlresult.predictions", - score_admission_table="prod_catalog.metadata.score_control", - alias_admission_table="prod_catalog.metadata.alias_control", ) config["model_name"] = "test_catalog.metadata.model" with pytest.raises(ValueError, match="model_name"): @@ -236,7 +202,6 @@ def test_generated_config_keeps_company_output_in_each_target(): template.read_text(encoding="utf-8") .replace("{{.project_name}}", "customer_model") .replace("{{.engine}}", "pandas") - .replace("{{.include_lifecycle}}", "no") ) outputs = {} for target, catalog, suffix in ( @@ -272,7 +237,6 @@ def test_minimal_generated_config_uses_one_existing_source(): template.read_text(encoding="utf-8") .replace("{{.project_name}}", "customer_model") .replace("{{.engine}}", "pandas") - .replace("{{.include_lifecycle}}", "no") ) bound = workflow.resolve_target_config( config, @@ -287,18 +251,34 @@ def test_minimal_generated_config_uses_one_existing_source(): assert bound["training_table"] == bound["score_source_table"] -def test_setup_rejects_missing_source_without_creating_tables(): +def test_score_provision_rejects_missing_source_without_creating_tables(): """A wrong source reference must not create partial prediction resources.""" workflow = _workflow() spark = Mock() spark.catalog.tableExists.return_value = False with pytest.raises(ValueError, match="source"): - workflow.provision_local_tables(spark, _config(), object()) + workflow.provision_prediction_table(spark, _config(), object()) spark.sql.assert_not_called() -def test_setup_creates_only_prediction_and_score_control(monkeypatch): - """First setup must leave inputs alone and create no alias table by default.""" +def test_score_does_not_require_labeled_training_table(monkeypatch): + """A retired training snapshot must not prevent scoring a live source.""" + workflow = _workflow() + config = _config() + config["training_table"] = "workspace.test.retired_training" + spark = Mock() + spark.catalog.tableExists.side_effect = lambda name: name != config["training_table"] + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + monkeypatch.setattr(workflow, "_prediction_columns", Mock(return_value=())) + monkeypatch.setattr(workflow, "_check_existing_table", Mock()) + prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True)) + assert workflow.provision_prediction_table(spark, config, prepared) is False + + +def test_score_replay_validates_existing_output_without_recounting_source(monkeypatch): + """A later score must accept a growing source without recreating its output.""" workflow = _workflow() config = _config() source = Mock() @@ -306,20 +286,14 @@ def test_setup_creates_only_prediction_and_score_control(monkeypatch): source.schema = { "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) } - source.select.return_value.limit.return_value.count.return_value = 2 spark = Mock() - spark.catalog.tableExists.side_effect = lambda name: ( - name - in { - config["training_table"], - config["score_source_table"], - } - ) + spark.catalog.tableExists.return_value = True spark.table.return_value = source spark.sql.return_value.first.return_value = { "properties": {"delta.enableChangeDataFeed": "true"} } - monkeypatch.setattr(workflow, "table_identity", Mock(return_value="prediction-id")) + check_target = Mock() + monkeypatch.setattr(workflow, "_check_existing_table", check_target) prepared = SimpleNamespace( artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), preflight=SimpleNamespace( @@ -327,18 +301,36 @@ def test_setup_creates_only_prediction_and_score_control(monkeypatch): output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), ), ) - result = workflow.provision_local_tables(spark, config, prepared) - statements = [call.args[0] for call in spark.sql.call_args_list] - creates = [statement for statement in statements if statement.startswith("CREATE TABLE")] - assert result.prediction_created and result.score_admission_created - assert result.alias_admission_table is None - assert len(creates) == 2 - assert creates[0].startswith(f"CREATE TABLE {config['prediction_table']} (") - assert creates[1].startswith(f"CREATE TABLE {config['score_admission_table']} USING DELTA") + result = workflow.provision_prediction_table(spark, config, prepared) + check_target.assert_called_once() + source.select.assert_not_called() + assert result is False + assert all(not call.args[0].startswith("CREATE TABLE") for call in spark.sql.call_args_list) + + +def test_first_score_provisions_prediction_before_incremental_write(monkeypatch): + """The scheduled score job must handle first-run setup without another job.""" + workflow = _workflow() + events = [] + prepared = object() + monkeypatch.setattr(workflow, "prepare_local_workflow", Mock(return_value=prepared)) + monkeypatch.setattr( + workflow, + "provision_prediction_table", + Mock(side_effect=lambda spark, config, model: events.append("provision")), + raising=False, + ) + monkeypatch.setattr( + workflow, + "run_incremental_local_batch", + Mock(side_effect=lambda *args, **kwargs: events.append("score")), + ) + workflow.run_action(object(), _config(), "score") + assert events == ["provision", "score"] -def test_setup_replay_validates_existing_tables_without_creating_anything(monkeypatch): - """Rerunning setup must preserve the existing prediction and control tables.""" +def test_prediction_provision_creates_no_control_table(monkeypatch): + """First scoring must create only the output table, with no lock table.""" workflow = _workflow() config = _config() source = Mock() @@ -348,16 +340,17 @@ def test_setup_replay_validates_existing_tables_without_creating_anything(monkey } source.select.return_value.limit.return_value.count.return_value = 2 spark = Mock() - spark.catalog.tableExists.return_value = True + spark.catalog.tableExists.side_effect = lambda name: ( + name + in { + config["training_table"], + config["score_source_table"], + } + ) spark.table.return_value = source spark.sql.return_value.first.return_value = { "properties": {"delta.enableChangeDataFeed": "true"} } - monkeypatch.setattr(workflow, "table_identity", Mock(return_value="prediction-id")) - check_target = Mock() - check_control = Mock() - monkeypatch.setattr(workflow, "_check_existing_table", check_target) - monkeypatch.setattr(workflow, "_check_existing_control", check_control) prepared = SimpleNamespace( artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), preflight=SimpleNamespace( @@ -365,8 +358,32 @@ def test_setup_replay_validates_existing_tables_without_creating_anything(monkey output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), ), ) - result = workflow.provision_local_tables(spark, config, prepared) - check_target.assert_called_once() - check_control.assert_called_once_with(spark, config["score_admission_table"], "prediction-id") - assert not result.prediction_created and not result.score_admission_created - assert all(not call.args[0].startswith("CREATE TABLE") for call in spark.sql.call_args_list) + created = workflow.provision_prediction_table(spark, config, prepared) + statements = [call.args[0] for call in spark.sql.call_args_list] + assert created is True + assert len([statement for statement in statements if statement.startswith("CREATE TABLE")]) == 1 + assert all("admission" not in statement for statement in statements) + + +def test_generated_config_has_no_admission_or_alias_state(): + """The starting Bundle must not ask users to provision coordination tables.""" + template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" + config = json.loads( + template.read_text(encoding="utf-8") + .replace("{{.project_name}}", "customer_model") + .replace("{{.engine}}", "pandas") + .replace("{{.include_lifecycle}}", "no") + ) + assert "score_admission_table" not in config + assert "alias_admission_table" not in config + assert "include_lifecycle" not in config + + +def test_generated_bundle_has_only_train_and_serialized_score_jobs(): + """A new project must not silently bring back setup or control jobs.""" + resource = WORKFLOW.parents[1] / "resources/workflow.jobs.yml.tmpl" + template = resource.read_text(encoding="utf-8") + assert re.findall(r"^ ([a-z_]+):$", template, flags=re.MULTILINE) == ["train", "score"] + assert re.search( + r"^ score:\n name:.*\n max_concurrent_runs: 1$", template, re.MULTILINE + ) From 2251769778deb606e215f9a32eee9e5d5357155a Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 18:38:34 +0300 Subject: [PATCH 49/85] refactor: move Databricks bundle template into core Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 3 ++- docs/user_guide/databricks_bundle.md | 4 ++-- .../03-mlflow-batch-delivery-plan.md | 2 +- .../spark_and_mlflow/05-sm20-bundle-plan.md | 12 ++++++------ .../21-sm20a-local-bundle-validation-report.md | 4 ++-- .../22-sm20p-production-bundle-plan.md | 2 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 2 +- skyulf-core/README.md | 14 ++++++++++++++ .../databricks/databricks_template_schema.json | 0 .../databricks/examples/policy-init.example.json | 0 .../examples/serverless-init.example.json | 0 .../template/{{.project_name}}/README.md.tmpl | 2 +- .../{{.project_name}}/config/workflow.json.tmpl | 0 .../template/{{.project_name}}/databricks.yml.tmpl | 0 .../resources/workflow.jobs.yml.tmpl | 0 .../template/{{.project_name}}/src/workflow.py | 0 tests/integration/test_sm20a_bundle_template.py | 2 +- 17 files changed, 31 insertions(+), 16 deletions(-) rename {templates => skyulf-core/templates}/databricks/databricks_template_schema.json (100%) rename {templates => skyulf-core/templates}/databricks/examples/policy-init.example.json (100%) rename {templates => skyulf-core/templates}/databricks/examples/serverless-init.example.json (100%) rename {templates => skyulf-core/templates}/databricks/template/{{.project_name}}/README.md.tmpl (97%) rename {templates => skyulf-core/templates}/databricks/template/{{.project_name}}/config/workflow.json.tmpl (100%) rename {templates => skyulf-core/templates}/databricks/template/{{.project_name}}/databricks.yml.tmpl (100%) rename {templates => skyulf-core/templates}/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl (100%) rename {templates => skyulf-core/templates}/databricks/template/{{.project_name}}/src/workflow.py (100%) diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 9cac474fb..55a723ec6 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -12,7 +12,8 @@ execution, MLflow registry and Databricks delivery remain under development. - The local-engine Bundle template exposes editable `dev/test/syst/prod` targets with separate host/catalog bindings and a serverless or policy-backed - compute choice. Its default now deploys only `train` and `score`; the first + compute choice. Its source lives in `skyulf-core/templates/databricks`. + Its default now deploys only `train` and `score`; the first score validates the source and pinned model and creates only its prediction table. It uses explicit single-writer admission with serialized score runs, while Core retains shared admission for multi-writer deployments. The diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index b901954e1..bf2ef23cc 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -8,12 +8,12 @@ feature engineering and model prediction are not distributed Spark work. Initialize a project from a Skyulf checkout: ```powershell -databricks bundle init templates/databricks --output-dir ./generated +databricks bundle init skyulf-core/templates/databricks --output-dir ./generated ``` The short path asks for project name, engine, serverless or policy-backed job compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable -noninteractive examples are in `templates/databricks/examples/`. The generated +noninteractive examples are in `skyulf-core/templates/databricks/examples/`. The generated project has its own `databricks.yml`; Skyulf's root has no Bundle config. `dev` uses the selected CLI profile's workspace host. `test`, `syst` and diff --git a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md index d5c0b949a..5f91e9d3c 100644 --- a/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md +++ b/initiatives/spark_and_mlflow/03-mlflow-batch-delivery-plan.md @@ -352,7 +352,7 @@ ve `npm run build` kanıtı kayıtlı. SM-20b needs selected validated Spark adapters; SM-19 only if endpoints are selected. See [the dedicated SM-20 plan](05-sm20-bundle-plan.md) for generated resources and the two-month UC source/output-table rehearsal. -**Planned files:** `templates/databricks/` and +**Planned files:** `skyulf-core/templates/databricks/` and `tests/templates/test_databricks_template.py`; template dosyaları `databricks.yml`, `resources/batch_job.yml`, `README.md`, `src/run_batch.py`. diff --git a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md index 1d3d72d6b..c42cbc331 100644 --- a/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md +++ b/initiatives/spark_and_mlflow/05-sm20-bundle-plan.md @@ -79,12 +79,12 @@ The SQL Connector is an alternative, not a required part of the first Bundle. The delivered custom template generates a project with these responsibilities: ```text -templates/databricks/databricks_template_schema.json -templates/databricks/template/{{.project_name}}/databricks.yml.tmpl -templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl -templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml -templates/databricks/template/{{.project_name}}/src/workflow.py -templates/databricks/template/{{.project_name}}/README.md.tmpl +skyulf-core/templates/databricks/databricks_template_schema.json +skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py +skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl ``` The generated Python entry point calls Skyulf services; it does not copy FE, model, diff --git a/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md b/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md index 5cc8f8c95..a349fca80 100644 --- a/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md +++ b/initiatives/spark_and_mlflow/21-sm20a-local-bundle-validation-report.md @@ -7,7 +7,7 @@ profile. Target release remains 0.9.0. ## Delivered contract -`templates/databricks` asks for project name, local engine and existing UC +`skyulf-core/templates/databricks` asks for project name, local engine and existing UC catalog/schema. It emits its own `databricks.yml`, editable workflow JSON, one thin Skyulf entry point and five separate serverless jobs: `train`, `compare`, `stage`, `promote` and `score`. Each job installs the matching @@ -26,7 +26,7 @@ admission rows as described in the generated README. ## Local and template gates -- `databricks bundle init templates/databricks --config-file ... --output-dir ...` +- `databricks bundle init skyulf-core/templates/databricks --config-file ... --output-dir ...` rendered the `skyulf_sm20a_r1` project with `engine=polars`. - `databricks bundle validate --strict -t dev --profile skyulf` passed after generation and after each test configuration change. diff --git a/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md b/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md index 7667f00e7..e9dd6bbf3 100644 --- a/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md +++ b/initiatives/spark_and_mlflow/22-sm20p-production-bundle-plan.md @@ -75,7 +75,7 @@ and promote are deliberate review actions. ### P1. Target-specific binding and generation -**Files:** `templates/databricks/databricks_template_schema.json`, generated +**Files:** `skyulf-core/templates/databricks/databricks_template_schema.json`, generated `databricks.yml`, `config/workflow.json`, `resources/workflow.jobs.yml`, `src/workflow.py`; extend `tests/integration/test_sm20a_bundle_template.py`. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 21b0b1a3b..d97b4bc48 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -173,7 +173,7 @@ decision must not hide missing support. SM-19 streaming remains optional and par Inspected branch `090` at the SM-28a baseline and added the custom template, generated-workflow tests, Databricks Bundle guide and isolated rehearsal example. -`databricks bundle init templates/databricks --config-file ... --output-dir ...`, +`databricks bundle init skyulf-core/templates/databricks --config-file ... --output-dir ...`, `databricks bundle validate --strict -t dev --profile skyulf`, `databricks bundle deploy -t dev --profile skyulf` and Bundle `run` commands for train/compare/stage/promote/score all succeeded in the test workspace. The diff --git a/skyulf-core/README.md b/skyulf-core/README.md index 3b2eeb8a9..768dd9f95 100644 --- a/skyulf-core/README.md +++ b/skyulf-core/README.md @@ -71,6 +71,20 @@ pip install skyulf-core[mlflow] `all` intentionally excludes the native geospatial stack; add `[geo]` only when you need geospatial nodes. +## Databricks Bundle template + +The source checkout includes a [local-engine Databricks Bundle template](templates/databricks/) +for bounded pandas or Polars training and scoring with Skyulf Core. From the +repository root, initialize an editable project with: + +```powershell +databricks bundle init skyulf-core/templates/databricks --output-dir ./generated +``` + +The generated project has `train` and `score` jobs. The first score creates +its prediction table; see the [Bundle guide](../docs/user_guide/databricks_bundle.md) +for configuration and the single-writer requirement. + ## Compute engines (pandas / Polars) Skyulf nodes run on a pandas or Polars engine, chosen per call: diff --git a/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json similarity index 100% rename from templates/databricks/databricks_template_schema.json rename to skyulf-core/templates/databricks/databricks_template_schema.json diff --git a/templates/databricks/examples/policy-init.example.json b/skyulf-core/templates/databricks/examples/policy-init.example.json similarity index 100% rename from templates/databricks/examples/policy-init.example.json rename to skyulf-core/templates/databricks/examples/policy-init.example.json diff --git a/templates/databricks/examples/serverless-init.example.json b/skyulf-core/templates/databricks/examples/serverless-init.example.json similarity index 100% rename from templates/databricks/examples/serverless-init.example.json rename to skyulf-core/templates/databricks/examples/serverless-init.example.json diff --git a/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl similarity index 97% rename from templates/databricks/template/{{.project_name}}/README.md.tmpl rename to skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index 1e292cd83..9d2f3bd3f 100644 --- a/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -59,7 +59,7 @@ need to publish to one target. {{if eq .compute_mode "policy_cluster"}} The selected policy-backed jobs look up the policy name supplied during initialization. Confirm its runtime, node type and cost tag in each workspace. -An example init config lives in `templates/databricks/examples/policy-init.example.json` +An example init config lives in `skyulf-core/templates/databricks/examples/policy-init.example.json` in the Skyulf checkout. Its placeholders must be reviewed before use. {{else}} The generated jobs use Databricks serverless Python environment 4. Policy diff --git a/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl similarity index 100% rename from templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl rename to skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl diff --git a/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl similarity index 100% rename from templates/databricks/template/{{.project_name}}/databricks.yml.tmpl rename to skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl diff --git a/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl similarity index 100% rename from templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl rename to skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl diff --git a/templates/databricks/template/{{.project_name}}/src/workflow.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py similarity index 100% rename from templates/databricks/template/{{.project_name}}/src/workflow.py rename to skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 3e1543430..74532e779 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -11,7 +11,7 @@ WORKFLOW = ( Path(__file__).resolve().parents[2] - / "templates/databricks/template/{{.project_name}}/src/workflow.py" + / "skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py" ) From 312205fc70649b8d89b97ffee35ac295ef91b293 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 18:54:41 +0300 Subject: [PATCH 50/85] feat: select prediction row key during bundle init Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 +-- docs/user_guide/databricks_bundle.md | 22 ++++++++++-- .../databricks_template_schema.json | 23 ++++++++----- .../examples/policy-init.example.json | 1 + .../examples/serverless-init.example.json | 1 + .../template/{{.project_name}}/README.md.tmpl | 8 +++++ .../config/workflow.json.tmpl | 2 +- .../integration/test_sm20a_bundle_template.py | 34 ++++++++++++++++++- 8 files changed, 82 insertions(+), 14 deletions(-) diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 55a723ec6..8a7dec271 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -15,8 +15,9 @@ execution, MLflow registry and Databricks delivery remain under development. compute choice. Its source lives in `skyulf-core/templates/databricks`. Its default now deploys only `train` and `score`; the first score validates the source and pinned model and creates only its prediction - table. It uses explicit single-writer admission with serialized score runs, - while Core retains shared admission for multi-writer deployments. The + table. Initialization can select an existing source row key for the + prediction table. It uses explicit single-writer admission with serialized + score runs, while Core retains shared admission for multi-writer deployments. The earlier three-job personal rehearsal trained a Polars model, wrote 600 initial and 50 later predictions, and replayed without a new commit. - Prediction Delta targets use `run_id`, `model_name` and `model_version` diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index bf2ef23cc..ae104a96d 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -11,8 +11,9 @@ Initialize a project from a Skyulf checkout: databricks bundle init skyulf-core/templates/databricks --output-dir ./generated ``` -The short path asks for project name, engine, serverless or policy-backed job -compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable +The short path asks for project name, engine, one existing source row-key +column, serverless or policy-backed job compute and the existing `dev` +catalog/schema. Serverless is the default. Reviewable noninteractive examples are in `skyulf-core/templates/databricks/examples/`. The generated project has its own `databricks.yml`; Skyulf's root has no Bundle config. @@ -53,6 +54,23 @@ data and new scoring data have different lifecycles. If they stay together, the first `score` run predicts all existing rows, including historical labeled rows; review whether that is intended for your use case. +The initialization question `row_key` defaults to `entity_id`, but you can +choose an existing `customer_id` column. It becomes `row_keys` in the generated +configuration, and the same column appears in the prediction table. It must +be non-null, `STRING` or `BIGINT`, and unique across the initial data and all +later inserts. For multiple predictions per customer, edit the generated +configuration to a composite key such as +`"row_keys": ["customer_id", "observation_id"]` before deployment. The Bundle +does not create an ID in the source. Keep keys out of `input_columns`. With +`customer_id` in the output, a query +can find a customer's predictions: + +```sql +SELECT customer_id, prediction, model_version +FROM catalog.schema.predictions +WHERE customer_id = 'C123'; +``` + ## First run Build and place the matching Skyulf wheel in the generated project's `dist/`, diff --git a/skyulf-core/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json index 8ed776695..dea8d6ddc 100644 --- a/skyulf-core/templates/databricks/databricks_template_schema.json +++ b/skyulf-core/templates/databricks/databricks_template_schema.json @@ -15,50 +15,57 @@ "description": "Local fit and prediction engine", "enum": ["pandas", "polars"] }, - "compute_mode": { + "row_key": { "order": 3, "type": "string", + "default": "entity_id", + "description": "Existing source column identifying one prediction row (also copied to output)", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "compute_mode": { + "order": 4, + "type": "string", "default": "serverless", "description": "Job compute mode for this project", "enum": ["serverless", "policy_cluster"] }, "catalog": { - "order": 4, + "order": 5, "type": "string", "default": "workspace", "description": "Existing dev Unity Catalog catalog", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, "schema": { - "order": 5, + "order": 6, "type": "string", "default": "default", "description": "Existing dev Unity Catalog schema", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, "cluster_policy_name": { - "order": 6, + "order": 7, "type": "string", "default": "REPLACE_WITH_APPROVED_POLICY", "description": "Approved job-cluster policy name", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "spark_version": { - "order": 7, + "order": 8, "type": "string", "default": "17.3.x-cpu-ml-scala2.13", "description": "Approved Databricks ML Runtime for the job cluster", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "node_type_id": { - "order": 8, + "order": 9, "type": "string", "default": "REPLACE_WITH_NODE_TYPE", "description": "Approved job-cluster node type", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "cost_tag_key": { - "order": 9, + "order": 10, "type": "string", "default": "CostCenter", "description": "Approved cluster cost tag key", @@ -66,7 +73,7 @@ "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "cost_tag_value": { - "order": 10, + "order": 11, "type": "string", "default": "REPLACE_WITH_COST_TAG", "description": "Approved cluster cost tag value", diff --git a/skyulf-core/templates/databricks/examples/policy-init.example.json b/skyulf-core/templates/databricks/examples/policy-init.example.json index 94a9fd8a0..84ae8b6ac 100644 --- a/skyulf-core/templates/databricks/examples/policy-init.example.json +++ b/skyulf-core/templates/databricks/examples/policy-init.example.json @@ -1,6 +1,7 @@ { "project_name": "my_model", "engine": "pandas", + "row_key": "entity_id", "compute_mode": "policy_cluster", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", diff --git a/skyulf-core/templates/databricks/examples/serverless-init.example.json b/skyulf-core/templates/databricks/examples/serverless-init.example.json index aa26e4f83..14bff74fb 100644 --- a/skyulf-core/templates/databricks/examples/serverless-init.example.json +++ b/skyulf-core/templates/databricks/examples/serverless-init.example.json @@ -1,6 +1,7 @@ { "project_name": "my_model", "engine": "pandas", + "row_key": "customer_id", "compute_mode": "serverless", "catalog": "workspace", "schema": "my_dev_schema" diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index 9d2f3bd3f..b3cdc75c3 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -26,6 +26,14 @@ You may give them different UC names when the labeled training data and new inference data have different lifecycles. Neither is created by this Bundle. `prediction_table` is the single model output table. `model_name` is a registered UC model, not a table. The Bundle creates no admission table. +The `row_key` selected during initialization names an existing source column; +`score` copies it into the prediction table for SQL lookups. It must be +non-null, `STRING` or `BIGINT`, and unique across all scored rows, including +later inserts. If a customer can have multiple prediction rows, edit +`row_keys` in `config/workflow.json` to a jointly unique list such as +`["customer_id", "observation_id"]` before deployment. The initialization +prompt chooses one column; it never creates an ID in the source. Keep key +columns out of `input_columns`; they identify predictions, not model features. The score job has `max_concurrent_runs: 1`; grant write access to the prediction table only to this job's identity. Other jobs must not write it. Skyulf Core's shared-admission option remains available when multiple jobs diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index 18e88e765..43537b790 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -7,7 +7,7 @@ "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", "model_version": "1", "champion_version": null, - "row_keys": ["entity_id"], + "row_keys": ["{{.row_key}}"], "input_columns": ["feature_value"], "target_column": "target", "event_column": "event_time", diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 74532e779..00e665ff1 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -202,6 +202,7 @@ def test_generated_config_keeps_company_output_in_each_target(): template.read_text(encoding="utf-8") .replace("{{.project_name}}", "customer_model") .replace("{{.engine}}", "pandas") + .replace("{{.row_key}}", "entity_id") ) outputs = {} for target, catalog, suffix in ( @@ -237,6 +238,7 @@ def test_minimal_generated_config_uses_one_existing_source(): template.read_text(encoding="utf-8") .replace("{{.project_name}}", "customer_model") .replace("{{.engine}}", "pandas") + .replace("{{.row_key}}", "entity_id") ) bound = workflow.resolve_target_config( config, @@ -372,13 +374,43 @@ def test_generated_config_has_no_admission_or_alias_state(): template.read_text(encoding="utf-8") .replace("{{.project_name}}", "customer_model") .replace("{{.engine}}", "pandas") - .replace("{{.include_lifecycle}}", "no") + .replace("{{.row_key}}", "entity_id") ) assert "score_admission_table" not in config assert "alias_admission_table" not in config assert "include_lifecycle" not in config +def test_init_row_key_becomes_prediction_table_key(): + """A chosen source identity must be carried into the generated output schema.""" + root = WORKFLOW.parents[3] + schema = json.loads((root / "databricks_template_schema.json").read_text(encoding="utf-8")) + assert schema["properties"]["row_key"]["default"] == "entity_id" + + template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" + config = json.loads( + template.read_text(encoding="utf-8") + .replace("{{.project_name}}", "customer_model") + .replace("{{.engine}}", "pandas") + .replace("{{.row_key}}", "customer_id") + ) + source = SimpleNamespace( + columns=["customer_id", "feature_value"], + schema={ + "customer_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) + }, + ) + prepared = SimpleNamespace( + artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("feature_value",))), + preflight=SimpleNamespace( + output_schema=(SimpleNamespace(name="prediction", dtype="float64"),) + ), + ) + columns = _workflow()._prediction_columns(config, prepared, source) + assert config["row_keys"] == ["customer_id"] + assert columns[0] == ("customer_id", "string", "STRING") + + def test_generated_bundle_has_only_train_and_serialized_score_jobs(): """A new project must not silently bring back setup or control jobs.""" resource = WORKFLOW.parents[1] / "resources/workflow.jobs.yml.tmpl" From 277e98e87ee1dff4986c095e05ef1b61e8cfc32e Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 19:12:37 +0300 Subject: [PATCH 51/85] feat: add optional monthly local retraining schedule Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 +- docs/user_guide/databricks_bundle.md | 29 +++++-- .../27-sm28b-monthly-retraining-plan.md | 43 ++++++++++ ...8b-monthly-retraining-validation-report.md | 39 +++++++++ initiatives/spark_and_mlflow/HANDOFF.md | 13 +++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 10 ++- .../databricks_template_schema.json | 7 ++ .../examples/policy-init.example.json | 1 + .../examples/serverless-init.example.json | 1 + .../template/{{.project_name}}/README.md.tmpl | 22 ++++- .../config/workflow.json.tmpl | 1 + .../resources/workflow.jobs.yml.tmpl | 9 +- .../{{.project_name}}/src/workflow.py | 78 +++++++++++++++-- .../integration/test_sm20a_bundle_template.py | 84 +++++++++++++++++++ 14 files changed, 319 insertions(+), 23 deletions(-) create mode 100644 initiatives/spark_and_mlflow/27-sm28b-monthly-retraining-plan.md create mode 100644 initiatives/spark_and_mlflow/28-sm28b-monthly-retraining-validation-report.md diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 8a7dec271..0a8286e15 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -20,6 +20,9 @@ execution, MLflow registry and Databricks delivery remain under development. score runs, while Core retains shared admission for multi-writer deployments. The earlier three-job personal rehearsal trained a Polars model, wrote 600 initial and 50 later predictions, and replayed without a new commit. + An optional `monthly_paused` mode adds a paused monthly schedule to the same + train job, pins a UTC label window and Delta version, and compares each new + candidate with the current champion without automatic promotion or scoring. - Prediction Delta targets use `run_id`, `model_name` and `model_version` metadata columns. Existing test targets with the former `__skyulf_*` schema require a new target; the writer does not migrate tables. @@ -45,7 +48,7 @@ execution, MLflow registry and Databricks delivery remain under development. train/compare/stage/promote and 2+2-row incremental scoring; the later clean generic rehearsal used one source table and proved 600+50-row scoring with a no-op replay. Existing predictions retained their pinned model version after - alias promotion. Scheduling, Spark FE/model execution and endpoints remain separate. + alias promotion. Spark FE/model execution and endpoints remain separate. - Explicit MLflow champion promotion and rollback revalidate a pinned local model comparison, acquire shared admission, check the expected alias version and record durable transition receipts. Local registry tests and an isolated diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index ae104a96d..274131d6f 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -12,7 +12,7 @@ databricks bundle init skyulf-core/templates/databricks --output-dir ./generated ``` The short path asks for project name, engine, one existing source row-key -column, serverless or policy-backed job compute and the existing `dev` +column, optional retraining mode, serverless or policy-backed job compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable noninteractive examples are in `skyulf-core/templates/databricks/examples/`. The generated project has its own `databricks.yml`; Skyulf's root has no Bundle config. @@ -34,7 +34,10 @@ initialization. Serverless compute needs none of those fields. | `train` | Fit one candidate and log held-out metrics | One registered model/version | | `score` | Verify the source and pinned model, create output if absent, then score initial and later CDF inserts | One prediction table, only if absent; rows in that table | -No schedule, endpoint or Unity Catalog table is created by deployment alone. +The default project has no schedule. Choosing `monthly_paused` at initialization +adds a paused monthly schedule to the existing `train` job, without adding a +third job or running it at deployment. No endpoint or Unity Catalog table is +created by deployment alone. The starting Bundle has no alias lifecycle job. Skyulf Core's registry comparison and promotion services remain available for a separately designed champion/challenger workflow. @@ -100,14 +103,24 @@ pinned to its configured model version; changing aliases does not rewrite old predictions. `max_concurrent_runs: 1` serializes the generated score job, but does not coordinate other jobs. Grant prediction-table writes only to this job's identity. For multiple publishers, use Skyulf Core's shared admission -provider. Full-history rescore, schedules, online endpoints and Spark-native -FE/model execution are separate work. +provider. Full-history rescore, online endpoints and Spark-native FE/model +execution are separate work. + +The optional monthly `train` schedule runs at 03:00 UTC on day three and starts +paused. After configuring real labeled data and verifying a manual run, unpause +it deliberately. Each run pins the source's latest Delta version and uses the +first day of the current UTC month as the label cutoff. The preceding month is +holdout; `monthly_lookback_months` (default four) controls the full window. +Only labels available by the cutoff are eligible. `@champion` is resolved to a +concrete version for comparison if present; the new candidate is never +promoted or substituted into `score` automatically. The source version is +pinned at run start, so `label_at` must faithfully record availability. The older SM-20a personal serverless rehearsal passed, but its jobs and test schemas were removed at the user's request. The subsequent clean generic `dev` rehearsal trained a Polars model from 600 real taxi rows, wrote 600 initial and 50 later predictions to one table, and replayed without another -commit. The personal test resources remain available for inspection. The -That rehearsal used the earlier three-job template; the two-job design needs -its own live validation. The `test`, `syst` and `prod` placeholders have not -been deployed in a company workspace. +commit. The later two-job design passed a separate personal serverless +rehearsal: 650 existing source rows, one later insert, and a no-op replay +left one prediction table with 651 rows. The `test`, `syst` and `prod` +placeholders have not been deployed in a company workspace. diff --git a/initiatives/spark_and_mlflow/27-sm28b-monthly-retraining-plan.md b/initiatives/spark_and_mlflow/27-sm28b-monthly-retraining-plan.md new file mode 100644 index 000000000..9adcb5d52 --- /dev/null +++ b/initiatives/spark_and_mlflow/27-sm28b-monthly-retraining-plan.md @@ -0,0 +1,43 @@ +# SM-28b: Optional monthly local retraining + +## Goal and boundary + +Keep the generated Bundle at two jobs (`train`, `score`) and one prediction +table. A new project has no active schedule. Users may opt into a **paused** +monthly schedule on the existing `train` job and unpause it after supplying a +real labeled source, pipeline, experiment and permissions. The schedule never +runs `score`, moves a registry alias, or changes its pinned `model_version`. + +## Monthly training run + +1. At run start, normalize the current instant to UTC. The cutoff is midnight + on the first day of that month. The holdout covers the preceding calendar + month; fit starts a configurable number of calendar months before cutoff. + A run on any day of the month therefore has the same temporal boundaries. +2. Validate the source as Delta and read its latest concrete version once. + Pass that version into the existing bounded `LocalTrainingSpec`; the run's + `dataset_id` records the exact version and window. Filter rows by event time + and label availability at cutoff. The version is pinned at run start, not + time-traveled to the cutoff: honest `label_at` values are required. +3. Resolve `@champion` once, if present, and pass its concrete version to the + existing `train_local_candidate` service. A missing alias means first-model + training; any other registry failure aborts. The service records metrics and + a comparison, then registers a candidate without moving aliases. +4. Activation remains explicit: review the comparison, manage aliases through + the existing lifecycle API, update `model_version` in the Bundle config and + redeploy before `score` uses the new version. Existing predictions remain. + +## Safety and acceptance + +- The opt-in train schedule is paused and uses one monthly Quartz time in UTC; + `max_concurrent_runs: 1` also applies to train. Initial Bundle output still + contains exactly two jobs and creates no Unity Catalog objects at deploy. +- Tests cover month/year rollover, timezone normalization, invalid lookback, + Delta snapshot pinning, missing champion, and no implicit promotion/scoring. +- Validate a generated serverless project with Databricks CLI. Live execution + needs a real labeled source with enough rows in both temporal partitions; + a static historical test table cannot establish a current-month success. +- Retrying a month may register another candidate if the source version or + configuration changed. That is visible in MLflow and does not activate it. + Shared-target scoring writers still need a separate admission decision; + this task introduces no second score writer. diff --git a/initiatives/spark_and_mlflow/28-sm28b-monthly-retraining-validation-report.md b/initiatives/spark_and_mlflow/28-sm28b-monthly-retraining-validation-report.md new file mode 100644 index 000000000..932135d02 --- /dev/null +++ b/initiatives/spark_and_mlflow/28-sm28b-monthly-retraining-validation-report.md @@ -0,0 +1,39 @@ +# SM-28b: Optional monthly retraining validation + +Date: 2026-09-24. Branch: `090`. + +The generated local-engine Bundle still has exactly two jobs. The default +`manual` mode has no schedule; `monthly_paused` adds a paused UTC monthly +schedule to the same `train` job, with `max_concurrent_runs: 1`. The `score` +job and its pinned model version do not change. No admission table or second +writer is introduced. + +The monthly action calculates a calendar-month fit/holdout window, captures +the source's current concrete Delta version, and delegates to the existing +bounded label-aware Skyulf candidate-training service. It resolves a current +`@champion` to one concrete version for comparison, permits an absent alias +for first-model training, and propagates other registry errors. It does not +stage, promote, or score the new candidate. The source snapshot is pinned at +run start; the label cutoff is the start of the current UTC month. The +`label_at` column must faithfully record availability by that cutoff. + +Verification: + +- `pytest tests/integration/test_sm20a_bundle_template.py -q`: 21 passed. + Cases cover year rollover, explicit source version, invalid lookback, + missing version, champion resolution and scorer isolation. +- The template suite plus the underlying label-aware retraining suite passed + together: 31 tests. +- `ruff check` on the changed workflow and integration tests: clean. +- Databricks CLI `bundle init` generated both manual and monthly projects. + Inspection found only `train` and `score`, with `train_monthly` and + `pause_status: PAUSED` only in the monthly project. +- Both generated serverless projects passed `databricks bundle validate + --strict -t dev --profile skyulf` after a matching 0.9.0 wheel was built. + Validation was read-only; no Bundle was deployed or job run. + +A current-month live training run was not attempted: the existing personal +test source is historical and cannot provide the required recent labeled +fit and holdout rows. The optional schedule remains paused until a user +configures a real source and deliberately unpauses it. Re-running a month +can register another candidate; alias activation remains explicit. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 99d50ab3f..e1bc85a9b 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,5 +1,18 @@ # Session handoff - 2026-09-24 +## Current state after SM-28b + +The latest first Bundle has exactly two jobs (`train`, `score`), and its first +score creates only the prediction table; see +[SM-20S](26-sm20s-two-job-live-validation-report.md). SM-28b adds an optional +paused monthly schedule to that same `train` job. Manual and monthly generated +projects passed strict CLI validation; no monthly live job was deployed or +run. See [SM-28b validation](28-sm28b-monthly-retraining-validation-report.md). +The next open item is SM-27, a bounded full-history local rescore with a new +prediction generation and explicit activation. Company workspace targets +remain unconfigured and unverified. The remainder of this file is historical +context from earlier Bundle stages. + SM-00 through SM-16, SM-15L/15I and SM-24a/25/26 are complete for their documented scopes. The selected Databricks serverless local monthly UC publication passed with 80 pandas January and 80 Polars February predictions. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index d97b4bc48..9e3ccb10a 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,7 +1,7 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a and SM-20a/20R/20S complete. SM-28b is next. Target: 0.9.0.** -Next deliverable: optional monthly local retraining schedule. Spark +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b and SM-20a/20R/20S complete. SM-27 is next. Target: 0.9.0.** +Next deliverable: bounded full-history local rescore with explicit activation. Spark expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -55,16 +55,18 @@ SUPERSEDED = replaced by a later user-directed scope; not a completed feature. | SM-20P | Company-shaped Bundle draft | SM-20a | SUPERSEDED | Replaced by the generic four-target SM-20R direction; no company workspace deployment | | SM-20R | Reset personal tests; generic minimal Bundle | SM-20a | DONE | Ten test jobs and three schemas removed; four target shapes validated, personal dev deployed with three jobs; one source, one prediction, one internal control, one UC model; Polars 600+50-row scoring and no-op replay; [live evidence](24-sm20r-clean-generic-bundle-validation-report.md) | | SM-20S | Two-job, table-minimal local Bundle | SM-20R | DONE | First score creates only prediction output; no admission tables; 650+1 rows, replay no-op, final two jobs/two tables; [live evidence](26-sm20s-two-job-live-validation-report.md) | -| SM-28b | Optional monthly retraining schedule | SM-20S, SM-28a | READY | Design one optional scheduled workflow around pinned labels, candidate comparison and explicit activation; keep the two-job starter unchanged and decide shared-target writer admission before wiring scoring | +| SM-28b | Optional monthly retraining schedule | SM-20S, SM-28a | DONE | Two-job Bundle with optional paused train schedule, pinned monthly label window/version and explicit activation; [plan](27-sm28b-monthly-retraining-plan.md), [validation](28-sm28b-monthly-retraining-validation-report.md) | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | -| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | LATER | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | +| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | READY | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | | SM-19 | Optional live HTTP / SQL ai_query / endpoint operations | SM-20a, compatible pyfunc package | LATER | Add only after serving parity; streaming remains parked | | SM-21 | Optional Databricks feature tables / online lookup | SM-20a; SM-19a for online serving | LATER | Point-in-time lookups and optional online freshness; declare any Spark dependency | | SM-23 | Optional monitoring and inference observability | SM-20a, relevant batch/serving adapter | LATER | Existing Skyulf metrics + optional Databricks monitoring/inference tables | | SM-24c | Spark batch workflow adapter | SM-20a, existing Spark sink | LATER | Expose tested Spark runner after first local Bundle | | SM-20b | Spark Bundle enhancement | SM-24c, selected SM-17 slices | LATER | Add tested Spark engine choice while preserving local variant | +SM-28b added no second score writer; shared-target admission remains a gate +before any later scoring workflow writes the same prediction table. SM-20R replaces SM-20P after the user's reset and generic-template direction. Company profile/policy execution remains unverified. SM-22a/b/c and SM-28a are prerequisites for the first Bundle. SM-28b only diff --git a/skyulf-core/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json index dea8d6ddc..04408c99e 100644 --- a/skyulf-core/templates/databricks/databricks_template_schema.json +++ b/skyulf-core/templates/databricks/databricks_template_schema.json @@ -22,6 +22,13 @@ "description": "Existing source column identifying one prediction row (also copied to output)", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "retraining_mode": { + "order": 12, + "type": "string", + "default": "manual", + "description": "Train manually, or add a paused monthly schedule to the same train job", + "enum": ["manual", "monthly_paused"] + }, "compute_mode": { "order": 4, "type": "string", diff --git a/skyulf-core/templates/databricks/examples/policy-init.example.json b/skyulf-core/templates/databricks/examples/policy-init.example.json index 84ae8b6ac..26e0fb6ea 100644 --- a/skyulf-core/templates/databricks/examples/policy-init.example.json +++ b/skyulf-core/templates/databricks/examples/policy-init.example.json @@ -2,6 +2,7 @@ "project_name": "my_model", "engine": "pandas", "row_key": "entity_id", + "retraining_mode": "manual", "compute_mode": "policy_cluster", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", diff --git a/skyulf-core/templates/databricks/examples/serverless-init.example.json b/skyulf-core/templates/databricks/examples/serverless-init.example.json index 14bff74fb..88feab715 100644 --- a/skyulf-core/templates/databricks/examples/serverless-init.example.json +++ b/skyulf-core/templates/databricks/examples/serverless-init.example.json @@ -2,6 +2,7 @@ "project_name": "my_model", "engine": "pandas", "row_key": "customer_id", + "retraining_mode": "manual", "compute_mode": "serverless", "catalog": "workspace", "schema": "my_dev_schema" diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index b3cdc75c3..9ece2bddc 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -9,10 +9,12 @@ same Skyulf workflow code with different target bindings. `bundle deploy` uploads the wheel, notebook and configuration, and creates two jobs. It creates **no** Unity Catalog table or registered model. +The initialization choice `retraining_mode=monthly_paused` adds a paused +schedule to the existing `train` job; the default `manual` choice adds none. | Job | Run it when | UC effect | | --- | --- | --- | -| `train` | A labeled snapshot is ready | Registers one candidate model and logs MLflow metrics | +| `train` | A labeled snapshot is ready, or a reviewed monthly schedule is unpaused | Registers one candidate model and logs MLflow metrics | | `score` | The model version is pinned and rows need predictions | Creates the prediction table if absent, then appends predictions for initial or new rows | Champion/challenger management is available through Skyulf Core but has no @@ -20,6 +22,20 @@ job in this starting Bundle. Training a candidate does not activate it for scoring. Set `model_version` to a concrete registered version and redeploy when you want scoring to use it. +In monthly mode, the job runs at 03:00 UTC on the third day of each month only +after you unpause it. Each run captures the latest concrete Delta source +version, uses the first day of that month as its UTC label cutoff, holds out +the preceding calendar month, and starts fit data +`monthly_lookback_months` months before the cutoff. The default lookback is +four months. `label_at` must reflect when a label became available: rows with +later labels are excluded. The captured Delta version is pinned at run start; +it is not a historical snapshot as of the cutoff. If the source has too few +labeled rows in either partition, training fails without publishing a model. +The run compares against the concrete version behind `@champion` if present; +a missing alias means first-model training. Registry access failures still +fail the job. Retry runs can create additional candidate versions; none is +promoted or used by `score` automatically. + `training_table` is the existing labeled input. `score_source_table` is the existing input to predict; the generated config points both at **one table**. You may give them different UC names when the labeled training data and new @@ -91,5 +107,5 @@ clusters are a separate compute choice at project initialization. `score` always uses its configured concrete model version. Training a new candidate or changing a registry alias does not rewrite old prediction rows. -There is no schedule, online endpoint or Spark-native FE/model execution in -this starting project. +The optional training schedule does not run `score`. There is no online +endpoint or Spark-native FE/model execution in this starting project. diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index 43537b790..beec9af95 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -2,6 +2,7 @@ "engine": "{{.engine}}", "training_table": "{catalog}.{input_schema}.{{.project_name}}_source", "training_version": 0, + "monthly_lookback_months": 4, "score_source_table": "{catalog}.{input_schema}.{{.project_name}}_source", "prediction_table": "{catalog}.{output_schema}.{{.project_name}}_predictions{resource_suffix}", "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl index dc2f9d3b3..ddc32efe6 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -2,12 +2,19 @@ resources: jobs: train: name: ${bundle.name}_train + max_concurrent_runs: 1 +{{if eq .retraining_mode "monthly_paused"}} + schedule: + quartz_cron_expression: "0 0 3 3 * ?" + timezone_id: UTC + pause_status: PAUSED +{{end}} tasks: - task_key: train notebook_task: notebook_path: ../src/workflow.py base_parameters: - action: train + action: {{if eq .retraining_mode "monthly_paused"}}train_monthly{{else}}train{{end}} config_path: ${workspace.file_path}/config/workflow.json experiment_name: ${workspace.root_path}/experiment catalog: ${var.catalog} diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py index 31803983d..4ca388d3f 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -5,7 +5,7 @@ import re import tempfile from dataclasses import asdict -from datetime import datetime +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -20,6 +20,7 @@ train_local_candidate, ) from skyulf.integrations.databricks.admission import SingleWriterAdmission +from skyulf.integrations.mlflow.registry import RegistryModelNotFoundError, resolve_model _TABLE_FIELDS = ( "training_table", @@ -184,6 +185,61 @@ def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: ) +def _monthly_training_spec(spark: Any, config: dict[str, Any], now: datetime) -> LocalTrainingSpec: + """Pin one Delta version and a UTC calendar window for monthly training.""" + if now.tzinfo is None or now.utcoffset() is None: + raise ValueError("Monthly training needs a timezone-aware run instant.") + lookback = config.get("monthly_lookback_months") + if type(lookback) is not int or not 2 <= lookback <= 120: + raise ValueError("monthly_lookback_months must be an integer from 2 to 120.") + cutoff = now.astimezone(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0) + + def months_before(count: int) -> datetime: + """Preserve the first-of-month boundary across year rollover.""" + index = cutoff.year * 12 + cutoff.month - 1 - count + return datetime(index // 12, index % 12 + 1, 1, tzinfo=UTC) + + table = config["training_table"] + if not _TABLE_NAME.fullmatch(table): + raise ValueError("training_table must be a three-part UC name.") + latest = ( + spark.sql(f"DESCRIBE HISTORY {table}") + .select("version") + .orderBy("version", ascending=False) + .first() + ) + if latest is None or type(latest["version"]) is not int: + raise ValueError("Training source has no concrete Delta version.") + return LocalTrainingSpec( + table=table, + version=latest["version"], + start=months_before(lookback), + holdout_start=months_before(1), + cutoff=cutoff, + event_column=config["event_column"], + label_time_column=config["label_time_column"], + row_keys=tuple(config["row_keys"]), + input_columns=tuple(config["input_columns"]), + target_column=config["target_column"], + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ) + + +def _monthly_champion_version(config: dict[str, Any]) -> str | None: + """Resolve the current champion once while allowing first-model training.""" + try: + champion = resolve_model( + config["model_name"], + alias="champion", + tracking_uri=config.get("tracking_uri", "databricks"), + registry_uri=config.get("registry_uri", "databricks-uc"), + ) + except RegistryModelNotFoundError: + return None + return champion.version + + def run_action( spark: Any, config: dict[str, Any], @@ -191,16 +247,26 @@ def run_action( *, experiment_name: str | None = None, artifact_path: str | Path | None = None, + now: datetime | None = None, ) -> Any: """Delegate training or scoring to Skyulf's existing services.""" tracking_uri = config.get("tracking_uri", "databricks") registry_uri = config.get("registry_uri", "databricks-uc") - if action == "train": + if action in {"train", "train_monthly"}: if experiment_name is None or artifact_path is None: raise ValueError("Training needs an experiment and temporary artifact path.") + monthly = action == "train_monthly" + spec = ( + _monthly_training_spec(spark, config, now or datetime.now(UTC)) + if monthly + else _training_spec(config) + ) + champion_version = ( + _monthly_champion_version(config) if monthly else config.get("champion_version") + ) return train_local_candidate( spark, - _training_spec(config), + spec, config["pipeline"], model_name=config["model_name"], tracking_uri=tracking_uri, @@ -211,7 +277,7 @@ def run_action( metric=config["metric"], min_improvement=config["min_improvement"], engine=config["engine"], - champion_version=config.get("champion_version"), + champion_version=champion_version, quality_threshold=config.get("quality_threshold"), ) if action == "score": @@ -249,8 +315,8 @@ def main() -> None: globals()["spark"], config, action, - experiment_name=widgets.get("experiment_name") if action == "train" else None, - artifact_path=Path(directory) / "artifact" if action == "train" else None, + experiment_name=widgets.get("experiment_name") if action.startswith("train") else None, + artifact_path=Path(directory) / "artifact" if action.startswith("train") else None, ) output = json.dumps(asdict(result), default=str, allow_nan=False) print(output) diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 00e665ff1..e68edac93 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -3,6 +3,7 @@ import importlib.util import json import re +from datetime import UTC, datetime, timedelta, timezone from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -69,6 +70,83 @@ def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, assert train.call_args.args[1].version == 0 +def test_monthly_window_pins_current_delta_version_across_year_boundary(): + """A delayed or timezone-shifted run must pin one reproducible monthly window.""" + workflow = _workflow() + history = Mock() + history.select.return_value.orderBy.return_value.first.return_value = {"version": 7} + spark = Mock() + spark.sql.return_value = history + config = _config() + config["monthly_lookback_months"] = 4 + spec = workflow._monthly_training_spec( + spark, config, datetime(2027, 1, 3, 5, tzinfo=timezone(timedelta(hours=2))) + ) + assert (spec.version, spec.start, spec.holdout_start, spec.cutoff) == ( + 7, + datetime(2026, 9, 1, tzinfo=UTC), + datetime(2026, 12, 1, tzinfo=UTC), + datetime(2027, 1, 1, tzinfo=UTC), + ) + spark.sql.assert_called_once_with("DESCRIBE HISTORY workspace.test.training") + + +def test_monthly_training_rejects_missing_version_and_invalid_lookback(): + """A scheduled run must fail before fitting an unpinned or empty window.""" + workflow = _workflow() + spark = Mock() + spark.sql.return_value.select.return_value.orderBy.return_value.first.return_value = None + config = _config() + config["monthly_lookback_months"] = 1 + with pytest.raises(ValueError, match="monthly_lookback_months"): + workflow._monthly_training_spec(spark, config, datetime(2027, 1, 3, tzinfo=UTC)) + config["monthly_lookback_months"] = 3 + with pytest.raises(ValueError, match="version"): + workflow._monthly_training_spec(spark, config, datetime(2027, 1, 3, tzinfo=UTC)) + + +def test_monthly_train_compares_pinned_champion_without_activation(monkeypatch, tmp_path): + """A monthly candidate must not change aliases or the scorer's pinned model.""" + workflow = _workflow() + spec = workflow._training_spec(_config()) + train = Mock(return_value=SimpleNamespace(model_version="3")) + champion = Mock(return_value=SimpleNamespace(version="2")) + monkeypatch.setattr(workflow, "_monthly_training_spec", lambda *args: spec) + monkeypatch.setattr(workflow, "resolve_model", champion) + monkeypatch.setattr(workflow, "train_local_candidate", train) + config = _config() + original_version = config["model_version"] + workflow.run_action( + object(), + config, + "train_monthly", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + now=datetime(2027, 1, 3, tzinfo=UTC), + ) + assert train.call_args.kwargs["champion_version"] == "2" + assert config["model_version"] == original_version + champion.assert_called_once() + + +def test_monthly_train_allows_first_model_but_propagates_registry_errors(monkeypatch): + """Only a missing champion alias is a valid first-training condition.""" + workflow = _workflow() + from skyulf.integrations.mlflow.registry import RegistryModelNotFoundError + + def missing(*args, **kwargs): + """Represent a registry without a champion alias.""" + raise RegistryModelNotFoundError("alias missing") + + monkeypatch.setattr(workflow, "resolve_model", missing) + assert workflow._monthly_champion_version(_config()) is None + monkeypatch.setattr( + workflow, "resolve_model", Mock(side_effect=RuntimeError("permission denied")) + ) + with pytest.raises(RuntimeError, match="permission denied"): + workflow._monthly_champion_version(_config()) + + def test_score_uses_incremental_service_without_period_or_source_version(monkeypatch): """Recurring scoring must derive new inserts from committed Delta receipts.""" workflow = _workflow() @@ -419,3 +497,9 @@ def test_generated_bundle_has_only_train_and_serialized_score_jobs(): assert re.search( r"^ score:\n name:.*\n max_concurrent_runs: 1$", template, re.MULTILINE ) + assert re.search( + r"^ train:\n name:.*\n max_concurrent_runs: 1$", template, re.MULTILINE + ) + assert 'if eq .retraining_mode "monthly_paused"' in template + assert "pause_status: PAUSED" in template + assert 'action: {{if eq .retraining_mode "monthly_paused"}}train_monthly' in template From d12d6aab9eefad62f5b1d416a7412b241989c704 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 19:42:26 +0300 Subject: [PATCH 52/85] feat: select model-change scoring and configure train schedule Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 4 + docs/user_guide/databricks_bundle.md | 35 ++- .../29-sm27-model-change-scoring-plan.md | 61 +++++ .../30-sm27-model-change-validation-report.md | 53 ++++ initiatives/spark_and_mlflow/HANDOFF.md | 7 + initiatives/spark_and_mlflow/OPEN_QUEUE.md | 2 +- .../databricks_template_schema.json | 23 ++ .../examples/policy-init.example.json | 1 + .../examples/serverless-init.example.json | 1 + .../template/{{.project_name}}/README.md.tmpl | 46 +++- .../config/workflow.json.tmpl | 1 + .../{{.project_name}}/databricks.yml.tmpl | 8 + .../resources/workflow.jobs.yml.tmpl | 4 +- .../{{.project_name}}/src/workflow.py | 114 ++++++++- .../integrations/test_local_delta_publish.py | 60 +++++ .../integration/test_sm20a_bundle_template.py | 235 ++++++++++++++++++ 16 files changed, 627 insertions(+), 28 deletions(-) create mode 100644 initiatives/spark_and_mlflow/29-sm27-model-change-scoring-plan.md create mode 100644 initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 0a8286e15..cb4b20836 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -23,6 +23,10 @@ execution, MLflow registry and Databricks delivery remain under development. An optional `monthly_paused` mode adds a paused monthly schedule to the same train job, pins a UTC label window and Delta version, and compares each new candidate with the current champion without automatic promotion or scoring. + Bundle initialization now selects whether a new pinned model version keeps + prior predictions and appends only new rows, or scores a new physical + generation and switches a stable view after success. Optional retraining + cron and timezone are editable Bundle variables. - Prediction Delta targets use `run_id`, `model_name` and `model_version` metadata columns. Existing test targets with the former `__skyulf_*` schema require a new target; the writer does not migrate tables. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index 274131d6f..017e5e348 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -12,7 +12,8 @@ databricks bundle init skyulf-core/templates/databricks --output-dir ./generated ``` The short path asks for project name, engine, one existing source row-key -column, optional retraining mode, serverless or policy-backed job compute and the existing `dev` +column, model-change scoring mode, optional retraining mode and cron, serverless +or policy-backed job compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable noninteractive examples are in `skyulf-core/templates/databricks/examples/`. The generated project has its own `databricks.yml`; Skyulf's root has no Bundle config. @@ -32,11 +33,12 @@ initialization. Serverless compute needs none of those fields. | Job | Purpose | UC objects created when run | | --- | --- | --- | | `train` | Fit one candidate and log held-out metrics | One registered model/version | -| `score` | Verify the source and pinned model, create output if absent, then score initial and later CDF inserts | One prediction table, only if absent; rows in that table | +| `score` | Score initial and later CDF rows | Prediction output and rows | The default project has no schedule. Choosing `monthly_paused` at initialization -adds a paused monthly schedule to the existing `train` job, without adding a -third job or running it at deployment. No endpoint or Unity Catalog table is +adds a paused schedule to the existing `train` job, without adding a third +job or running it at deployment. The Quartz cron and timezone are selected +at initialization and remain editable Bundle variables. No endpoint or Unity Catalog table is created by deployment alone. The starting Bundle has no alias lifecycle job. Skyulf Core's registry comparison and promotion services remain available for a separately designed @@ -48,7 +50,7 @@ The four relevant Unity Catalog names have different roles: | --- | --- | | `training_table` | Existing labeled input table, pinned to a Delta version for training | | `score_source_table` | Existing CDF-enabled source of rows to predict | -| `prediction_table` | The one output table for this model | +| `prediction_table` | The output table in append mode, or the stable active view in full-rebuild mode | | `model_name` | Registered Unity Catalog model, not a table | The first two references point to **the same existing table by default**. @@ -57,6 +59,11 @@ data and new scoring data have different lifecycles. If they stay together, the first `score` run predicts all existing rows, including historical labeled rows; review whether that is intended for your use case. +In `full_rebuild`, a version-specific physical table records the model name, +version and artifact digest. Scoring rejects an existing table at that name +when its model provenance differs. A new model with the same numeric version +needs a different logical prediction name or a new model version. + The initialization question `row_key` defaults to `entity_id`, but you can choose an existing `customer_id` column. It becomes `row_keys` in the generated configuration, and the same column appears in the prediction table. It must @@ -99,16 +106,24 @@ receipt. A repeat without new rows is a no-op. No monthly date or source version is entered for each run. The first candidate does not become champion automatically. Scoring stays -pinned to its configured model version; changing aliases does not rewrite old -predictions. `max_concurrent_runs: 1` serializes the generated score job, but +pinned to its configured model version; changing aliases alone does not +change predictions. At initialization, choose `incremental_append` to keep +v1 predictions and score only later source inserts with pinned v2. Choose +`full_rebuild` to write a new physical `_v2` generation, +switch the stable `prediction_table` view after a successful complete score, +and append future inserts to v2. The previous generation remains available; +a failed rebuild leaves the active view unchanged. Full mode needs view +creation/ownership privileges and cannot silently turn an existing append-mode +physical table into a view. `max_concurrent_runs: 1` serializes the generated score job, but does not coordinate other jobs. Grant prediction-table writes only to this job's identity. For multiple publishers, use Skyulf Core's shared admission provider. Full-history rescore, online endpoints and Spark-native FE/model execution are separate work. -The optional monthly `train` schedule runs at 03:00 UTC on day three and starts -paused. After configuring real labeled data and verifying a manual run, unpause -it deliberately. Each run pins the source's latest Delta version and uses the +The optional monthly `train` schedule defaults to 03:00 UTC on day three and +starts paused. Edit its Bundle cron and timezone variables for the desired +monthly run time. After configuring real labeled data and verifying a manual +run, unpause it deliberately. Each run pins the source's latest Delta version and uses the first day of the current UTC month as the label cutoff. The preceding month is holdout; `monthly_lookback_months` (default four) controls the full window. Only labels available by the cutoff are eligible. `@champion` is resolved to a diff --git a/initiatives/spark_and_mlflow/29-sm27-model-change-scoring-plan.md b/initiatives/spark_and_mlflow/29-sm27-model-change-scoring-plan.md new file mode 100644 index 000000000..7bd53acce --- /dev/null +++ b/initiatives/spark_and_mlflow/29-sm27-model-change-scoring-plan.md @@ -0,0 +1,61 @@ +# SM-27: Selectable model-change scoring and editable retraining schedule + +## Goal + +At Bundle initialization choose what happens **after an operator pins a new +registered model version**. Training, challenger staging and champion alias +changes alone must never change scoring. Keep the existing two jobs. + +`incremental_append` is the default. It preserves old rows and their +`model_version`. A newly pinned version scores only later source inserts. + +`full_rebuild` preserves the previous physical generation. A newly pinned +version scores one bounded full source snapshot into a new generation. After +that score succeeds, it switches the stable prediction view. Later inserts +append to the new generation using its own CDF receipt. + +The full-rebuild logical `prediction_table` is a Unity Catalog view. Physical +Delta generations are named `_v` and keep +their own model name, version, digest and source watermark. An existing +generation with different model provenance is rejected. A changed model +version selects a new generation, so the current incremental scorer safely +bootstraps from all source rows instead of trying to overwrite prior keys. +The same version reuses the generation and processes only later source inserts. +The view is created only after a nonempty successful first score; an existing +Skyulf-managed view is altered only after the candidate generation is complete +and its schema matches. Never replace an unrelated table or view. Use `ALTER +VIEW ... AS` for an existing view to retain its grants. The old generation +remains queryable. Switching from an already deployed append-mode physical +`prediction_table` to rebuild mode requires a new logical view name or an +explicit migration; this workflow must fail rather than replace that table. + +The default `incremental_append` path remains the existing one-table behavior. +Neither mode adds a third job, admission table, auto-promotion, or Spark-native +feature/model execution. `score` remains the sole serialized writer for each +target. Multiple writers still require shared admission before use. + +## Schedule configuration + +For the optional `monthly_paused` train schedule, initialization asks for a +Quartz cron expression and timezone (default `0 0 3 3 * ?`, `UTC`). Render +them as editable Bundle variables and reference those variables from the job +schedule. Keep the schedule paused by default. `manual` still emits no +schedule. The cron determines **when** training runs; the current monthly +training action still uses UTC calendar-month fit/holdout boundaries. A custom +nonmonthly cron is outside this action's contract and should be rejected or +documented as a monthly-frequency requirement. + +## Acceptance and verification + +1. Test both policies through the generated workflow: an appended v2 increment + leaves v1 rows intact; rebuild v2 uses a new target, fills it before view + activation and keeps v1 generation; same-version replay remains incremental. +2. Reject invalid modes/versions, missing source, empty generation, incompatible + output schema, existing physical table at the logical view name and any + non-Skyulf view. A failed score never changes the active view. +3. Generate default and rebuild projects through Databricks CLI and strictly + validate their serverless Bundle shape. Test that cron and timezone values + supplied at initialization appear as editable variables, not literals in + the resource file. +4. Run focused Core/Bundle tests, Ruff, ty, `mkdocs build --strict`, and + document any live test not run. Do not mutate a company workspace. diff --git a/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md b/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md new file mode 100644 index 000000000..d0553ba92 --- /dev/null +++ b/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md @@ -0,0 +1,53 @@ +# SM-27: Model-change scoring and configurable schedule validation + +Date: 2026-09-24. Branch: `090`. + +## Delivered locally + +The existing two-job Bundle asks how a newly pinned concrete model version +affects scoring. `incremental_append` remains the default and preserves old +predictions while scoring only later source inserts with the new model. +`full_rebuild` creates one physical Delta generation per model version, +bootstraps it from the current bounded source snapshot, and only then points +the stable prediction view at it. Subsequent source inserts are appended to +that generation using its own committed CDF receipt. Old generations remain. +The logical view rejects an existing physical table, a foreign view, an empty +new generation and an incompatible output schema. A known view-name conflict +fails before model loading or generation-table creation. Training a candidate +or changing an MLflow alias alone still does not select a scoring version. +Each generation table records the model name, version and artifact digest. +Reusing its numeric version with a different model or artifact is rejected. + +The optional `monthly_paused` train job now reads its Quartz cron and IANA +timezone from editable Bundle variables initialized from the user's answers. +The schedule stays paused; the default is the previous monthly time. The +monthly training window remains a UTC calendar-month window regardless of the +schedule timezone. + +## Verification + +- The focused suite passed: **46 passed, 18 skipped**. The generated-workflow + tests cover both mode selections, call order, + failed scoring, view ownership/schema guards, generation provenance and + editable schedule fields. +- Databricks CLI generated both a default append project and a custom + full-rebuild project with `0 30 7 10 * ?` / `Europe/Vilnius`. Both generated + serverless projects passed `bundle validate --strict -t dev --profile + skyulf` after the final workflow source was copied into each generated + project. This was read-only validation, not deployment or a job run. +- Ruff check/format, ty and `mkdocs build --strict` passed. +- A real local Delta v1/v2 generation test was added. The normal local venv + skips optional Delta; the Spark venv cannot start local Delta on this Windows + host because Hadoop's `winutils.exe` is absent. Its assertions have therefore + not passed yet, and no live Databricks full-rebuild job has run. + +## Live validation still needed + +Use an isolated personal-workspace source, model and output prefix. Score an +initial bounded source with v1, insert a new row, pin v2 and run the selected +full-rebuild mode. Verify the v1 physical generation remains unchanged, the +v2 generation contains all current source rows, the stable view points to v2, +and a later insert appends only to v2. Repeat the test in append mode to show +mixed `model_version` values in one physical target. Check the view's grants +after `ALTER VIEW`; then remove the isolated test resources after recording +evidence. Company targets remain untested. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index e1bc85a9b..792a06f31 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -2,6 +2,13 @@ ## Current state after SM-28b +SM-27 implementation now exposes append-vs-full-rebuild model-change scoring +at Bundle initialization and editable paused-retraining cron/timezone +variables. Generated-project CLI validation passed, but an actual v1-to-v2 +full-rebuild job has not run. Keep SM-27 ACTIVE until that live test verifies +the versioned physical tables and stable view; see +[SM-27 validation](30-sm27-model-change-validation-report.md). + The latest first Bundle has exactly two jobs (`train`, `score`), and its first score creates only the prediction table; see [SM-20S](26-sm20s-two-job-live-validation-report.md). SM-28b adds an optional diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 9e3ccb10a..bb7d92cad 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -58,7 +58,7 @@ SUPERSEDED = replaced by a later user-directed scope; not a completed feature. | SM-28b | Optional monthly retraining schedule | SM-20S, SM-28a | DONE | Two-job Bundle with optional paused train schedule, pinned monthly label window/version and explicit activation; [plan](27-sm28b-monthly-retraining-plan.md), [validation](28-sm28b-monthly-retraining-validation-report.md) | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | -| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | READY | Score a pinned, bounded source snapshot into a new prediction generation; validate and activate explicitly; preserve prior generation | +| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | ACTIVE | Both modes and editable cron implemented; generated Bundle validation passed; live v1/v2 scoring/view proof pending; [plan](29-sm27-model-change-scoring-plan.md), [validation](30-sm27-model-change-validation-report.md) | | SM-19 | Optional live HTTP / SQL ai_query / endpoint operations | SM-20a, compatible pyfunc package | LATER | Add only after serving parity; streaming remains parked | | SM-21 | Optional Databricks feature tables / online lookup | SM-20a; SM-19a for online serving | LATER | Point-in-time lookups and optional online freshness; declare any Spark dependency | | SM-23 | Optional monitoring and inference observability | SM-20a, relevant batch/serving adapter | LATER | Existing Skyulf metrics + optional Databricks monitoring/inference tables | diff --git a/skyulf-core/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json index 04408c99e..6be879013 100644 --- a/skyulf-core/templates/databricks/databricks_template_schema.json +++ b/skyulf-core/templates/databricks/databricks_template_schema.json @@ -29,6 +29,29 @@ "description": "Train manually, or add a paused monthly schedule to the same train job", "enum": ["manual", "monthly_paused"] }, + "model_change_mode": { + "order": 13, + "type": "string", + "default": "incremental_append", + "description": "Keep old predictions and append new rows, or rebuild all rows into a new model-version generation", + "enum": ["incremental_append", "full_rebuild"] + }, + "retraining_cron_expression": { + "order": 14, + "type": "string", + "default": "0 0 3 3 * ?", + "description": "Editable Quartz cron for the paused training job; use one run per month", + "pattern": "^[A-Za-z0-9*?/,# +\\-]+$", + "skip_prompt_if": {"properties": {"retraining_mode": {"const": "manual"}}} + }, + "retraining_timezone_id": { + "order": 15, + "type": "string", + "default": "UTC", + "description": "IANA timezone used by the paused training schedule; training windows remain UTC months", + "pattern": "^[A-Za-z_]+(?:/[A-Za-z0-9_+.-]+)*$", + "skip_prompt_if": {"properties": {"retraining_mode": {"const": "manual"}}} + }, "compute_mode": { "order": 4, "type": "string", diff --git a/skyulf-core/templates/databricks/examples/policy-init.example.json b/skyulf-core/templates/databricks/examples/policy-init.example.json index 26e0fb6ea..c15416b13 100644 --- a/skyulf-core/templates/databricks/examples/policy-init.example.json +++ b/skyulf-core/templates/databricks/examples/policy-init.example.json @@ -3,6 +3,7 @@ "engine": "pandas", "row_key": "entity_id", "retraining_mode": "manual", + "model_change_mode": "incremental_append", "compute_mode": "policy_cluster", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", diff --git a/skyulf-core/templates/databricks/examples/serverless-init.example.json b/skyulf-core/templates/databricks/examples/serverless-init.example.json index 88feab715..c94c1d803 100644 --- a/skyulf-core/templates/databricks/examples/serverless-init.example.json +++ b/skyulf-core/templates/databricks/examples/serverless-init.example.json @@ -3,6 +3,7 @@ "engine": "pandas", "row_key": "customer_id", "retraining_mode": "manual", + "model_change_mode": "incremental_append", "compute_mode": "serverless", "catalog": "workspace", "schema": "my_dev_schema" diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index 9ece2bddc..594354b09 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -14,16 +14,20 @@ schedule to the existing `train` job; the default `manual` choice adds none. | Job | Run it when | UC effect | | --- | --- | --- | -| `train` | A labeled snapshot is ready, or a reviewed monthly schedule is unpaused | Registers one candidate model and logs MLflow metrics | -| `score` | The model version is pinned and rows need predictions | Creates the prediction table if absent, then appends predictions for initial or new rows | +| `train` | Labeled data is ready or the schedule runs | Registers a candidate; logs metrics | +| `score` | A model is pinned and rows need scoring | Appends rows or builds a new generation | Champion/challenger management is available through Skyulf Core but has no job in this starting Bundle. Training a candidate does not activate it for scoring. Set `model_version` to a concrete registered version and redeploy when you want scoring to use it. -In monthly mode, the job runs at 03:00 UTC on the third day of each month only -after you unpause it. Each run captures the latest concrete Delta source +In monthly mode, the schedule starts paused. Its Quartz cron and IANA timezone +are selected at initialization and remain editable as +`retraining_cron_expression` and `retraining_timezone_id` Bundle variables. +The default is 03:00 UTC on the third day of each month. Configure one run per +month; a different cadence can retrain the same UTC month more than once. +After you unpause it, each run captures the latest concrete Delta source version, uses the first day of that month as its UTC label cutoff, holds out the preceding calendar month, and starts fit data `monthly_lookback_months` months before the cutoff. The default lookback is @@ -40,8 +44,19 @@ promoted or used by `score` automatically. existing input to predict; the generated config points both at **one table**. You may give them different UC names when the labeled training data and new inference data have different lifecycles. Neither is created by this Bundle. -`prediction_table` is the single model output table. `model_name` is a -registered UC model, not a table. The Bundle creates no admission table. +`prediction_table` is the physical output table in `incremental_append` mode. +In `full_rebuild` mode it is a stable **view**, backed by physical Delta +generations named `_v`. A successful `score` +fills a new generation before switching the view; previous generations stay +available. The first full score creates one physical table and the view. +Each generation records the registered model name, version and artifact digest. +An existing generation with different provenance is rejected. If you change +the registered model name while reusing the same numeric version, choose a +different logical prediction name or a new model version before scoring. +Moving an already deployed append-mode table to full mode under the same +logical name is rejected; choose a new view name or migrate deliberately. +`model_name` is a registered UC model, not a table. The Bundle creates no +admission table. The `row_key` selected during initialization names an existing source column; `score` copies it into the prediction table for SQL lookups. It must be non-null, `STRING` or `BIGINT`, and unique across all scored rows, including @@ -50,8 +65,10 @@ later inserts. If a customer can have multiple prediction rows, edit `["customer_id", "observation_id"]` before deployment. The initialization prompt chooses one column; it never creates an ID in the source. Keep key columns out of `input_columns`; they identify predictions, not model features. -The score job has `max_concurrent_runs: 1`; grant write access to the -prediction table only to this job's identity. Other jobs must not write it. +The score job has `max_concurrent_runs: 1`; grant write access to its physical +prediction targets only to this job's identity. In full mode the job also +needs permission to create and own the active view. Other jobs must not write +the targets. Skyulf Core's shared-admission option remains available when multiple jobs need to publish to one target. @@ -97,8 +114,9 @@ clusters are a separate compute choice at project initialization. 2. Put that concrete version in `model_version` in `config/workflow.json` and redeploy. Run `score`. It verifies the source, Change Data Feed, model outputs, row keys and any existing target schema before writing. It creates - only the missing prediction table; it never overwrites an existing table - or creates the source. The initial row check is bounded by `max_rows`, and + only a missing physical prediction table; it never overwrites an existing + table or creates the source. Full mode then creates or updates its managed + view after a complete nonempty score. The initial row check is bounded by `max_rows`, and scoring enforces `max_rows` and `max_bytes` for each local transfer. 3. Add new rows to the existing source Delta table and run `score` again. An unchanged replay is a no-op. No date or source-version argument @@ -106,6 +124,12 @@ clusters are a separate compute choice at project initialization. rescore policy. `score` always uses its configured concrete model version. Training a new -candidate or changing a registry alias does not rewrite old prediction rows. +candidate or changing a registry alias alone does not change predictions. +After pinning v2 and redeploying, `incremental_append` leaves v1 rows intact +and scores only new source inserts with v2. `full_rebuild` scores every current +source row into a new v2 table, switches the view only after success, then +uses that table's Delta receipt to append future inserts. A failed rebuild +leaves the old view active. The new generation must retain the active output +schema; an incompatible model needs a new logical view or an explicit migration. The optional training schedule does not run `score`. There is no online endpoint or Spark-native FE/model execution in this starting project. diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index beec9af95..6f4b34dfc 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -7,6 +7,7 @@ "prediction_table": "{catalog}.{output_schema}.{{.project_name}}_predictions{resource_suffix}", "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", "model_version": "1", + "model_change_mode": "{{.model_change_mode}}", "champion_version": null, "row_keys": ["{{.row_key}}"], "input_columns": ["feature_value"], diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl index a7681d2d3..a5548ab0e 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl @@ -26,6 +26,14 @@ variables: resource_suffix: description: Optional namespace suffix for shared development targets default: "" +{{if eq .retraining_mode "monthly_paused"}} + retraining_cron_expression: + description: Editable Quartz cron for the paused training job + default: "{{.retraining_cron_expression}}" + retraining_timezone_id: + description: IANA timezone for the paused training schedule + default: "{{.retraining_timezone_id}}" +{{end}} {{if eq .compute_mode "policy_cluster"}} cluster_policy_id: description: Approved policy looked up in the active workspace diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl index ddc32efe6..1d56a3824 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -5,8 +5,8 @@ resources: max_concurrent_runs: 1 {{if eq .retraining_mode "monthly_paused"}} schedule: - quartz_cron_expression: "0 0 3 3 * ?" - timezone_id: UTC + quartz_cron_expression: ${var.retraining_cron_expression} + timezone_id: ${var.retraining_timezone_id} pause_status: PAUSED {{end}} tasks: diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py index 4ca388d3f..8822f926c 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -89,6 +89,72 @@ def _scoring_config(config: dict[str, Any]) -> LocalWorkflowConfig: ) +def _scoring_target(config: dict[str, Any]) -> str: + """Choose a stable append target or a physical model-version generation.""" + mode = config.get("model_change_mode", "incremental_append") + if type(mode) is not str or mode not in {"incremental_append", "full_rebuild"}: + raise ValueError("model_change_mode must be incremental_append or full_rebuild.") + base = config["prediction_table"] + version = config["model_version"] + if not _TABLE_NAME.fullmatch(base): + raise ValueError("prediction_table must be a three-part UC name.") + if ( + type(version) is not str + or not version.isascii() + or not version.isdecimal() + or version[0] == "0" + ): + raise ValueError("model_version must be a concrete positive version.") + if mode == "full_rebuild": + return f"{base}_v{version}" + return base + + +def _managed_prediction_view_exists(spark: Any, logical: str) -> bool: + """Reject a table or unrelated view before creating prediction resources.""" + if not spark.catalog.tableExists(logical): + return False + if spark.catalog.getTable(logical).tableType.upper() != "VIEW": + raise ValueError("Full rebuild needs a view name, but a physical table already uses it.") + marker = spark.sql(f"SHOW TBLPROPERTIES {logical} ('skyulf.mode')").first() + if marker is None or marker["value"] != "full_rebuild": + raise ValueError("Existing prediction view is not managed by Skyulf full rebuild.") + return True + + +def _activate_prediction_view(spark: Any, logical: str, generation: str) -> None: + """Expose a complete generation without replacing prior prediction tables.""" + if ( + not _TABLE_NAME.fullmatch(logical) + or not _TABLE_NAME.fullmatch(generation) + or not re.fullmatch(re.escape(logical) + r"_v[1-9][0-9]*", generation) + ): + raise ValueError("Prediction view and generation names must match one UC target.") + physical = spark.table(generation) + if not physical.limit(1).count(): + raise ValueError("A full-rebuild generation must contain predictions before activation.") + if not _managed_prediction_view_exists(spark, logical): + spark.sql( + f"CREATE VIEW {logical} TBLPROPERTIES ('skyulf.mode' = 'full_rebuild') " + f"AS SELECT * FROM {generation}" + ).collect() + return + active_columns = tuple( + (field.name, field.dataType.typeName()) for field in spark.table(logical).schema.fields + ) + candidate_columns = tuple( + (field.name, field.dataType.typeName()) for field in physical.schema.fields + ) + if active_columns != candidate_columns: + raise ValueError("New prediction generation differs from the active view schema.") + definition = spark.sql(f"SHOW CREATE TABLE {logical}").first() + if definition is not None: + sql = definition["createtab_stmt"].casefold().replace("`", "") + if re.search(r"\bfrom\s+" + re.escape(generation.casefold()) + r"\b", sql): + return + spark.sql(f"ALTER VIEW {logical} AS SELECT * FROM {generation}").collect() + + def _prediction_columns( config: dict[str, Any], prepared: Any, source: Any ) -> tuple[tuple[str, str, str], ...]: @@ -129,6 +195,19 @@ def _check_existing_table(spark: Any, name: str, columns: tuple[tuple[str, str, raise ValueError(f"Existing prediction table {name} differs from the model output schema.") +def _generation_properties(config: dict[str, Any], prepared: Any) -> dict[str, str]: + """Bind a full-rebuild table to one concrete saved model artifact.""" + digest = prepared.preflight.model_digest + if type(digest) is not str or not re.fullmatch(r"[0-9a-f]{64}", digest): + raise ValueError("Pinned model has no valid artifact digest.") + return { + "skyulf.mode": "full_rebuild", + "skyulf.model_name": config["model_name"], + "skyulf.model_version": config["model_version"], + "skyulf.model_digest": digest, + } + + def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any) -> bool: """Preflight an existing source/model and create only a missing output table.""" source_name = config["score_source_table"] @@ -152,7 +231,19 @@ def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any ): raise ValueError("Scoring source must have Delta Change Data Feed enabled.") target_exists = spark.catalog.tableExists(target_name) + generation = config.get("model_change_mode") == "full_rebuild" + generation_properties = _generation_properties(config, prepared) if generation else {} if target_exists: + if generation: + actual_properties = ( + spark.sql(f"DESCRIBE DETAIL {target_name}").first()["properties"] or {} + ) + if any( + actual_properties.get(key) != value for key, value in generation_properties.items() + ): + raise ValueError( + "Existing prediction generation belongs to another model or workflow." + ) _check_existing_table(spark, target_name, columns) if not target_exists: if ( @@ -163,7 +254,15 @@ def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any ): raise ValueError("Initial scoring source exceeds the configured max_rows budget.") definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) - spark.sql(f"CREATE TABLE {target_name} ({definition}) USING DELTA").collect() + table_properties = "" + if generation: + properties = ", ".join( + f"'{key}' = '{value}'" for key, value in generation_properties.items() + ) + table_properties = f" TBLPROPERTIES ({properties})" + spark.sql( + f"CREATE TABLE {target_name} ({definition}) USING DELTA{table_properties}" + ).collect() return not target_exists @@ -281,14 +380,21 @@ def run_action( quality_threshold=config.get("quality_threshold"), ) if action == "score": - prepared = prepare_local_workflow(_scoring_config(config)) - provision_prediction_table(spark, config, prepared) - return run_incremental_local_batch( + target = _scoring_target(config) + if config.get("model_change_mode", "incremental_append") == "full_rebuild": + _managed_prediction_view_exists(spark, config["prediction_table"]) + score_config = {**config, "prediction_table": target} + prepared = prepare_local_workflow(_scoring_config(score_config)) + provision_prediction_table(spark, score_config, prepared) + result = run_incremental_local_batch( spark, prepared, row_keys=tuple(config["row_keys"]), admission=SingleWriterAdmission(), ) + if config.get("model_change_mode", "incremental_append") == "full_rebuild": + _activate_prediction_view(spark, config["prediction_table"], target) + return result raise ValueError(f"Unknown workflow action: {action}.") diff --git a/skyulf-core/tests/integrations/test_local_delta_publish.py b/skyulf-core/tests/integrations/test_local_delta_publish.py index e39d81327..daea24242 100644 --- a/skyulf-core/tests/integrations/test_local_delta_publish.py +++ b/skyulf-core/tests/integrations/test_local_delta_publish.py @@ -320,6 +320,66 @@ def test_incremental_single_writer_uses_receipts_without_control_table(local_del assert [row.id for row in spark.table(target).orderBy("id").collect()] == [1, 2, 3] +def test_new_model_generation_rebuilds_existing_rows_then_scores_new_inserts(local_delta_case): + """A v2 physical target must rescore all rows without changing v1's receipt.""" + from skyulf.integrations.databricks import run_incremental_local_batch + from skyulf.integrations.databricks.admission import SingleWriterAdmission + + spark, source, v1_target, prepared, _ = _prepared_incremental_case(local_delta_case) + v2_target = f"spark_catalog.default.local_predictions_v2_{uuid4().hex}" + try: + first = run_incremental_local_batch( + spark, prepared, row_keys=("id",), admission=SingleWriterAdmission() + ) + spark.createDataFrame( + [(3, datetime(2026, 1, 8, tzinfo=UTC), 6.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + spark.createDataFrame([], spark.table(v1_target).schema).write.format("delta").saveAsTable( + v2_target + ) + v2_config = prepared.config.model_copy( + update={ + "model": ModelSelection( + kind="local_pipeline", name="workspace.test.local_model", version="2" + ), + "sink": OutputSink(kind="uc_delta", table=v2_target), + } + ) + v2_prepared = replace( + prepared, + config=v2_config, + preflight=replace(prepared.preflight, model_version="2"), + ) + rebuilt = run_incremental_local_batch( + spark, v2_prepared, row_keys=("id",), admission=SingleWriterAdmission() + ) + spark.createDataFrame( + [(4, datetime(2026, 1, 9, tzinfo=UTC), 8.0)], + "id long, event_time timestamp, x double", + ).write.format("delta").mode("append").saveAsTable(source) + continued = run_incremental_local_batch( + spark, v2_prepared, row_keys=("id",), admission=SingleWriterAdmission() + ) + assert (first.input_count, rebuilt.input_count, continued.input_count) == (2, 3, 1) + assert [ + (row.id, row.model_version) for row in spark.table(v1_target).orderBy("id").collect() + ] == [ + (1, "1"), + (2, "1"), + ] + assert [ + (row.id, row.model_version) for row in spark.table(v2_target).orderBy("id").collect() + ] == [ + (1, "2"), + (2, "2"), + (3, "2"), + (4, "2"), + ] + finally: + spark.sql(f"DROP TABLE IF EXISTS {v2_target}") + + def test_incremental_local_batch_does_not_require_a_date_column(local_delta_case): """New rows are found from Delta commits even when no event date exists.""" from skyulf.integrations.databricks import run_incremental_local_batch diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index e68edac93..9efbd25f0 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -35,6 +35,7 @@ def _config(): "prediction_table": "workspace.test.predictions", "model_name": "workspace.test.model", "model_version": "1", + "model_change_mode": "incremental_append", "champion_version": "1", "row_keys": ["entity_id"], "input_columns": ["x"], @@ -53,6 +54,13 @@ def _config(): } +def _one_column_schema(kind): + """Model the Spark field names/types used by view compatibility checks.""" + return SimpleNamespace( + fields=[SimpleNamespace(name="prediction", dataType=SimpleNamespace(typeName=lambda: kind))] + ) + + def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, tmp_path): """A training job must only produce a candidate with the chosen fit engine.""" workflow = _workflow() @@ -164,6 +172,158 @@ def test_score_uses_incremental_service_without_period_or_source_version(monkeyp assert isinstance(score.call_args.kwargs["admission"], workflow.SingleWriterAdmission) +def test_full_rebuild_scores_new_generation_before_view_activation(monkeypatch): + """A v2 rebuild must fill a new table before changing the logical output view.""" + workflow = _workflow() + config = _config() + config.update(model_version="2", model_change_mode="full_rebuild") + events = [] + prepared = Mock() + provision = Mock(side_effect=lambda *args: events.append("provision")) + monkeypatch.setattr( + workflow, + "prepare_local_workflow", + Mock(side_effect=lambda cfg: events.append("prepare") or prepared), + ) + monkeypatch.setattr( + workflow, + "provision_prediction_table", + provision, + ) + monkeypatch.setattr( + workflow, + "run_incremental_local_batch", + Mock(side_effect=lambda *args, **kwargs: events.append("score") or object()), + ) + activate = Mock(side_effect=lambda *args: events.append("activate")) + monkeypatch.setattr(workflow, "_activate_prediction_view", activate) + spark = Mock() + spark.catalog.tableExists.return_value = False + workflow.run_action(spark, config, "score") + assert events == ["prepare", "provision", "score", "activate"] + assert provision.call_args.args[1]["prediction_table"] == "workspace.test.predictions_v2" + assert activate.call_args.args[1:] == ( + "workspace.test.predictions", + "workspace.test.predictions_v2", + ) + + +def test_full_rebuild_does_not_activate_a_failed_generation(monkeypatch): + """A failed full score must leave the active prediction view untouched.""" + workflow = _workflow() + config = _config() + config["model_change_mode"] = "full_rebuild" + monkeypatch.setattr(workflow, "prepare_local_workflow", Mock(return_value=object())) + monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) + monkeypatch.setattr( + workflow, "run_incremental_local_batch", Mock(side_effect=RuntimeError("score failed")) + ) + activate = Mock() + monkeypatch.setattr(workflow, "_activate_prediction_view", activate) + spark = Mock() + spark.catalog.tableExists.return_value = False + with pytest.raises(RuntimeError, match="score failed"): + workflow.run_action(spark, config, "score") + activate.assert_not_called() + + +def test_full_rebuild_rejects_existing_table_before_creating_generation(monkeypatch): + """A mode switch must fail before creating an orphan physical generation.""" + workflow = _workflow() + config = _config() + config["model_change_mode"] = "full_rebuild" + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.catalog.getTable.return_value.tableType = "MANAGED" + prepare = Mock() + provision = Mock() + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "provision_prediction_table", provision) + with pytest.raises(ValueError, match="view name"): + workflow.run_action(spark, config, "score") + prepare.assert_not_called() + provision.assert_not_called() + + +@pytest.mark.parametrize( + "mode,version", [("unknown", "2"), ("full_rebuild", "@champion"), ("full_rebuild", "02")] +) +def test_scoring_rejects_unsafe_model_change_selection(mode, version): + """An invalid mode or moving version must fail before a score target is chosen.""" + workflow = _workflow() + config = _config() + config.update(model_change_mode=mode, model_version=version) + with pytest.raises(ValueError): + workflow._scoring_target(config) + + +def test_full_rebuild_refuses_existing_table_at_logical_view_name(): + """Switching modes must never replace an existing prediction Delta table.""" + workflow = _workflow() + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.catalog.getTable.return_value.tableType = "MANAGED" + spark.table.return_value.limit.return_value.count.return_value = 2 + with pytest.raises(ValueError, match="view name"): + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + spark.sql.assert_not_called() + + +def test_full_rebuild_refuses_foreign_view_and_incompatible_schema(): + """Activation must neither hijack a foreign view nor break its output schema.""" + workflow = _workflow() + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.catalog.getTable.return_value.tableType = "VIEW" + spark.table.return_value.limit.return_value.count.return_value = 2 + spark.sql.return_value.first.return_value = {"value": "other"} + with pytest.raises(ValueError, match="Skyulf"): + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + spark.sql.reset_mock() + spark.sql.return_value.first.return_value = {"value": "full_rebuild"} + spark.table.side_effect = [ + SimpleNamespace( + limit=Mock(return_value=SimpleNamespace(count=lambda: 2)), + schema=_one_column_schema("double"), + ), + SimpleNamespace(schema=_one_column_schema("string")), + ] + with pytest.raises(ValueError, match="schema"): + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + assert all(not call.args[0].startswith("ALTER VIEW") for call in spark.sql.call_args_list) + + +def test_full_rebuild_creates_owned_view_then_preserves_grants_on_switch(): + """A validated generation becomes active through create then ALTER VIEW.""" + workflow = _workflow() + spark = Mock() + spark.table.return_value.limit.return_value.count.return_value = 2 + spark.table.return_value.schema = _one_column_schema("double") + spark.catalog.tableExists.side_effect = [False, True] + spark.catalog.getTable.return_value.tableType = "VIEW" + spark.sql.return_value.first.side_effect = [ + {"value": "full_rebuild"}, + { + "createtab_stmt": "CREATE VIEW workspace.test.predictions AS SELECT * FROM workspace.test.predictions_v1" + }, + ] + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v1" + ) + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + statements = [call.args[0] for call in spark.sql.call_args_list] + assert any(statement.startswith("CREATE VIEW") for statement in statements) + assert any(statement.startswith("ALTER VIEW") for statement in statements) + + def test_lifecycle_actions_are_not_bundle_entry_points(): """The minimal Bundle must not accidentally mutate registry aliases.""" workflow = _workflow() @@ -445,6 +605,66 @@ def test_prediction_provision_creates_no_control_table(monkeypatch): assert all("admission" not in statement for statement in statements) +def test_full_rebuild_generation_records_model_identity(monkeypatch): + """A new generation must carry enough provenance to reject unrelated tables.""" + workflow = _workflow() + config = _config() + config.update( + model_change_mode="full_rebuild", prediction_table="workspace.test.predictions_v2" + ) + spark = Mock() + spark.catalog.tableExists.side_effect = lambda name: name == config["score_source_table"] + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + spark.table.return_value.select.return_value.limit.return_value.count.return_value = 2 + monkeypatch.setattr( + workflow, "_prediction_columns", Mock(return_value=(("prediction", "double", "DOUBLE"),)) + ) + prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True, model_digest="a" * 64)) + assert workflow.provision_prediction_table(spark, config, prepared) is True + created = next( + call.args[0] for call in spark.sql.call_args_list if call.args[0].startswith("CREATE TABLE") + ) + assert "'skyulf.mode' = 'full_rebuild'" in created + assert "'skyulf.model_name' = 'workspace.test.model'" in created + assert "'skyulf.model_version' = '1'" in created + assert f"'skyulf.model_digest' = '{'a' * 64}'" in created + + +@pytest.mark.parametrize("changed", ["mode", "name", "digest"]) +def test_full_rebuild_rejects_unrelated_or_changed_generation(monkeypatch, changed): + """A same-named table must not be scored or activated under another model.""" + workflow = _workflow() + config = _config() + config.update( + model_change_mode="full_rebuild", prediction_table="workspace.test.predictions_v2" + ) + expected = { + "skyulf.mode": "full_rebuild", + "skyulf.model_name": config["model_name"], + "skyulf.model_version": config["model_version"], + "skyulf.model_digest": "a" * 64, + } + key = {"mode": "skyulf.mode", "name": "skyulf.model_name", "digest": "skyulf.model_digest"}[ + changed + ] + expected[key] = "other" + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.sql.return_value.first.side_effect = [ + {"properties": {"delta.enableChangeDataFeed": "true"}}, + {"properties": expected}, + ] + monkeypatch.setattr(workflow, "_prediction_columns", Mock(return_value=())) + check_target = Mock() + monkeypatch.setattr(workflow, "_check_existing_table", check_target) + prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True, model_digest="a" * 64)) + with pytest.raises(ValueError, match="another model or workflow"): + workflow.provision_prediction_table(spark, config, prepared) + check_target.assert_not_called() + + def test_generated_config_has_no_admission_or_alias_state(): """The starting Bundle must not ask users to provision coordination tables.""" template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" @@ -503,3 +723,18 @@ def test_generated_bundle_has_only_train_and_serialized_score_jobs(): assert 'if eq .retraining_mode "monthly_paused"' in template assert "pause_status: PAUSED" in template assert 'action: {{if eq .retraining_mode "monthly_paused"}}train_monthly' in template + assert "quartz_cron_expression: ${var.retraining_cron_expression}" in template + assert "timezone_id: ${var.retraining_timezone_id}" in template + + +def test_init_exposes_both_model_change_modes_and_editable_training_cadence(): + """The generated Bundle must let users choose scoring semantics and cron.""" + root = WORKFLOW.parents[3] + schema = json.loads((root / "databricks_template_schema.json").read_text(encoding="utf-8")) + properties = schema["properties"] + assert properties["model_change_mode"]["enum"] == ["incremental_append", "full_rebuild"] + assert properties["retraining_cron_expression"]["default"] == "0 0 3 3 * ?" + assert properties["retraining_timezone_id"]["default"] == "UTC" + bundle = (WORKFLOW.parents[1] / "databricks.yml.tmpl").read_text(encoding="utf-8") + assert 'default: "{{.retraining_cron_expression}}"' in bundle + assert 'default: "{{.retraining_timezone_id}}"' in bundle From 68f649355f4bbb2fb6626b06db6768ed3216ec49 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 20:21:26 +0300 Subject: [PATCH 53/85] feat: gate automatic champion selection before scoring Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 5 +- docs/user_guide/databricks_bundle.md | 48 +++-- .../31-sm29-auto-champion-design.md | 37 ++++ .../32-sm29-auto-champion-plan.md | 39 ++++ ...33-sm29-auto-champion-validation-report.md | 47 +++++ initiatives/spark_and_mlflow/HANDOFF.md | 12 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 6 +- .../skyulf/integrations/mlflow/promotion.py | 129 ++++++++++++ .../skyulf/integrations/mlflow/registry.py | 9 + .../databricks_template_schema.json | 30 +++ .../examples/policy-init.example.json | 1 + .../examples/serverless-init.example.json | 1 + .../template/{{.project_name}}/README.md.tmpl | 43 +++- .../config/workflow.json.tmpl | 7 +- .../resources/workflow.jobs.yml.tmpl | 11 + .../{{.project_name}}/src/workflow.py | 93 ++++++++- .../integrations/test_mlflow_promotion.py | 126 +++++++++++- .../integration/test_sm20a_bundle_template.py | 192 +++++++++++++++--- 18 files changed, 775 insertions(+), 61 deletions(-) create mode 100644 initiatives/spark_and_mlflow/31-sm29-auto-champion-design.md create mode 100644 initiatives/spark_and_mlflow/32-sm29-auto-champion-plan.md create mode 100644 initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index cb4b20836..e456eb9a0 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -22,7 +22,10 @@ execution, MLflow registry and Databricks delivery remain under development. initial and 50 later predictions, and replayed without a new commit. An optional `monthly_paused` mode adds a paused monthly schedule to the same train job, pins a UTC label window and Delta version, and compares each new - candidate with the current champion without automatic promotion or scoring. + candidate with the current champion. The default keeps promotion and scoring + selection manual. Optional automatic champion mode requires a heldout metric, + minimum improvement and absolute quality threshold. It uses checked alias + receipts and the same serialized score job, which pins champion per run. Bundle initialization now selects whether a new pinned model version keeps prior predictions and appends only new rows, or scores a new physical generation and switches a stable view after success. Optional retraining diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index 017e5e348..9fb528345 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -12,7 +12,7 @@ databricks bundle init skyulf-core/templates/databricks --output-dir ./generated ``` The short path asks for project name, engine, one existing source row-key -column, model-change scoring mode, optional retraining mode and cron, serverless +column, model-change and model-selection modes, optional retraining mode and cron, serverless or policy-backed job compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable noninteractive examples are in `skyulf-core/templates/databricks/examples/`. The generated @@ -40,9 +40,26 @@ adds a paused schedule to the existing `train` job, without adding a third job or running it at deployment. The Quartz cron and timezone are selected at initialization and remain editable Bundle variables. No endpoint or Unity Catalog table is created by deployment alone. -The starting Bundle has no alias lifecycle job. Skyulf Core's registry -comparison and promotion services remain available for a separately designed -champion/challenger workflow. +`pinned_version` keeps manual model selection. `auto_champion` uses the same +train job to compare candidate and champion on a pinned temporal holdout. The +selected `metric`, `min_improvement`, and absolute `quality_threshold` stay +editable in `config/workflow.json`. A first champion requires a numeric +absolute threshold because no prior version exists for comparison. Later +versions must pass that threshold and improve on champion by the chosen +minimum. A passing candidate is staged and promoted through checked registry +receipts; an ineligible candidate leaves champion unchanged. The train job +then calls the existing score job. No third job or control table is added. + +In automatic mode, score resolves `@champion` once to a concrete version per +run. Only the serialized train job identity may write this model's aliases; +other alias-write grants must be removed before enabling this table-free mode. +Alias promotion and Delta scoring are separate transactions. If scoring fails +after promotion, the last successful prediction output remains and the score +job must be retried. Unknown alias outcomes need receipt reconciliation. +Skyulf marks an alias transition as pending before writing it; automatic +training and scoring stop until that pending event is reconciled. An existing +champion alias set outside this controlled lifecycle also needs reconciliation +before automatic mode can use it. The four relevant Unity Catalog names have different roles: @@ -94,20 +111,21 @@ databricks bundle deploy -t dev --profile databricks bundle run train -t dev --profile ``` -Inspect the registered model version, put that concrete value in -`model_version`, redeploy the changed JSON, then run `score`. The first score +In manual mode, inspect the registered model version, put that concrete value +in `model_version`, redeploy the changed JSON, then run `score`. In automatic +mode, inspect the train and dependent score task results. The first score rejects a missing source, disabled CDF, unsuitable row keys, a model output -mismatch or an existing target schema mismatch before it creates the single -prediction table. It checks initial row count against `max_rows`; each score +mismatch or an existing target schema mismatch before creating prediction +output. It checks initial row count against `max_rows`; each score also checks decoded transfer bytes against `max_bytes`. Existing tables are never overwritten. The first score processes the current source snapshot; later runs process only new inserts since the committed Delta receipt. A repeat without new rows is a no-op. No monthly date or source version is entered for each run. -The first candidate does not become champion automatically. Scoring stays -pinned to its configured model version; changing aliases alone does not -change predictions. At initialization, choose `incremental_append` to keep +In manual mode, the first candidate does not become champion automatically; +scoring stays pinned to its configured version. At initialization, choose +`incremental_append` to keep v1 predictions and score only later source inserts with pinned v2. Choose `full_rebuild` to write a new physical `_v2` generation, switch the stable `prediction_table` view after a successful complete score, @@ -117,8 +135,8 @@ creation/ownership privileges and cannot silently turn an existing append-mode physical table into a view. `max_concurrent_runs: 1` serializes the generated score job, but does not coordinate other jobs. Grant prediction-table writes only to this job's identity. For multiple publishers, use Skyulf Core's shared admission -provider. Full-history rescore, online endpoints and Spark-native FE/model -execution are separate work. +provider. Online endpoints and Spark-native FE/model execution remain +separate work. The optional monthly `train` schedule defaults to 03:00 UTC on day three and starts paused. Edit its Bundle cron and timezone variables for the desired @@ -127,8 +145,8 @@ run, unpause it deliberately. Each run pins the source's latest Delta version an first day of the current UTC month as the label cutoff. The preceding month is holdout; `monthly_lookback_months` (default four) controls the full window. Only labels available by the cutoff are eligible. `@champion` is resolved to a -concrete version for comparison if present; the new candidate is never -promoted or substituted into `score` automatically. The source version is +concrete version for comparison if present. Manual mode leaves selection +unchanged; automatic mode applies its metric gates and invokes score. The source version is pinned at run start, so `label_at` must faithfully record availability. The older SM-20a personal serverless rehearsal passed, but its jobs and test diff --git a/initiatives/spark_and_mlflow/31-sm29-auto-champion-design.md b/initiatives/spark_and_mlflow/31-sm29-auto-champion-design.md new file mode 100644 index 000000000..2c97cd52c --- /dev/null +++ b/initiatives/spark_and_mlflow/31-sm29-auto-champion-design.md @@ -0,0 +1,37 @@ +# SM-29: Automatic local champion selection before Spark expansion + +The generated Bundle keeps two jobs: `train` and `score`. Initialization can +select `pinned_version` (current behavior) or `auto_champion`. The latter asks +for a task-compatible heldout metric, a nonnegative minimum improvement, and +an absolute quality threshold. All remain editable in `config/workflow.json`. + +`train` fits a candidate on a pinned, label-aware Delta snapshot. The existing +comparison evaluates candidate and champion on the **same** temporal holdout. +An existing champion changes only when the candidate is strictly better, +meets minimum improvement, and passes the absolute quality threshold. The +first champion has no comparison baseline, so it may be initialized only if +the mandatory absolute threshold passes on that same holdout. + +Alias mutation uses the existing prepared/committed registry receipts and +expected-version checks. The Bundle adds no control table: only the serialized +`train` job identity may write model aliases. This is an operational contract; +another alias writer voids the guarantee. Unknown alias outcomes fail closed +and require reconciliation. A pending model tag is verified before alias +mutation and cleared only after the committed receipt is verified. Automatic +train and score refuse pending tags or aliases lacking a controlled committed +receipt. The `train` job calls the existing serialized +`score` job after a successful training action. A candidate that fails the +gate leaves champion unchanged; scoring can still process new source rows +with the old champion. + +In automatic mode, each score run resolves `@champion` once to a concrete +version and uses the existing `incremental_append` or `full_rebuild` policy. +Prediction rows retain their concrete model version. Alias promotion and Delta +publication are separate transactions: if scoring fails, the prior prediction +view/table remains, and the score job must be retried. Do not silently roll +back the model alias. Full rebuild must retain its score-before-view-switch +ordering. Manual mode continues to require a concrete `model_version`. + +No Spark-native FE/model support, new endpoint, extra UC table, or third job is +part of SM-29. Live Databricks validation must cover first champion, passing +v2, rejected v3, append and rebuild behavior, and retry after score failure. diff --git a/initiatives/spark_and_mlflow/32-sm29-auto-champion-plan.md b/initiatives/spark_and_mlflow/32-sm29-auto-champion-plan.md new file mode 100644 index 000000000..a75a10fa8 --- /dev/null +++ b/initiatives/spark_and_mlflow/32-sm29-auto-champion-plan.md @@ -0,0 +1,39 @@ +# SM-29 Automatic Champion Implementation Plan + +> **For agentic workers:** Implement inline with test-driven development and +> check each step before moving to the next. + +**Goal:** Let a small-data Databricks Bundle retrain, select champion by a +chosen heldout metric and thresholds, and score with that concrete champion. + +**Architecture:** Reuse Skyulf Core's pinned comparison and guarded alias +receipts. Add first-champion validation, a documented exclusive-job admission +option, and Bundle orchestration that calls its existing score job. Resolve +champion once per score run so existing incremental/rebuild writers stay pinned. + +**Tech Stack:** Python, pandas/Polars, MLflow UC, Delta, Databricks Bundle. + +**Spec:** `initiatives/spark_and_mlflow/31-sm29-auto-champion-design.md`. + +## Global constraints + +- Preserve `pinned_version` behavior and the existing two job resources. +- No additional UC table; alias writes belong to one serialized job identity. +- First champion requires an absolute heldout quality threshold. +- A failed score never changes the active full-rebuild view. +- Keep SM-29 open until an isolated live test verifies the full lifecycle. + +## Tasks + +1. Add failing MLflow integration tests for first-champion threshold, + concurrent or stale alias state, and verified receipt. Implement the + guarded first-champion operation and exclusive-writer admission contract. +2. Add failing generated-workflow tests for auto train selection and score + alias resolution. Implement the two paths using the pinned training + snapshot, existing stage/promote APIs, and a concrete score-run version. +3. Add failing template tests for initialization fields, editable metric and + thresholds, and dependent `run_job_task` calling the existing score job. + Implement the Bundle template and document its first-run/failed-run flow. +4. Generate both modes through the CLI and run strict validation. Run focused + tests, Ruff, ty and strict docs build; record the results and update the + open queue. Live Databricks resources require a separate concrete test run. diff --git a/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md b/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md new file mode 100644 index 000000000..20f720ee6 --- /dev/null +++ b/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md @@ -0,0 +1,47 @@ +# SM-29: Automatic champion validation + +Date: 2026-09-24. Branch: `090`. + +## Local result + +The Bundle offers `pinned_version` and `auto_champion`. Automatic mode +compares a registered candidate with champion on a pinned temporal holdout, +checks the chosen metric and thresholds, stages and promotes an eligible +candidate, and calls the existing score job. First champion initialization +requires an absolute threshold and a fresh heldout check. Score resolves +champion once to a concrete version per run. The train and score jobs remain +serial and queue concurrent requests. Manual mode retains its version pin. +Alias mutation first records a pending model tag. Automatic training and +scoring reject pending tags and existing aliases without a controlled +committed receipt, so an uncertain registry write cannot become a silently +accepted champion on retry. + +No alias control table was added. Automatic alias writes rely on exclusive +model-alias write privileges for the train job identity. The caller must +enforce that boundary before production use. Registry alias promotion and +Delta publication are separate transactions; a failed score needs retry, +not a silent alias rollback. + +## Verification + +- The focused Bundle, retraining, MLflow registry, comparison and real local + promotion suite passed **94 tests**. First-champion tests exercise a + verified receipt, an existing alias without a receipt, an unknown alias + outcome, and rejected missing/failed quality thresholds. +- Databricks CLI 1.17.0 generated a manual serverless Bundle and a Polars + `auto_champion` full-rebuild Bundle with `heldout_rmse`, minimum improvement + `0.05`, quality threshold `10.0`, and a custom paused monthly cron. Both + passed strict read-only `dev` validation with the `skyulf` profile. +- A fresh `uv build --wheel --no-build-isolation` succeeded. Focused Ruff + check/format, ty, `git diff --check` and `mkdocs build --strict` passed. + The CLI projects were generated from the final template and validated + read-only; their jobs have not been deployed or run. + +## Live validation still needed + +In an isolated personal-workspace schema, test first champion, a passing v2, +an ineligible v3, the train-to-score job handoff, and both append/rebuild +scoring policies. Confirm model-version values in predictions, old-generation +retention, view activation, queued score behavior, a failed-score retry, and +the alias-write privilege boundary. Do not deploy to company targets until +their hosts, catalogs and grants are configured and validated. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 792a06f31..a22c9ead7 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -2,6 +2,14 @@ ## Current state after SM-28b +SM-29 now has an optional `auto_champion` Bundle selection. It asks for a +heldout metric, minimum improvement and absolute quality threshold, uses the +existing guarded alias receipts, and calls the serialized score job after +train. Manual selection remains the default. Generated manual/automatic +serverless projects passed strict CLI validation. Live alias-to-Delta evidence +is pending, so keep SM-29 ACTIVE; see +[SM-29 validation](33-sm29-auto-champion-validation-report.md). + SM-27 implementation now exposes append-vs-full-rebuild model-change scoring at Bundle initialization and editable paused-retraining cron/timezone variables. Generated-project CLI validation passed, but an actual v1-to-v2 @@ -15,8 +23,8 @@ score creates only the prediction table; see paused monthly schedule to that same `train` job. Manual and monthly generated projects passed strict CLI validation; no monthly live job was deployed or run. See [SM-28b validation](28-sm28b-monthly-retraining-validation-report.md). -The next open item is SM-27, a bounded full-history local rescore with a new -prediction generation and explicit activation. Company workspace targets +The next open item is the combined live SM-27/SM-29 verification of model +selection and both scoring modes. Company workspace targets remain unconfigured and unverified. The remainder of this file is historical context from earlier Bundle stages. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index bb7d92cad..f311491f3 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,7 +1,8 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b and SM-20a/20R/20S complete. SM-27 is next. Target: 0.9.0.** -Next deliverable: bounded full-history local rescore with explicit activation. Spark +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b and SM-20a/20R/20S complete. SM-27 and SM-29 are active before Spark. Target: 0.9.0.** +Next deliverable: live proof for selectable local rescoring and automatic +champion selection. Spark expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -59,6 +60,7 @@ SUPERSEDED = replaced by a later user-directed scope; not a completed feature. | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | | SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | ACTIVE | Both modes and editable cron implemented; generated Bundle validation passed; live v1/v2 scoring/view proof pending; [plan](29-sm27-model-change-scoring-plan.md), [validation](30-sm27-model-change-validation-report.md) | +| SM-29 | Gated automatic champion and score handoff | SM-22a/b/c, SM-28a/b, SM-27 | ACTIVE | First and later champion gates, existing two-job handoff and alias-pinned scoring implemented locally; live UC alias/score proof pending; [design](31-sm29-auto-champion-design.md), [plan](32-sm29-auto-champion-plan.md), [validation](33-sm29-auto-champion-validation-report.md) | | SM-19 | Optional live HTTP / SQL ai_query / endpoint operations | SM-20a, compatible pyfunc package | LATER | Add only after serving parity; streaming remains parked | | SM-21 | Optional Databricks feature tables / online lookup | SM-20a; SM-19a for online serving | LATER | Point-in-time lookups and optional online freshness; declare any Spark dependency | | SM-23 | Optional monitoring and inference observability | SM-20a, relevant batch/serving adapter | LATER | Existing Skyulf metrics + optional Databricks monitoring/inference tables | diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py index ca1e27e30..4f45d6735 100644 --- a/skyulf-core/skyulf/integrations/mlflow/promotion.py +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -35,6 +35,7 @@ _PREVIOUS = "previous_champion" _ACTIVE_TAG = "champion_current_event" _CHALLENGER_TAG = "challenger_current_event" +_PENDING_TAG = "pending_alias_event" class AliasConflictError(RegistryError): @@ -108,6 +109,23 @@ def hold(self, resource_id: str) -> Iterator[None]: raise AliasConflictError("Another writer holds alias admission.") from exc +class ExclusiveAliasWriterAdmission: + """Use no control table when one serialized job owns all alias writes. + + This provider does not lock. The caller must ensure that no other job or + principal can mutate the model aliases, including manual UI writes. + """ + + local_only = False + + @contextmanager + def hold(self, resource_id: str) -> Iterator[None]: + """Enter the externally enforced exclusive alias-writer scope.""" + if type(resource_id) is not str or not resource_id.startswith("mlflow-alias:"): + raise ValueError("Exclusive alias writing needs an alias resource ID.") + yield + + @dataclass(frozen=True, slots=True) class AliasChangeReceipt: """Record a verified alias transition and its durable registry event.""" @@ -158,6 +176,40 @@ def _read_alias(client: Any, name: str) -> str: return current +def _assert_no_pending(client: Any, name: str) -> None: + """Stop automatic alias work until an uncertain prior write is reconciled.""" + tags = client.get_registered_model(name).tags or {} + if tags.get(_PENDING_TAG): + raise AliasConflictError("A pending alias event requires reconciliation.") + + +def controlled_champion_version( + model_name: str, + *, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> str | None: + """Read a champion only when its last transition has a committed receipt.""" + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + try: + registered = client.get_registered_model(model_name) + except Exception as exc: # noqa: BLE001 - a new model has no registry object yet + if _error_code(exc) in {"RESOURCE_DOES_NOT_EXIST", "NOT_FOUND"}: + return None + raise _translate_error(exc, name=model_name, version=_ALIAS) from exc + tags = registered.tags or {} + if tags.get(_PENDING_TAG): + raise AliasConflictError("A pending alias event requires reconciliation.") + current = _read_optional_alias(client, model_name, _ALIAS) + if current is None: + if tags.get(_ACTIVE_TAG): + raise AliasConflictError("Champion receipt exists without its alias.") + return None + if _active_marker(client, model_name, current) is None: + raise AliasConflictError("Champion alias lacks a controlled committed receipt.") + return current + + def _active_marker(client: Any, name: str, current: str, alias: str = _ALIAS) -> str | None: """Reject a bypass write that left the active receipt on another version.""" tag = _ACTIVE_TAG if alias == _ALIAS else _CHALLENGER_TAG @@ -237,10 +289,20 @@ def _commit_change( MLflow alias calls are not atomic. Once any call may have changed an alias, failures are reported as unknown and require reconciliation before retry. """ + _assert_no_pending(client, receipt.model_name) try: _write_event(client, receipt, "prepared") except Exception as exc: # noqa: BLE001 - registry transport boundary raise _translate_error(exc, name=receipt.model_name, version=receipt.new_version) from exc + try: + client.set_registered_model_tag(receipt.model_name, _PENDING_TAG, receipt.event_id) + pending = (client.get_registered_model(receipt.model_name).tags or {}).get(_PENDING_TAG) + if pending != receipt.event_id: + raise AliasOutcomeUnknownError("Pending alias event was not verified.") + except Exception as exc: # noqa: BLE001 - pending marker may have been written + raise AliasOutcomeUnknownError( + f"Alias preparation outcome unknown; inspect event {receipt.event_id}." + ) from exc changed = False for alias, new_version, old_version in updates: try: @@ -283,6 +345,8 @@ def _commit_change( != receipt.event_id ): raise AliasOutcomeUnknownError("Active receipt verification failed.") + client.delete_registered_model_tag(receipt.model_name, _PENDING_TAG) + _assert_no_pending(client, receipt.model_name) except Exception as exc: # noqa: BLE001 - never imply rollback after a possible alias write raise AliasOutcomeUnknownError( f"Alias may have changed; inspect event {receipt.event_id} before retry." @@ -345,6 +409,71 @@ def _validated_report( ).hexdigest() +def initialize_champion( + report: ModelComparisonReport, + heldout: pd.DataFrame | pl.DataFrame, + *, + target_column: str, + admission: AliasAdmission, + max_rows: int, + max_bytes: int, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> AliasChangeReceipt: + """Initialize an absent champion only after a fresh absolute-quality check.""" + _admission(admission, registry_uri) + if not isinstance(report, ModelComparisonReport) or report.champion_version is not None: + raise ValueError("First champion needs a comparison without a champion.") + threshold = report.quality_threshold + if threshold is None: + raise ValueError("First champion needs an absolute quality threshold.") + candidate = resolve_model( + report.model_name, + version=report.candidate_version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + fresh = compare_registered_local_models( + candidate, + None, + heldout, + target_column=target_column, + dataset_id=report.dataset_id, + metric=report.metric, + min_improvement=report.min_improvement, + quality_threshold=report.quality_threshold, + max_rows=max_rows, + max_bytes=max_bytes, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + if fresh != report: + raise ValueError("Pinned first-champion comparison changed before initialization.") + value = fresh.candidate_metrics[fresh.metric] + passed = value <= threshold if fresh.metric_direction == "minimize" else value >= threshold + if not passed: + raise ValueError("First champion failed the absolute quality threshold.") + digest = hashlib.sha256(json.dumps(asdict(fresh), sort_keys=True).encode()).hexdigest() + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + with admission.hold(alias_resource_id(report.model_name)): + if _read_optional_alias(client, report.model_name, _ALIAS) is not None: + raise AliasConflictError("Champion alias already exists.") + if (client.get_registered_model(report.model_name).tags or {}).get(_ACTIVE_TAG): + raise AliasConflictError("Champion receipt exists without its alias.") + receipt = AliasChangeReceipt( + event_id=uuid4().hex, + kind="initial", + model_name=report.model_name, + alias=_ALIAS, + prior_version=None, + new_version=report.candidate_version, + comparison_sha256=digest, + parent_event_id=None, + ) + _commit_change(client, receipt, [(_ALIAS, report.candidate_version, None)]) + return receipt + + def stage_challenger( report: ModelComparisonReport, heldout: pd.DataFrame | pl.DataFrame, diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py index 6588512f4..f1e3ece02 100644 --- a/skyulf-core/skyulf/integrations/mlflow/registry.py +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -239,6 +239,15 @@ def resolve_model( else client.get_model_version(name, str(version)) ) except Exception as exc: # noqa: BLE001 - translate MLflow's backend errors at the boundary + if ( + alias is not None + and _error_code(exc) == "INVALID_PARAMETER_VALUE" + and "alias" in str(exc).lower() + and "not found" in str(exc).lower() + ): + raise RegistryModelNotFoundError( + f"Model '{name}' alias '{alias}' was not found." + ) from exc raise _translate_error(exc, name=name, version=str(version or alias)) from exc concrete_version = str(model_version.version) diff --git a/skyulf-core/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json index 6be879013..d7c478736 100644 --- a/skyulf-core/templates/databricks/databricks_template_schema.json +++ b/skyulf-core/templates/databricks/databricks_template_schema.json @@ -36,6 +36,36 @@ "description": "Keep old predictions and append new rows, or rebuild all rows into a new model-version generation", "enum": ["incremental_append", "full_rebuild"] }, + "model_selection_mode": { + "order": 16, + "type": "string", + "default": "pinned_version", + "description": "Pin one model version manually or select champion after a gated training run", + "enum": ["pinned_version", "auto_champion"] + }, + "metric": { + "order": 17, + "type": "string", + "default": "heldout_rmse", + "description": "Heldout metric for candidate/champion comparison; must match the model task", + "enum": ["heldout_mae", "heldout_mse", "heldout_rmse", "heldout_r2", "heldout_mape", "heldout_explained_variance", "heldout_accuracy", "heldout_balanced_accuracy", "heldout_precision_weighted", "heldout_recall_weighted", "heldout_f1_weighted", "heldout_matthews_corrcoef", "heldout_precision", "heldout_recall", "heldout_f1", "heldout_g_score", "heldout_log_loss", "heldout_roc_auc", "heldout_pr_auc", "heldout_roc_auc_ovr_weighted", "heldout_roc_auc_weighted", "heldout_roc_auc_ovr", "heldout_roc_auc_ovo", "heldout_roc_auc_ovo_weighted", "heldout_pr_auc_weighted"] + }, + "min_improvement": { + "order": 18, + "type": "number", + "default": 0.0, + "minimum": 0, + "description": "Minimum metric improvement over champion; ties never pass", + "skip_prompt_if": {"properties": {"model_selection_mode": {"const": "pinned_version"}}} + }, + "quality_threshold": { + "order": 19, + "type": "string", + "default": "null", + "description": "Enter a numeric absolute heldout gate for the first champion; null is rejected in automatic mode", + "pattern": "^(null|-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)$", + "skip_prompt_if": {"properties": {"model_selection_mode": {"const": "pinned_version"}}} + }, "retraining_cron_expression": { "order": 14, "type": "string", diff --git a/skyulf-core/templates/databricks/examples/policy-init.example.json b/skyulf-core/templates/databricks/examples/policy-init.example.json index c15416b13..e878bece0 100644 --- a/skyulf-core/templates/databricks/examples/policy-init.example.json +++ b/skyulf-core/templates/databricks/examples/policy-init.example.json @@ -4,6 +4,7 @@ "row_key": "entity_id", "retraining_mode": "manual", "model_change_mode": "incremental_append", + "model_selection_mode": "pinned_version", "compute_mode": "policy_cluster", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", diff --git a/skyulf-core/templates/databricks/examples/serverless-init.example.json b/skyulf-core/templates/databricks/examples/serverless-init.example.json index c94c1d803..dd7e5e895 100644 --- a/skyulf-core/templates/databricks/examples/serverless-init.example.json +++ b/skyulf-core/templates/databricks/examples/serverless-init.example.json @@ -4,6 +4,7 @@ "row_key": "customer_id", "retraining_mode": "manual", "model_change_mode": "incremental_append", + "model_selection_mode": "pinned_version", "compute_mode": "serverless", "catalog": "workspace", "schema": "my_dev_schema" diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index 594354b09..b43b9e99e 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -17,10 +17,30 @@ schedule to the existing `train` job; the default `manual` choice adds none. | `train` | Labeled data is ready or the schedule runs | Registers a candidate; logs metrics | | `score` | A model is pinned and rows need scoring | Appends rows or builds a new generation | +{{if eq .model_selection_mode "auto_champion"}} +This project uses automatic champion selection. `train` compares a candidate +against champion on a pinned temporal holdout. The first champion needs a +numeric absolute `quality_threshold`; later candidates need strictly positive +improvement that meets `min_improvement`. A passing candidate is staged then +promoted through checked registry receipts. A failed candidate leaves champion +unchanged. The train job calls the existing score job after it succeeds. + +Score resolves `@champion` once to a concrete version at run start. Alias +promotion and Delta publication are separate transactions. If scoring fails +after promotion, retry `score`; the previous successful prediction output +remains until a new score completes. Only the serialized train job identity +may write this model's aliases. Restrict other alias writers before enabling +automatic mode; table-free alias admission does not provide a lock. An +unknown alias-write outcome leaves a pending marker and blocks later automatic +training and scoring until registry receipt reconciliation. An existing +`@champion` set outside Skyulf's guarded promotion path has no committed +receipt and must be reconciled before automatic mode can use it. +{{else}} Champion/challenger management is available through Skyulf Core but has no job in this starting Bundle. Training a candidate does not activate it for scoring. Set `model_version` to a concrete registered version and redeploy when you want scoring to use it. +{{end}} In monthly mode, the schedule starts paused. Its Quartz cron and IANA timezone are selected at initialization and remain editable as @@ -37,8 +57,9 @@ it is not a historical snapshot as of the cutoff. If the source has too few labeled rows in either partition, training fails without publishing a model. The run compares against the concrete version behind `@champion` if present; a missing alias means first-model training. Registry access failures still -fail the job. Retry runs can create additional candidate versions; none is -promoted or used by `score` automatically. +fail the job. Retry runs can create additional candidate versions. +{{if eq .model_selection_mode "pinned_version"}}None is promoted or used by +`score` automatically.{{end}} `training_table` is the existing labeled input. `score_source_table` is the existing input to predict; the generated config points both at **one table**. @@ -111,8 +132,15 @@ clusters are a separate compute choice at project initialization. 1. Run `train` against a pinned labeled Delta version. It logs held-out MLflow metrics and registers a concrete model version. +{{if eq .model_selection_mode "auto_champion"}} +2. The train job evaluates the candidate and calls the existing score job. + Inspect both task results. The first score requires a champion that passed + the absolute threshold. +{{else}} 2. Put that concrete version in `model_version` in `config/workflow.json` and - redeploy. Run `score`. It verifies the source, Change Data Feed, model + redeploy. Run `score`. +{{end}} + Scoring verifies the source, Change Data Feed, model outputs, row keys and any existing target schema before writing. It creates only a missing physical prediction table; it never overwrites an existing table or creates the source. Full mode then creates or updates its managed @@ -123,13 +151,20 @@ clusters are a separate compute choice at project initialization. is entered for each run. Source updates or deletes require a separate rescore policy. +{{if eq .model_selection_mode "pinned_version"}} `score` always uses its configured concrete model version. Training a new candidate or changing a registry alias alone does not change predictions. +{{else}} +`score` loads the concrete champion version at run start. A later alias change +cannot alter that run's pinned model. The train job invokes scoring after +selection; score remains independently runnable for new source rows. +{{end}} After pinning v2 and redeploying, `incremental_append` leaves v1 rows intact and scores only new source inserts with v2. `full_rebuild` scores every current source row into a new v2 table, switches the view only after success, then uses that table's Delta receipt to append future inserts. A failed rebuild leaves the old view active. The new generation must retain the active output schema; an incompatible model needs a new logical view or an explicit migration. -The optional training schedule does not run `score`. There is no online +{{if eq .model_selection_mode "pinned_version"}}The optional training schedule +does not run `score`.{{end}} There is no online endpoint or Spark-native FE/model execution in this starting project. diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index 6f4b34dfc..b505f22ff 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -8,6 +8,7 @@ "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", "model_version": "1", "model_change_mode": "{{.model_change_mode}}", + "model_selection_mode": "{{.model_selection_mode}}", "champion_version": null, "row_keys": ["{{.row_key}}"], "input_columns": ["feature_value"], @@ -19,9 +20,9 @@ "cutoff": "2025-03-01T00:00:00+00:00", "max_rows": 10000, "max_bytes": 67108864, - "metric": "heldout_rmse", - "min_improvement": 0.0, - "quality_threshold": null, + "metric": "{{.metric}}", + "min_improvement": {{.min_improvement}}, + "quality_threshold": {{if eq .model_selection_mode "auto_champion"}}{{.quality_threshold}}{{else}}null{{end}}, "pipeline": { "preprocessing": [], "modeling": {"type": "linear_regression"} diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl index 1d56a3824..335ab018b 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -3,6 +3,8 @@ resources: train: name: ${bundle.name}_train max_concurrent_runs: 1 + queue: + enabled: true {{if eq .retraining_mode "monthly_paused"}} schedule: quartz_cron_expression: ${var.retraining_cron_expression} @@ -31,6 +33,13 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} +{{if eq .model_selection_mode "auto_champion"}} + - task_key: score_after_training + depends_on: + - task_key: train + run_job_task: + job_id: ${resources.jobs.score.id} +{{end}} {{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf @@ -55,6 +64,8 @@ resources: score: name: ${bundle.name}_score max_concurrent_runs: 1 + queue: + enabled: true tasks: - task_key: score notebook_task: diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py index 8822f926c..885cbcc6f 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -4,11 +4,13 @@ import json import re import tempfile -from dataclasses import asdict +from dataclasses import asdict, dataclass from datetime import UTC, datetime from pathlib import Path from typing import Any +import polars as pl + from skyulf.integrations.databricks import ( InputSource, LocalTrainingSpec, @@ -16,10 +18,20 @@ ModelSelection, OutputSink, prepare_local_workflow, + read_training_snapshot, run_incremental_local_batch, + split_labeled_snapshot, train_local_candidate, ) from skyulf.integrations.databricks.admission import SingleWriterAdmission +from skyulf.integrations.mlflow.promotion import ( + AliasChangeReceipt, + ExclusiveAliasWriterAdmission, + controlled_champion_version, + initialize_champion, + promote_candidate, + stage_challenger, +) from skyulf.integrations.mlflow.registry import RegistryModelNotFoundError, resolve_model _TABLE_FIELDS = ( @@ -38,6 +50,22 @@ } +@dataclass(frozen=True, slots=True) +class AutoTrainingOutcome: + """Expose both candidate evidence and the optional alias change in job output.""" + + candidate: Any + alias_change: AliasChangeReceipt | None + + +def _selection_mode(config: dict[str, Any]) -> str: + """Reject a selection policy that could silently load a wrong model.""" + mode = config.get("model_selection_mode", "pinned_version") + if mode not in ("pinned_version", "auto_champion"): + raise ValueError("model_selection_mode must be pinned_version or auto_champion.") + return mode + + def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: """Bind only UC object names to one validated Bundle target.""" for name in ("catalog", "input_schema", "output_schema", "metadata_schema"): @@ -339,6 +367,40 @@ def _monthly_champion_version(config: dict[str, Any]) -> str | None: return champion.version +def _automatic_promotion( + spark: Any, config: dict[str, Any], spec: LocalTrainingSpec, candidate: Any +) -> AliasChangeReceipt | None: + """Recheck the pinned holdout before one guarded champion transition.""" + report = candidate.comparison + if report.champion_version is not None and not report.eligible: + return None + frame = read_training_snapshot(spark, spec) + _, heldout, _ = split_labeled_snapshot(frame, spec) + native = pl.from_pandas(heldout) if config["engine"] == "polars" else heldout + options = { + "target_column": spec.target_column, + "admission": ExclusiveAliasWriterAdmission(), + "max_rows": spec.max_rows, + "max_bytes": spec.max_bytes, + "tracking_uri": config.get("tracking_uri", "databricks"), + "registry_uri": config.get("registry_uri", "databricks-uc"), + } + if report.champion_version is None: + return initialize_champion(report, native, **options) + stage_challenger( + report, + native, + expected_champion_version=report.champion_version, + **options, + ) + return promote_candidate( + report, + native, + expected_champion_version=report.champion_version, + **options, + ) + + def run_action( spark: Any, config: dict[str, Any], @@ -351,19 +413,27 @@ def run_action( """Delegate training or scoring to Skyulf's existing services.""" tracking_uri = config.get("tracking_uri", "databricks") registry_uri = config.get("registry_uri", "databricks-uc") + selection_mode = _selection_mode(config) if action in {"train", "train_monthly"}: if experiment_name is None or artifact_path is None: raise ValueError("Training needs an experiment and temporary artifact path.") monthly = action == "train_monthly" + if selection_mode == "auto_champion" and config.get("quality_threshold") is None: + raise ValueError("auto_champion requires an absolute quality_threshold.") spec = ( _monthly_training_spec(spark, config, now or datetime.now(UTC)) if monthly else _training_spec(config) ) - champion_version = ( - _monthly_champion_version(config) if monthly else config.get("champion_version") - ) - return train_local_candidate( + if selection_mode == "auto_champion": + champion_version = controlled_champion_version( + config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri + ) + elif monthly: + champion_version = _monthly_champion_version(config) + else: + champion_version = config.get("champion_version") + candidate = train_local_candidate( spark, spec, config["pipeline"], @@ -379,7 +449,20 @@ def run_action( champion_version=champion_version, quality_threshold=config.get("quality_threshold"), ) + if selection_mode == "auto_champion": + return AutoTrainingOutcome( + candidate=candidate, + alias_change=_automatic_promotion(spark, config, spec, candidate), + ) + return candidate if action == "score": + if selection_mode == "auto_champion": + champion_version = controlled_champion_version( + config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri + ) + if champion_version is None: + raise ValueError("auto_champion scoring requires a committed champion.") + config = {**config, "model_version": champion_version} target = _scoring_target(config) if config.get("model_change_mode", "incremental_append") == "full_rebuild": _managed_prediction_view_exists(spark, config["prediction_table"]) diff --git a/skyulf-core/tests/integrations/test_mlflow_promotion.py b/skyulf-core/tests/integrations/test_mlflow_promotion.py index ce078d2a2..ea42adbd8 100644 --- a/skyulf-core/tests/integrations/test_mlflow_promotion.py +++ b/skyulf-core/tests/integrations/test_mlflow_promotion.py @@ -16,6 +16,7 @@ AliasChangeReceipt, AliasConflictError, AliasOutcomeUnknownError, + ExclusiveAliasWriterAdmission, LocalAliasAdmission, _admission, alias_resource_id, @@ -23,7 +24,12 @@ rollback_promotion, stage_challenger, ) -from skyulf.integrations.mlflow.registry import RegistryAccessError, register_model, resolve_model +from skyulf.integrations.mlflow.registry import ( + RegistryAccessError, + RegistryModelNotFoundError, + register_model, + resolve_model, +) from skyulf.integrations.mlflow.tracking import TrackingConfig, track_run from skyulf.integrations.mlflow.validation import ( ModelComparisonReport, @@ -308,6 +314,119 @@ def test_missing_champion_and_contention_refuse_promotion(case) -> None: _promote(case) +def test_first_champion_needs_absolute_quality_and_verified_receipt(case) -> None: + """An unseeded registry must select only a rechecked, good first model.""" + from skyulf.integrations.mlflow.promotion import ( + controlled_champion_version, + initialize_champion, + ) + + client, uri, name, heldout, _, admission = case + client.delete_registered_model_alias(name, "champion") + with pytest.raises(RegistryModelNotFoundError): + resolve_model(name, alias="champion", tracking_uri=uri, registry_uri=uri) + assert controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) is None + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + report = compare_registered_local_models( + candidate, + None, + heldout, + target_column="target", + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=0.0, + quality_threshold=1.0, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + receipt = initialize_champion( + report, + heldout, + target_column="target", + admission=admission, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + assert receipt.kind == "initial" + assert receipt.new_version == "2" + assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + assert controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) == "2" + with pytest.raises(AliasConflictError): + initialize_champion( + report, + heldout, + target_column="target", + admission=admission, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + + +def test_first_champion_rejects_missing_or_failed_quality_threshold(case) -> None: + """Automatic bootstrap cannot use improvement alone without a baseline.""" + from skyulf.integrations.mlflow.promotion import initialize_champion + + client, uri, name, heldout, _, admission = case + client.delete_registered_model_alias(name, "champion") + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + for threshold in (None, -1.0): + report = compare_registered_local_models( + candidate, + None, + heldout, + target_column="target", + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=0.0, + quality_threshold=threshold, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + with pytest.raises(ValueError, match="quality threshold"): + initialize_champion( + report, + heldout, + target_column="target", + admission=admission, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + with pytest.raises(mlflow.exceptions.MlflowException): + client.get_model_version_by_alias(name, "champion") + + +def test_controlled_champion_rejects_alias_without_receipt(case) -> None: + """An alias set outside the guarded lifecycle must not feed automatic scoring.""" + from skyulf.integrations.mlflow.promotion import controlled_champion_version + + client, uri, name, _, _, _ = case + with pytest.raises(AliasConflictError, match="committed receipt"): + controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) + client.set_registered_model_tag(name, "skyulf_pending_alias_event", "unresolved") + with pytest.raises(AliasConflictError, match="pending"): + controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) + + +def test_exclusive_alias_writer_requires_external_serialization() -> None: + """A table-free UC writer opts into an explicit alias resource contract.""" + admission = ExclusiveAliasWriterAdmission() + assert _admission(admission, "databricks-uc") is admission + with admission.hold(alias_resource_id("catalog.schema.model")): + assert admission.local_only is False + with pytest.raises(ValueError, match="alias resource ID"), admission.hold("not-an-alias"): + pass + + def test_rollback_rejects_newer_alias_state(case) -> None: """A receipt cannot roll back a different current model version.""" client, uri, name, _, _, admission = case @@ -359,6 +478,11 @@ def move_then_fail(model_name, alias, version): with pytest.raises(AliasOutcomeUnknownError, match="inspect prepared event"): _promote(case) assert str(client.get_model_version_by_alias(name, "champion").version) == "2" + assert client.get_registered_model(name).tags.get("skyulf_pending_alias_event") + from skyulf.integrations.mlflow.promotion import controlled_champion_version + + with pytest.raises(AliasConflictError, match="pending"): + controlled_champion_version(name, tracking_uri=case[1], registry_uri=case[1]) def test_old_receipt_cannot_rollback_newer_promotion_to_same_version(case) -> None: diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 9efbd25f0..0659f30d4 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -54,6 +54,23 @@ def _config(): } +def _render_default_config(row_key="entity_id"): + """Resolve the manual-mode template fields read by the generated-config tests.""" + template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" + content = ( + template.read_text(encoding="utf-8") + .replace("{{.project_name}}", "customer_model") + .replace("{{.engine}}", "pandas") + .replace("{{.row_key}}", row_key) + .replace("{{.min_improvement}}", "0.0") + .replace( + '{{if eq .model_selection_mode "auto_champion"}}{{.quality_threshold}}{{else}}null{{end}}', + "null", + ) + ) + return json.loads(content) + + def _one_column_schema(kind): """Model the Spark field names/types used by view compatibility checks.""" return SimpleNamespace( @@ -155,6 +172,127 @@ def missing(*args, **kwargs): workflow._monthly_champion_version(_config()) +def test_auto_champion_train_promotes_only_an_eligible_candidate(monkeypatch, tmp_path): + """A passing candidate must use the pinned holdout and controlled alias APIs.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", quality_threshold=1.0, engine="pandas") + report = SimpleNamespace(champion_version="1", eligible=True) + candidate = SimpleNamespace(comparison=report) + frame = object() + heldout = object() + monkeypatch.setattr(workflow, "train_local_candidate", Mock(return_value=candidate)) + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="1")) + monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=frame), raising=False) + monkeypatch.setattr( + workflow, + "split_labeled_snapshot", + Mock(return_value=(object(), heldout, 0)), + raising=False, + ) + stage = Mock(return_value=object()) + promote = Mock(return_value=SimpleNamespace(new_version="2")) + monkeypatch.setattr(workflow, "stage_challenger", stage, raising=False) + monkeypatch.setattr(workflow, "promote_candidate", promote, raising=False) + result = workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.alias_change.new_version == "2" + assert stage.call_args.args[1] is heldout + assert promote.call_args.kwargs["expected_champion_version"] == "1" + + +def test_auto_champion_train_leaves_alias_when_candidate_fails_gate(monkeypatch, tmp_path): + """A failed comparison must never stage or promote its registered model.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", quality_threshold=1.0, engine="pandas") + monkeypatch.setattr( + workflow, + "train_local_candidate", + Mock( + return_value=SimpleNamespace( + comparison=SimpleNamespace(champion_version="1", eligible=False) + ) + ), + ) + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="1")) + stage = Mock() + monkeypatch.setattr(workflow, "stage_challenger", stage, raising=False) + result = workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.alias_change is None + stage.assert_not_called() + + +def test_auto_champion_bootstraps_first_model_or_rejects_missing_threshold(monkeypatch, tmp_path): + """First-model selection requires a real absolute gate before fitting.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", quality_threshold=None, engine="pandas") + train = Mock(return_value=SimpleNamespace(comparison=SimpleNamespace(champion_version=None))) + monkeypatch.setattr(workflow, "train_local_candidate", train) + with pytest.raises(ValueError, match="quality_threshold"): + workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + train.assert_not_called() + config["quality_threshold"] = 1.0 + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value=None)) + monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=object())) + monkeypatch.setattr( + workflow, + "split_labeled_snapshot", + Mock(return_value=(object(), object(), 0)), + ) + initialize = Mock(return_value=SimpleNamespace(new_version="1")) + monkeypatch.setattr(workflow, "initialize_champion", initialize) + result = workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.alias_change.new_version == "1" + initialize.assert_called_once() + + +def test_auto_champion_score_pins_resolved_version_before_target_selection(monkeypatch): + """A moving alias must become one concrete model and full-rebuild table per run.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", model_change_mode="full_rebuild") + controlled = Mock(return_value="2") + prepare = Mock(return_value=object()) + provision = Mock() + monkeypatch.setattr(workflow, "controlled_champion_version", controlled) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "provision_prediction_table", provision) + monkeypatch.setattr(workflow, "run_incremental_local_batch", Mock(return_value=object())) + monkeypatch.setattr(workflow, "_activate_prediction_view", Mock()) + spark = Mock() + spark.catalog.tableExists.return_value = False + workflow.run_action(spark, config, "score") + assert controlled.call_args.args == (config["model_name"],) + assert prepare.call_args.args[0].model.version == "2" + assert provision.call_args.args[1]["prediction_table"] == "workspace.test.predictions_v2" + assert config["model_version"] == "1" + + def test_score_uses_incremental_service_without_period_or_source_version(monkeypatch): """Recurring scoring must derive new inserts from committed Delta receipts.""" workflow = _workflow() @@ -435,13 +573,7 @@ def test_target_binding_rejects_cross_environment_model(): def test_generated_config_keeps_company_output_in_each_target(): """The actual JSON template must bind its outputs separately in every target.""" workflow = _workflow() - template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" - config = json.loads( - template.read_text(encoding="utf-8") - .replace("{{.project_name}}", "customer_model") - .replace("{{.engine}}", "pandas") - .replace("{{.row_key}}", "entity_id") - ) + config = _render_default_config() outputs = {} for target, catalog, suffix in ( ("test", "test_catalog", "_murat"), @@ -471,13 +603,7 @@ def test_generated_config_keeps_company_output_in_each_target(): def test_minimal_generated_config_uses_one_existing_source(): """Default training and scoring should reference one existing source table.""" workflow = _workflow() - template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" - config = json.loads( - template.read_text(encoding="utf-8") - .replace("{{.project_name}}", "customer_model") - .replace("{{.engine}}", "pandas") - .replace("{{.row_key}}", "entity_id") - ) + config = _render_default_config() bound = workflow.resolve_target_config( config, { @@ -667,13 +793,7 @@ def test_full_rebuild_rejects_unrelated_or_changed_generation(monkeypatch, chang def test_generated_config_has_no_admission_or_alias_state(): """The starting Bundle must not ask users to provision coordination tables.""" - template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" - config = json.loads( - template.read_text(encoding="utf-8") - .replace("{{.project_name}}", "customer_model") - .replace("{{.engine}}", "pandas") - .replace("{{.row_key}}", "entity_id") - ) + config = _render_default_config() assert "score_admission_table" not in config assert "alias_admission_table" not in config assert "include_lifecycle" not in config @@ -685,13 +805,7 @@ def test_init_row_key_becomes_prediction_table_key(): schema = json.loads((root / "databricks_template_schema.json").read_text(encoding="utf-8")) assert schema["properties"]["row_key"]["default"] == "entity_id" - template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" - config = json.loads( - template.read_text(encoding="utf-8") - .replace("{{.project_name}}", "customer_model") - .replace("{{.engine}}", "pandas") - .replace("{{.row_key}}", "customer_id") - ) + config = _render_default_config("customer_id") source = SimpleNamespace( columns=["customer_id", "feature_value"], schema={ @@ -738,3 +852,25 @@ def test_init_exposes_both_model_change_modes_and_editable_training_cadence(): bundle = (WORKFLOW.parents[1] / "databricks.yml.tmpl").read_text(encoding="utf-8") assert 'default: "{{.retraining_cron_expression}}"' in bundle assert 'default: "{{.retraining_timezone_id}}"' in bundle + + +def test_auto_champion_init_exposes_metric_gates_and_reuses_score_job(): + """Automatic selection must be explicit and call the serialized score job.""" + root = WORKFLOW.parents[3] + schema = json.loads((root / "databricks_template_schema.json").read_text(encoding="utf-8")) + properties = schema["properties"] + assert properties["model_selection_mode"]["enum"] == [ + "pinned_version", + "auto_champion", + ] + assert "heldout_rmse" in properties["metric"]["enum"] + assert "heldout_f1" in properties["metric"]["enum"] + assert properties["quality_threshold"]["type"] == "string" + assert properties["quality_threshold"]["default"] == "null" + config = (WORKFLOW.parents[1] / "config/workflow.json.tmpl").read_text(encoding="utf-8") + assert '"model_selection_mode": "{{.model_selection_mode}}"' in config + assert '"metric": "{{.metric}}"' in config + jobs = (WORKFLOW.parents[1] / "resources/workflow.jobs.yml.tmpl").read_text(encoding="utf-8") + assert "job_id: ${resources.jobs.score.id}" in jobs + assert "task_key: score_after_training" in jobs + assert jobs.count("queue:\n enabled: true") == 2 From 556b63f3fa6a2a2b973ea9fe0b8360b37f1f976b Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 20:24:20 +0300 Subject: [PATCH 54/85] docs: plan isolated champion and rescore rehearsal Signed-off-by: flyingriverhorse --- .../34-sm27-sm29-live-rehearsal-plan.md | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md diff --git a/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md b/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md new file mode 100644 index 000000000..c7b4f54f8 --- /dev/null +++ b/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md @@ -0,0 +1,58 @@ +# SM-27/SM-29 isolated live rehearsal + +Status: awaiting approval for personal-workspace resources and serverless runs. +Catalog: `workspace`; proposed schema: `skyulf_sm27_sm29_20260924`. +Profile: `skyulf`; target: `dev`. Company targets are out of scope. + +## Test resources + +| Resource | Purpose | +| --- | --- | +| `workspace.skyulf_sm27_sm29_20260924.source` | One bounded, CDF-enabled Delta source containing labeled history and later inserts | +| `...predictions_append` | One physical incremental prediction table | +| `...predictions_full` | One stable full-rebuild view over `_v1` and `_v2` physical generations | +| `...model` | One registered UC model with v1, v2 and v3 candidates | +| `skyulf_sm29_verify_train`, `skyulf_sm29_verify_score` | The generated Bundle's only two persistent jobs | + +The source will have 160 deterministic rows at initialization, with +`entity_id`, `feature_value`, `target`, `event_time`, and `label_at` columns. +The target is a simple customer-value estimate in dollars derived from the +feature, so the test can check model quality as well as row identity. Ten new +rows will be appended only after the initial runs. This is a bounded ML +contract test, not a benchmark or production dataset. A one-time ephemeral +serverless setup run creates the schema and source; it does not create a +persistent setup job. Each submitted task will have a 15-minute timeout. + +## Rehearsal sequence + +1. Generate a Polars, serverless, `auto_champion` Bundle with a heldout RMSE + gate and `incremental_append`. Build the current wheel, validate the Bundle + strictly, deploy only its `dev` target, and inspect that deployment itself + created no UC table/model. +2. Train v1 with a deliberately underfit linear model. The first model must + pass an absolute RMSE gate, receive a committed `@champion` receipt, and + trigger the score job. Verify 160 v1 prediction rows. +3. Change only the scoring policy/output to `full_rebuild` and score v1. + Verify the complete `_v1` table and managed view. +4. Train v2 with an intercept on the same pinned labeled snapshot. Verify a + lower RMSE, the configured minimum improvement, `@challenger` staging, + promotion to `@champion`, `@previous_champion=v1`, and automatic scoring + into complete `_v2` before the view switches. `_v1` must remain unchanged. +5. Return to append mode, insert ten new source rows, and score. Verify that + the append table retains its 160 v1 rows and adds exactly ten v2 rows. + Score full mode again and verify its v2 generation/view reaches 170 rows. +6. Train v3 with the same configuration as v2. The tie should fail the + improvement gate, leave champion on v2, and let scoring process no new + rows. Verify the concrete model-version metadata, aliases, receipts, + MLflow heldout metrics, target versions, and no-op behavior. + +Record run URLs/IDs, counts, model metrics, aliases, table/view state, and +any failure before calling either task DONE. Read-only audits will inspect +outputs. Keep test resources for user inspection until cleanup is explicitly +requested. Production and company workspaces remain untouched. + +This plan does not establish exclusive alias-write permissions by itself. +Before treating the Bundle as production-ready, give the train identity sole +model-alias write authority and verify a restricted identity is denied. If +the personal workspace cannot provide that isolation, record it as an open +deployment gate rather than claiming it passed. From 7c3a086691cf28d9d6bdfee100fe4eb388f962c5 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 21:06:45 +0300 Subject: [PATCH 55/85] docs: record live champion and rescore validation Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 3 + docs/user_guide/databricks_bundle.md | 27 +++ .../30-sm27-model-change-validation-report.md | 27 +-- ...33-sm29-auto-champion-validation-report.md | 25 +-- .../34-sm27-sm29-live-rehearsal-plan.md | 3 +- .../35-sm27-sm29-live-validation-report.md | 154 ++++++++++++++++++ initiatives/spark_and_mlflow/HANDOFF.md | 28 +++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 32 +++- 8 files changed, 265 insertions(+), 34 deletions(-) create mode 100644 initiatives/spark_and_mlflow/35-sm27-sm29-live-validation-report.md diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index e456eb9a0..7bef69b40 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -30,6 +30,9 @@ execution, MLflow registry and Databricks delivery remain under development. prior predictions and appends only new rows, or scores a new physical generation and switches a stable view after success. Optional retraining cron and timezone are editable Bundle variables. + The live Polars/serverless rehearsal verified first champion, improved-model + promotion, tied-candidate rejection, both scoring policies, failed-score + recovery, queued no-op requests and a restricted-principal alias-write denial. - Prediction Delta targets use `run_id`, `model_name` and `model_version` metadata columns. Existing test targets with the former `__skyulf_*` schema require a new target; the writer does not migrate tables. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index 9fb528345..b92927fe7 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -61,6 +61,33 @@ training and scoring stop until that pending event is reconciled. An existing champion alias set outside this controlled lifecycle also needs reconciliation before automatic mode can use it. +For example, a regression project can select its gate in the generated config: + +```json +{ + "engine": "polars", + "model_selection_mode": "auto_champion", + "metric": "heldout_rmse", + "min_improvement": 0.1, + "quality_threshold": 5.0, + "model_change_mode": "incremental_append" +} +``` + +These example values mean RMSE must be at most `5.0`; a later candidate must +reduce champion's RMSE by at least `0.1` on the same holdout. Improvement is +an absolute metric difference, not a percentage. Skyulf derives the direction +from the metric: RMSE/MAE/log loss are minimized, while R²/accuracy/F1 are +maximized. Use a metric supported by the configured model task. The first +comparison reports `reason=no_champion` and `eligible=false` because no +baseline exists; successful bootstrap is recorded separately as +`alias_change.kind=initial` after the absolute gate passes. + +If promotion succeeds but scoring fails, the train job reports a failed +dependent score task. Correct the scoring problem and run `score` again; +retraining is unnecessary. Full-rebuild output continues to expose the last +successfully activated generation during this recovery. + The four relevant Unity Catalog names have different roles: | Name | Meaning | diff --git a/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md b/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md index d0553ba92..2799aea91 100644 --- a/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md +++ b/initiatives/spark_and_mlflow/30-sm27-model-change-validation-report.md @@ -2,6 +2,9 @@ Date: 2026-09-24. Branch: `090`. +Live closure: **PASS** for the selected Polars/serverless workflow. See +[SM-27/SM-29 live evidence](35-sm27-sm29-live-validation-report.md). + ## Delivered locally The existing two-job Bundle asks how a newly pinned concrete model version @@ -39,15 +42,15 @@ schedule timezone. - A real local Delta v1/v2 generation test was added. The normal local venv skips optional Delta; the Spark venv cannot start local Delta on this Windows host because Hadoop's `winutils.exe` is absent. Its assertions have therefore - not passed yet, and no live Databricks full-rebuild job has run. - -## Live validation still needed - -Use an isolated personal-workspace source, model and output prefix. Score an -initial bounded source with v1, insert a new row, pin v2 and run the selected -full-rebuild mode. Verify the v1 physical generation remains unchanged, the -v2 generation contains all current source rows, the stable view points to v2, -and a later insert appends only to v2. Repeat the test in append mode to show -mixed `model_version` values in one physical target. Check the view's grants -after `ALTER VIEW`; then remove the isolated test resources after recording -evidence. Company targets remain untested. + not passed on this Windows host. The subsequent live Databricks rehearsal + below provides the selected UC full-rebuild proof. + +## Live validation completed + +The approved personal-workspace rehearsal verified 160 initial v1 rows, +complete v2 rescoring before view activation, then ten later inserts. The +append target retains mixed v1/v2 rows, the full view exposes 170 v2 rows, +and the v1 generation stays unchanged. The view's SELECT grant survived +ALTER VIEW. A deliberate target-type failure preserved prior outputs; +scoring-only retry succeeded. Resources remain for user inspection as the +latest approval requested. Company targets remain untested. diff --git a/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md b/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md index 20f720ee6..585a96afd 100644 --- a/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md +++ b/initiatives/spark_and_mlflow/33-sm29-auto-champion-validation-report.md @@ -2,6 +2,9 @@ Date: 2026-09-24. Branch: `090`. +Live closure: **PASS** for the selected Polars/serverless workflow. See +[SM-27/SM-29 live evidence](35-sm27-sm29-live-validation-report.md). + ## Local result The Bundle offers `pinned_version` and `auto_champion`. Automatic mode @@ -35,13 +38,15 @@ not a silent alias rollback. - A fresh `uv build --wheel --no-build-isolation` succeeded. Focused Ruff check/format, ty, `git diff --check` and `mkdocs build --strict` passed. The CLI projects were generated from the final template and validated - read-only; their jobs have not been deployed or run. - -## Live validation still needed - -In an isolated personal-workspace schema, test first champion, a passing v2, -an ineligible v3, the train-to-score job handoff, and both append/rebuild -scoring policies. Confirm model-version values in predictions, old-generation -retention, view activation, queued score behavior, a failed-score retry, and -the alias-write privilege boundary. Do not deploy to company targets until -their hosts, catalogs and grants are configured and validated. + read-only. The separate approved rehearsal subsequently deployed and ran + the generated project as recorded in the live report. + +## Live validation completed + +The isolated personal-workspace rehearsal passed first champion, improved +v2, ineligible v3, automatic train-to-score handoff and both scoring modes. +It verified model-version metadata, retained v1 output, v2 view activation, +queued no-op scores, expected score failure/retry and a restricted principal's +real alias-write denial. Production still requires an exclusive serialized +alias-writer identity; the personal test does not prove every administrative +principal is excluded. Company targets remain unconfigured and untested. diff --git a/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md b/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md index c7b4f54f8..75dbffa6e 100644 --- a/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md +++ b/initiatives/spark_and_mlflow/34-sm27-sm29-live-rehearsal-plan.md @@ -1,6 +1,7 @@ # SM-27/SM-29 isolated live rehearsal -Status: awaiting approval for personal-workspace resources and serverless runs. +Status: approved by the user and completed on 2026-09-24; see +[live evidence](35-sm27-sm29-live-validation-report.md). Catalog: `workspace`; proposed schema: `skyulf_sm27_sm29_20260924`. Profile: `skyulf`; target: `dev`. Company targets are out of scope. diff --git a/initiatives/spark_and_mlflow/35-sm27-sm29-live-validation-report.md b/initiatives/spark_and_mlflow/35-sm27-sm29-live-validation-report.md new file mode 100644 index 000000000..20af1c960 --- /dev/null +++ b/initiatives/spark_and_mlflow/35-sm27-sm29-live-validation-report.md @@ -0,0 +1,154 @@ +# SM-27/SM-29 live validation + +Date: 2026-09-24. Profile: `skyulf`; personal workspace; `dev` only. +Implementation commit: `68f64935`; approved rehearsal plan: `556b63f3`. +Status: **PASS for the selected bounded Polars/serverless workflow**. + +This is a functional lifecycle gate, not certification of production access +isolation. Both jobs ran as the same human owner. An exclusive production +alias writer remains a deployment precondition; concurrent train runs were +not exercised. Live contention evidence covers score requests only. + +Databricks CLI: 1.17.0. Jobs used serverless environment 4 with +`mlflow==3.16.1` and the built `skyulf-core==0.9.0` wheel. Wheel SHA-256: +`ceb609354c9ab4fca0fee5bd7c740f68958d6dce5d0b48a8aeceabe622925414`. +The local two-engine precheck used Python 3.12.10, pandas 2.3.2, +Polars 1.44.1, MLflow 3.16.1 and scikit-learn 1.8.0. Those local package +versions are not a measurement of the remote serverless environment. + +## Observed behavior + +The generated Bundle deployed exactly two persistent jobs, train +`1106811466161550` and score `793298964293930`. Both have concurrency one, +queueing enabled and a 900-second test timeout. Deployment created no schema, +table or model: CLI schema lookups before and immediately after deployment +reported the schema absent. Those observations were recorded in the session +transcript, not archived as separate API responses. The separate ephemeral +setup run then created +`workspace.skyulf_sm27_sm29_20260924.source`, a CDF-enabled Delta table. + +The test used 120 fit rows and 40 temporal holdout rows from source version +zero, a Skyulf `StandardScaler` and `linear_regression`, fitted with Polars. +The deterministic target was `10 + 4 * feature_value`. v1 omitted the model +intercept; v2/v3 included it. The heldout RMSE gate was `500.0` and minimum +improvement `0.1`, deliberately chosen for this controlled synthetic test, +not as production recommendations. All six regression metrics were logged +in each candidate's MLflow training run. + +| Model | Heldout RMSE | Selection result | +| --- | ---: | --- | +| v1 | 148.375 | Passed the first-model absolute gate; initialized champion | +| v2 | 3.1776437161565094e-15 | Improved by more than 0.1; staged, promoted and retained v1 as previous champion | +| v3 | 3.1776437161565094e-15 | Equal performance; rejected with `insufficient_improvement` | + +To test recovery, v2 training intentionally configured full rebuild against +the existing physical append-table name. Promotion succeeded; scoring +rejected the table/view conflict before writing. The independent audit found +both original outputs still at 160 v1 rows and Delta commit one, while +champion was v2. Correcting only the scoring target and rerunning score +created the complete v2 generation, then switched the view. No retraining or +alias rollback was needed. The two FAILED run entries below are this expected +negative test, including the serverless retry of its score task. + +After ten new source inserts, the final independent audit and local assertions +verified: + +| Object | Final state | +| --- | --- | +| `source` | 170 rows | +| `predictions_append` | 170 unique keys: 160 v1 predictions plus ten v2 predictions; Delta commit two | +| `predictions_full_v1` | Original 160 v1 rows, sum and Delta commit unchanged | +| `predictions_full_v2` | All 170 rows predicted with v2; Delta commit two | +| `predictions_full` | Stable view selecting `_v2`, 170 unique keys, original SELECT grant preserved | +| `model` | `champion=2`, `previous_champion=1`, no challenger or pending alias event | + +The v2 table/view predictions matched the deterministic target to an absolute +error below `1e-8`. Physical generation properties matched the corresponding +registered artifact digests. Initial, challenger and promotion receipts were +committed. Rejected v3 triggered scoring with the unchanged champion; it was +a no-op. Two additional simultaneous score requests completed serially; the +second was observed queued. Neither added a Delta commit. + +## Live run evidence + +| Purpose | Run | Result | +| --- | --- | --- | +| Create the isolated 160-row CDF source | [994289042356535](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/435128515818943/run/994289042356535) | SUCCESS | +| First champion and automatic score handoff | [734876178121464](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1106811466161550/run/734876178121464) | SUCCESS | +| Write 160 v1 append predictions | [1077735115421974](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/1077735115421974) | SUCCESS | +| Create 160-row v1 generation and view | [469943013477365](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/469943013477365) | SUCCESS | +| Promote v2; expected dependent scoring failure | [965294795399239](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1106811466161550/run/965294795399239) | FAILED | +| Reject full-rebuild target using a physical table name | [619154417488](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/619154417488) | FAILED | +| Verify v1 outputs survived while champion became v2 | [868165136083032](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/490825661254282/run/868165136083032) | SUCCESS | +| Deny alias write by the read-only principal | [513771267496014](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/363313111655727/run/513771267496014) | SUCCESS | +| Retry score and activate complete 160-row v2 generation | [66863176859812](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/66863176859812) | SUCCESS | +| Append ten new source rows and audit | [1116599148703461](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/692533573335489/run/1116599148703461) | SUCCESS | +| Append only ten v2 predictions to the mixed-version target | [340142551545850](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/340142551545850) | SUCCESS | +| Append ten rows to the active v2 generation | [746243399428598](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/746243399428598) | SUCCESS | +| Reject equal-quality v3 and retain champion v2 | [185130188901742](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/1106811466161550/run/185130188901742) | SUCCESS | +| Automatic no-op score after rejected candidate | [225986416024048](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/225986416024048) | SUCCESS | +| First concurrent no-op score request | [980883336179936](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/980883336179936) | SUCCESS | +| Second score request waits then completes | [680565312006506](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/793298964293930/run/680565312006506) | SUCCESS | +| Verify final rows, predictions, aliases, metrics and receipts | [36123647896664](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/91117816108119/run/36123647896664) | SUCCESS | + +## Permission and runtime boundary + +The existing restricted principal `skyulf-sm16-restricted-20260922` received +only schema traversal, model EXECUTE and test-notebook read access. It read +champion v2, received `PERMISSION_DENIED` when trying to assign v1, and still +read v2 afterward. Its SELECT grant on the stable view survived `ALTER VIEW`. +This verifies the selected restricted identity, not every possible workspace +administrator. The Bundle's table-free alias coordination still requires an +exclusive serialized writer identity in each production deployment. UC alias +management requires model ownership; model execution alone does not permit +alias changes. See the official [model lifecycle permissions](https://docs.databricks.com/gcp/en/machine-learning/manage-model-lifecycle). + +This rehearsal used Polars for remote FE/model execution and Spark for UC +table I/O. The same deterministic pipeline was checked locally with pandas +and Polars and produced identical v1/v2/v3 metrics. This does not establish +all models, policy clusters, company targets, Spark-native FE, streaming, +source updates/deletes, or multi-writer publication. The template's existing +explicit bounds and insert-only source contract remain in force. + +No production resource was changed. The approved test schema, model, source, +two prediction outputs (append table and full view with retained generations), +two persistent Bundle jobs and audit notebooks remain for user inspection. +The train job has no active schedule. Temporary setup/audit/permission runs +did not add persistent Bundle jobs. + +## Verification and corrections + +Raw run outputs, assertions, wheel and the generated Bundle are retained +locally under `initiatives/spark_and_mlflow/rehearsals/sm29_20260924/` +(ignored by Git). The commands below show the original execution paths +before that local archive move. + +Commands used from the repository root or generated project as appropriate: + +```text +uv build --wheel --no-build-isolation --out-dir .tmp-sm29-live/wheel skyulf-core +databricks bundle init skyulf-core/templates/databricks --config-file .tmp-sm29-live/init.json --output-dir .tmp-sm29-live/generated +databricks bundle validate --strict -t dev --profile skyulf +databricks bundle deploy -t dev --profile skyulf +databricks bundle run train --no-wait -t dev --profile skyulf +databricks bundle run score --no-wait -t dev --profile skyulf +databricks jobs submit --no-wait --json @ --profile skyulf -o json +.venv/Scripts/python.exe .tmp-sm29-live/verify_local.py +.venv/Scripts/python.exe .tmp-sm29-live/validate_evidence.py +.venv/Scripts/mkdocs.exe build --strict --site-dir .tmp-sm29-live/site +``` + +- The implementation's 94-test local gate and signed commit passed before + deployment; no library or generated-workflow fix was needed during this + live rehearsal. +- The current wheel built successfully; strict generated-Bundle validation + passed. English usage docs now explain absolute metric differences, first + champion bootstrap evidence and scoring-only recovery; strict MkDocs passed. +- Live evidence assertions checked counts, uniqueness, metric gates, model + versions, aliases, committed receipts, generation digests, prediction values, + failure preservation, retries, no-op commits and view grants. +- Test tooling corrections: PowerShell UTF-8 BOM initially prevented a local + submit JSON from parsing (no remote run was created); the audit changed from + search-result tags to concrete `get_model_version(...).tags`; the poller + learned to collect failed `INTERNAL_ERROR` run outputs. These affected test + reporting only and were corrected before the final audit. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index a22c9ead7..9578f53ae 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,19 +1,35 @@ # Session handoff - 2026-09-24 -## Current state after SM-28b +## Current state after SM-27/SM-29 + +The combined personal-workspace live rehearsal passed; SM-27 and SM-29 are +DONE for the documented bounded Polars/serverless workflow. v1 initialized +champion, improved v2 replaced it, and tied v3 was rejected. Append output +contains 160 v1 plus ten v2 predictions; full output exposes all 170 v2 rows +while retaining v1. Expected score failure, recovery, queued no-op runs, +committed alias receipts and restricted-principal write denial passed. See +[the final live report](35-sm27-sm29-live-validation-report.md). + +Retain `workspace.skyulf_sm27_sm29_20260924`, the two `skyulf_sm29_verify` +jobs and their audit notebooks for user inspection. No schedule is active. +Production still requires exclusive alias-writer ownership and serialized +target publication. Company targets and policy compute remain unverified. +Spark expansion and endpoint tasks remain later; do not treat this selected +local-engine rehearsal as broad Spark coverage. The notes below preserve the +earlier local delivery state. SM-29 now has an optional `auto_champion` Bundle selection. It asks for a heldout metric, minimum improvement and absolute quality threshold, uses the existing guarded alias receipts, and calls the serialized score job after train. Manual selection remains the default. Generated manual/automatic -serverless projects passed strict CLI validation. Live alias-to-Delta evidence -is pending, so keep SM-29 ACTIVE; see +serverless projects passed strict CLI validation. This local phase was followed +by the completed live rehearsal above; see [SM-29 validation](33-sm29-auto-champion-validation-report.md). SM-27 implementation now exposes append-vs-full-rebuild model-change scoring at Bundle initialization and editable paused-retraining cron/timezone variables. Generated-project CLI validation passed, but an actual v1-to-v2 -full-rebuild job has not run. Keep SM-27 ACTIVE until that live test verifies +full-rebuild job had not run at that point. The live rehearsal above now verifies the versioned physical tables and stable view; see [SM-27 validation](30-sm27-model-change-validation-report.md). @@ -23,8 +39,8 @@ score creates only the prediction table; see paused monthly schedule to that same `train` job. Manual and monthly generated projects passed strict CLI validation; no monthly live job was deployed or run. See [SM-28b validation](28-sm28b-monthly-retraining-validation-report.md). -The next open item is the combined live SM-27/SM-29 verification of model -selection and both scoring modes. Company workspace targets +The combined live SM-27/SM-29 verification of model selection and both scoring +modes is now complete. Company workspace targets remain unconfigured and unverified. The remainder of this file is historical context from earlier Bundle stages. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index f311491f3..4b4e7b3d4 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,8 +1,12 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b and SM-20a/20R/20S complete. SM-27 and SM-29 are active before Spark. Target: 0.9.0.** -Next deliverable: live proof for selectable local rescoring and automatic -champion selection. Spark +Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b, SM-20a/20R/20S and SM-27/29 complete for their documented scopes. Target: 0.9.0.** +The pre-Spark local Bundle lifecycle gate passed live: selectable rescoring, +automatic champion selection, failed-score recovery and serialized handoff. +This is functional completion for the selected workflow. Production must +still enforce one exclusive alias writer; both test jobs used a human owner, +and live contention was exercised for score requests, not concurrent trains. +See [the combined live evidence](35-sm27-sm29-live-validation-report.md). Spark expansion follows the validated first Bundle. SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -59,8 +63,8 @@ SUPERSEDED = replaced by a later user-directed scope; not a completed feature. | SM-28b | Optional monthly retraining schedule | SM-20S, SM-28a | DONE | Two-job Bundle with optional paused train schedule, pinned monthly label window/version and explicit activation; [plan](27-sm28b-monthly-retraining-plan.md), [validation](28-sm28b-monthly-retraining-validation-report.md) | | SM-24b | Optional Databricks Jobs API operations | SM-20a | LATER | Add dynamic submit/status/cancel only if Bundle jobs are insufficient | | SM-24d | Hard transport budget for wide UC rows | SM-24a | LATER | Add a proven paged/size-limited source adapter when exact transfer-byte enforcement is required; current Spark iterator bounds accepted decoded rows and frame memory only | -| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | ACTIVE | Both modes and editable cron implemented; generated Bundle validation passed; live v1/v2 scoring/view proof pending; [plan](29-sm27-model-change-scoring-plan.md), [validation](30-sm27-model-change-validation-report.md) | -| SM-29 | Gated automatic champion and score handoff | SM-22a/b/c, SM-28a/b, SM-27 | ACTIVE | First and later champion gates, existing two-job handoff and alias-pinned scoring implemented locally; live UC alias/score proof pending; [design](31-sm29-auto-champion-design.md), [plan](32-sm29-auto-champion-plan.md), [validation](33-sm29-auto-champion-validation-report.md) | +| SM-27 | Full-history local rescore and selectable Bundle mode | SM-20a, SM-15L | DONE | Live append retained 160 v1 rows and added ten v2 rows; full view exposes 170 v2 rows, retains v1 and its SELECT grant; [plan](29-sm27-model-change-scoring-plan.md), [live evidence](35-sm27-sm29-live-validation-report.md) | +| SM-29 | Gated automatic champion and score handoff | SM-22a/b/c, SM-28a/b, SM-27 | DONE | Live first champion, v2 promotion, tied v3 rejection, two-job handoff, score-failure recovery, queue/no-op and restricted alias-write denial passed; [design](31-sm29-auto-champion-design.md), [live evidence](35-sm27-sm29-live-validation-report.md) | | SM-19 | Optional live HTTP / SQL ai_query / endpoint operations | SM-20a, compatible pyfunc package | LATER | Add only after serving parity; streaming remains parked | | SM-21 | Optional Databricks feature tables / online lookup | SM-20a; SM-19a for online serving | LATER | Point-in-time lookups and optional online freshness; declare any Spark dependency | | SM-23 | Optional monitoring and inference observability | SM-20a, relevant batch/serving adapter | LATER | Existing Skyulf metrics + optional Databricks monitoring/inference tables | @@ -76,6 +80,24 @@ wires their optional monthly schedule after the Bundle exists. SM-27 remains post-Bundle and independent. Endpoint, feature lookup and monitoring remain optional; broad Spark expansion follows the local Bundle. +## SM-27/SM-29 closure record - 2026-09-24 + +Implementation inspected: `68f64935`; approved test plan: `556b63f3`. +The selected Polars/serverless generated Bundle passed first-champion +initialization, improved v2 promotion, tied v3 rejection, both scoring +policies, failed-score recovery, queued no-op requests and a restricted +principal's real alias-write denial. Final rows: append 160 v1 + ten v2; +full view 170 v2; retained v1 generation unchanged. Exactly two persistent +test jobs and no admission table. The English +[live report](35-sm27-sm29-live-validation-report.md) records every run URL, +expected negative runs, exact commands, wheel hash, runtime configuration +and scope limits. Strict Bundle validation, wheel build, local pandas/Polars +precheck, live-evidence assertions and strict docs build passed. The prior +94-test implementation gate is preserved in the SM-29 local report. +No library fix was required by this rehearsal. Source updates/deletes, +company targets, policy compute and broad Spark execution remain outside +this evidence. Production must still enforce one serialized alias writer. + ## Local-first path to the first Bundle These tasks were identified in the reference review; the latest user direction From fcfcee3106038bade8610b7a957776ea8d8f9e34 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 22:39:26 +0300 Subject: [PATCH 56/85] feat: retain challengers and extract reusable bundle workflows Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 14 + docs/user_guide/databricks_bundle.md | 53 +- docs/user_guide/mlflow_registry.md | 19 +- .../04-databricks-integration-plan.md | 5 + ...ndle-reference-comparison-and-readiness.md | 202 +++++ .../37-local-bundle-improvement-program.md | 331 +++++++ .../38-model-selection-and-approval-design.md | 136 +++ ...erving-and-feature-lookup-delivery-plan.md | 29 + .../40-sm30-challenger-validation-report.md | 71 ++ ...-company-tags-and-clean-live-validation.md | 90 ++ .../42-sm31-refactor-plan-and-evidence.md | 55 ++ initiatives/spark_and_mlflow/HANDOFF.md | 51 ++ initiatives/spark_and_mlflow/OPEN_QUEUE.md | 79 +- .../databricks/local_retraining.py | 44 +- .../integrations/databricks/local_workflow.py | 345 ++++++++ .../databricks/prediction_output.py | 192 +++++ .../skyulf/integrations/mlflow/challenger.py | 133 +++ .../skyulf/integrations/mlflow/promotion.py | 168 +++- .../skyulf/integrations/mlflow/registry.py | 4 +- .../databricks_template_schema.json | 11 +- .../examples/paying-reg-no-init.example.json | 17 + .../template/{{.project_name}}/README.md.tmpl | 36 +- .../config/workflow.json.tmpl | 1 + .../{{.project_name}}/src/workflow.py | 478 +--------- .../test_databricks_local_retraining.py | 21 + .../test_databricks_local_workflow.py | 813 ++++++++++++++++++ .../integrations/test_mlflow_promotion.py | 206 ++++- .../test_bundle_challenger_lifecycle.py | 104 +++ .../integration/test_sm20a_bundle_template.py | 742 +--------------- .../test_sm31_notebook_boundary.py | 87 ++ 30 files changed, 3303 insertions(+), 1234 deletions(-) create mode 100644 initiatives/spark_and_mlflow/36-bundle-reference-comparison-and-readiness.md create mode 100644 initiatives/spark_and_mlflow/37-local-bundle-improvement-program.md create mode 100644 initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md create mode 100644 initiatives/spark_and_mlflow/39-serving-and-feature-lookup-delivery-plan.md create mode 100644 initiatives/spark_and_mlflow/40-sm30-challenger-validation-report.md create mode 100644 initiatives/spark_and_mlflow/41-company-tags-and-clean-live-validation.md create mode 100644 initiatives/spark_and_mlflow/42-sm31-refactor-plan-and-evidence.md create mode 100644 skyulf-core/skyulf/integrations/databricks/local_workflow.py create mode 100644 skyulf-core/skyulf/integrations/databricks/prediction_output.py create mode 100644 skyulf-core/skyulf/integrations/mlflow/challenger.py create mode 100644 skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json create mode 100644 skyulf-core/tests/integrations/test_databricks_local_workflow.py create mode 100644 tests/integration/test_bundle_challenger_lifecycle.py create mode 100644 tests/integration/test_sm31_notebook_boundary.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 7bef69b40..1499d9b04 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -10,6 +10,20 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed +- Bundle initialization accepts an optional business risk label and documents + the PayingRegNo cost-tag choice. New lifecycle receipts use from_version; + older from and compact receipts remain readable. +- Generated Bundle notebooks delegate to reusable local workflow and prediction + output services in Core. Training, both scoring policies and target checks + retain their behavior; the notebook only handles widgets, JSON and results. +- Training uses separate company-compatible data/model tags and an optional + risk category. Dataset identity moves to a run artifact; validation reasons + and lifecycle receipt fields use readable English, retaining old receipt support. +- Bundle training nominates every registered contender as `challenger` before + comparison, retains rejected contenders with validation status/reason, and + records comparison failures. Promotion remains gated; pinned scoring stays + unchanged. Rollback preserves a separately verified contender. Generic Core + training opts into this behavior through an explicit registration callback. - The local-engine Bundle template exposes editable `dev/test/syst/prod` targets with separate host/catalog bindings and a serverless or policy-backed compute choice. Its source lives in `skyulf-core/templates/databricks`. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index b92927fe7..ad377afee 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -26,6 +26,31 @@ personal-workspace value is built into those three targets. Policy-backed compute uses the policy name, runtime, node type and cost tag supplied at initialization. Serverless compute needs none of those fields. +For a company policy requiring `PayingRegNo`, select that value as +`cost_tag_key` and supply the approved registration number as `cost_tag_value`. +The `paying-reg-no-init.example.json` example demonstrates both settings; +the generic default remains `CostCenter`. This tag applies to policy-cluster +compute. Selecting it does not assign a model risk category. + +Initialization also asks for an optional `risk_category`, such as `Low`, +`Medium`, or `High`. Leave it blank to omit the tag. The value remains editable +in `config/workflow.json` and is recorded on future training runs and model +versions; it does not change promotion gates or relabel existing versions. + +## Where the workflow lives + +The generated `src/workflow.py` reads job widgets and JSON, calls the installed +library, and serializes its result. Reusable behavior lives in +`skyulf.integrations.databricks.local_workflow`: `resolve_target_config` binds +target names and `run_action` executes train, train_monthly or score. +`prediction_output` validates and creates output tables and safely switches +full-rebuild views. Both reuse the existing training, inference and registry +services. Importing them does not create a Spark session or cloud resource. + +Edit the business pipeline in `config/workflow.json`. Model/preprocessing +choices remain project configuration; common workflow fixes ship in the +Skyulf wheel instead of requiring edits to every generated notebook. + ## What is created `bundle deploy` creates only two jobs and uploads their code: @@ -50,9 +75,33 @@ minimum. A passing candidate is staged and promoted through checked registry receipts; an ineligible candidate leaves champion unchanged. The train job then calls the existing score job. No third job or control table is added. +In both modes, registration nominates `@challenger` before comparison. A tied +or worse candidate retains that alias with `validation_status=rejected` and +a reason; comparison errors retain it with `validation_status=error`. +New contenders replace the pointer without deleting earlier version evidence. +Manual mode records these results without promotion or changing pinned scoring. +Training resolves the current champion; a stale explicit `champion_version` +fails before fit. Generic Core training remains alias-free unless a caller +supplies the explicit `on_registered` lifecycle callback. + +Training runs and model versions share readable metadata: `train_data_version`, +`test_data_version`, `train_data_destination`, `test_data_destination`, +`model_type`, `candidate_date_tag`, and `engine`. Optional `risk_category` is +editable in workflow.json. Since fit and evaluation split one Delta snapshot, +their table names and versions match; `train_start`, `test_start`, and +`data_end` explain the split. The exact dataset identity is saved in +`training_data.json`. Run tags use `task=training`. + +Validation reasons use plain English. Technical event tags retain unique IDs +and evidence hashes for rollback/recovery; their JSON fields are `action`, +`from_version`, `proof`, `parent`, `state`, and `previous`. `from_version` +identifies the version previously held by the affected alias, not necessarily +the previous champion. These are audit records, +not settings to edit. Earlier compact receipts remain supported. + In automatic mode, score resolves `@champion` once to a concrete version per -run. Only the serialized train job identity may write this model's aliases; -other alias-write grants must be removed before enabling this table-free mode. +run. In both modes, only the serialized train job identity may write this +model's aliases; other alias-write grants must be removed before training. Alias promotion and Delta scoring are separate transactions. If scoring fails after promotion, the last successful prediction output remains and the score job must be retried. Unknown alias outcomes need receipt reconciliation. diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 71fa23116..ca3b983f8 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -176,12 +176,22 @@ follows before Bundle generation. ## Stage, promote, and roll back a local pipeline -After a successful comparison, stage_challenger re-evaluates the same pinned -holdout and assigns the concrete candidate version to `@challenger`. It does +After a comparison, stage_challenger re-evaluates the same pinned +holdout and assigns the concrete candidate version to `@challenger`, even +when it fails the promotion gate. It records validation status and reason and does not move `@champion`. A replacement challenger requires an explicit `expected_challenger_version`; staging cannot silently overwrite another candidate. Merely registering or comparing a model never assigns an alias. +An orchestrator can explicitly create `ChallengerLifecycle` from +`skyulf.integrations.mlflow.challenger` and pass its `registered` method as +`train_local_candidate(..., on_registered=...)`. This nominates a registered +contender before comparison, with `validation_status=pending`. After evaluation, +`stage_challenger` records `passed` or `rejected`; `lifecycle.failed()` records +`error` for a still-pending comparison without overwriting a completed result. +The caller must use the same serialized alias writer for all these operations. +An uncertain registry write keeps its pending receipt and requires reconciliation. + The promote_candidate function re-resolves both concrete model versions and re-evaluates the same bounded labeled holdout. It rejects a changed comparison report, an ineligible candidate, a missing champion alias, a stale expected @@ -266,8 +276,9 @@ concrete model versions, event ID, and the previous value of `@previous_champion`. Rollback verifies the committed promotion event, restores `@champion` and the previous rollback pointer, and does not reinstate the rolled-back model as challenger. A prior release's single-alias -promotion receipt remains reversible. A staged newer challenger blocks -rollback until the operator reconciles it. +promotion receipt remains reversible. A separate challenger with a verified +committed lifecycle event survives rollback unchanged. An unverified alias, +or one pointing at the champion or rollback destination, still blocks rollback. MLflow performs these alias changes as separate calls, not one atomic transaction. If a later call fails after an earlier alias moved, the operation diff --git a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md index 110d96b93..bffee83c8 100644 --- a/initiatives/spark_and_mlflow/04-databricks-integration-plan.md +++ b/initiatives/spark_and_mlflow/04-databricks-integration-plan.md @@ -1,5 +1,10 @@ # Local-first Databricks integration and Bundle plan +Current sequencing update (2026-09-24): the first local Bundle has been +validated. The user now prioritizes [SM-30 through SM-43 improvements](37-local-bundle-improvement-program.md) +before broad Spark work. [OPEN_QUEUE.md](OPEN_QUEUE.md) is authoritative; +the earlier baseline and first-Bundle plan below are historical context. + Updated: 2026-09-23. SM-26, SM-25, SM-24a, SM-15L and SM-15I are implemented and validated for their documented scopes; the first Bundle remains planned. Baseline: `63dd3e21` and the completed, scoped SM-16 evidence. diff --git a/initiatives/spark_and_mlflow/36-bundle-reference-comparison-and-readiness.md b/initiatives/spark_and_mlflow/36-bundle-reference-comparison-and-readiness.md new file mode 100644 index 000000000..4bdab7d16 --- /dev/null +++ b/initiatives/spark_and_mlflow/36-bundle-reference-comparison-and-readiness.md @@ -0,0 +1,202 @@ +# Local Bundle comparison and readiness review + +Date: 2026-09-24. Skyulf baseline: `7c3a0866`. +Reference: `C:/Users/Murat/Downloads/codes-main (2)/codes-main/dbml-mlops-template`. + +Follow-up: the user approved the improvements and corrected the desired +challenger meaning. The current code observations below remain historical; +the [approved program](37-local-bundle-improvement-program.md) and +[selection/approval design](38-model-selection-and-approval-design.md) define +the next behavior. In particular, a rejected contender will retain challenger +alias; challenger assignment will no longer require promotion eligibility. + +This is a static comparison of the initialization schema, generated project +configuration, job resources, lifecycle services, inference, deployment, +monitoring and CI/CD entry points. The reference was not deployed or executed. +Its classification and example projects were inventoried; the regression +skeleton was the primary implementation inspected. This is not a claim that +every file or optional scenario in the reference has been tested. + +Skyulf's prior live evidence is in +[the SM-27/SM-29 report](35-sm27-sm29-live-validation-report.md). +No cloud resources were changed during this review. + +## Readiness decision + +The existing local-engine Bundle is a working foundation for a supervised +small-data batch pilot. It is not yet a turnkey company production package. +Personal serverless validation does not establish company policy-compute, +service-principal, data-access or deployment-approval readiness. + +Production prerequisites for this scope are real source/label/key contracts, +business-defined quality gates, supported data volumes, CDF availability, +explicit job identities and grants, a single serialized alias writer, score +scheduling and operational recovery. Serving, feature-store integration and +Spark-native FE are optional extensions, not prerequisites for this batch use case. + +## What v3 and manual selection mean today + +- v3 is registered and evaluated, but its improvement over v2 is zero. The + automatic workflow returns before `stage_challenger`, so v3 has no alias. +- In this implementation, `challenger` means a validated candidate eligible + to replace champion, not simply the most recently trained version. A passing + automatic candidate is staged then promoted immediately, so the challenger + alias is transient. A version's durable result is in its training run and + `candidate_comparison.json`; readable status tags on rejected UC versions + are a usability gap. +- `pinned_version` scores the concrete `model_version` in deployed JSON. + Training does not change that value or automatically invoke score. Edit the + version, deploy the configuration and run the existing score job. The model + artifact is loaded from MLflow; it is not rebuilt or uploaded again. +- `auto_champion` resolves a controlled champion once at the beginning of + each score run and pins that version. A later approved promotion is picked + up by the next run without redeploying score code. A running score keeps + its pinned version. The input/output contract must remain compatible. +- Direct Catalog UI alias edits bypass Skyulf's receipt records. They can + cause automatic scoring to stop with an alias/receipt conflict; this is + stricter than plain MLflow alias loading. +- Manual stage/promote/rollback APIs exist in the library, but a convenient + manual-approval Bundle action is not implemented. Staging and promotion + still require valid comparison evidence; the current APIs do not turn a + rejected tie into an approved champion by operator preference alone. + +Recommended extension, not current functionality: separate model selection +from promotion policy. Keep pinned scoring and controlled champion scoring; +allow promotion to be automatic or explicitly approved. A manual action should +reference an existing version, recheck evidence, write the same receipt and +invoke the existing serialized score job without retraining. It must share +the alias-writer serialization path rather than introduce a competing writer. +Any deliberate quality-gate override needs its own explicit policy and audit. + +## Quality gates + +`quality_threshold: 5.0` with `metric: heldout_rmse` means RMSE must be at most +5 target units on the held-out data. It is an example, not a percentage or a +classification probability threshold. With `heldout_accuracy`, a threshold +such as `0.90` means accuracy must be at least 90 percent instead. + +`min_improvement: 0.1` means an absolute metric difference of at least 0.1; +ties never pass even when the minimum is zero. If champion RMSE is 4.0, +candidate RMSE 3.8 passes both example gates; 3.95 fails the improvement gate. +The absolute gate applies to subsequent champions as well as initialization. +Many metrics are logged, but only one selected metric controls this decision. + +## Comparison + +"Present in reference" below means source/configuration was found, not that +its runtime behavior was validated in this review. + +| Capability | Reference template | Current Skyulf Bundle | Assessment | +| --- | --- | --- | --- | +| Project initialization | Classification/regression skeletons, examples, many infrastructure prompts | Generic local project; pandas/Polars, engine/compute/selection/scoring choices | Skyulf needs friendlier task, columns and pipeline setup | +| Core FE and model reuse | Project-specific feature notebooks and training services | Existing `SkyulfPipeline`, saved FE/model, local artifact and MLflow wrapper | Skyulf avoids reimplementing node/model behavior in each project | +| Small-data local execution | Local Python model training plus Spark-oriented inference | Bounded pandas/Polars fit/predict; Spark handles UC I/O | Selected Polars lifecycle live; both-engine local parity; not all nodes/models certified | +| Distributed batch inference | `spark_udf` and optional feature-store `score_batch` paths | Library Spark inference exists; first Bundle exposes local execution only | Intentional deferred Bundle extension | +| Metrics and model validation | MLflow evaluation, extra metrics, multiple thresholds and SHAP configuration | Core held-out metrics, one decision metric, absolute gate and minimum improvement | Multi-metric approval and explainability are not first-class Bundle options | +| Model search | Optuna, model list, search spaces and trial settings | Core tuning exists; template presents one `pipeline.modeling` configuration | Add an explicit tested tuning/model-search configuration, not duplicate trainers | +| Candidate visibility | Training sets `candidate`; validation stages `challenger` or bootstraps champion | Registered candidate plus comparison artifact; only eligible candidates get `challenger` | UC version status/rejection tags would improve Skyulf inspection | +| Promotion and rollback | Alias assignment and rolling-promotion services | Checked transitions, previous champion, committed receipts and rollback API | Skyulf has stronger explicit recovery checks; manual Bundle approval UX is missing | +| Prediction refresh | Date/backfill controls and optional champion/challenger rollout | CDF insert-only append or new complete model generation behind a stable view | Both Skyulf policies live-tested; updates/deletes and CDF-expiry recovery not covered | +| Retry/no new data | Project publication helpers | Commit-bound progress, duplicate checks, no-op, serialized score job | Skyulf retry/no-op and queue evidence is explicit | +| Resource footprint | Main workflow delegates to feature/train/validation/inference jobs; other optional jobs | Two jobs, no admission tables; full mode retains versioned tables plus a view | Keep the smaller default; retained generations need an eventual cleanup policy | +| Runtime parameters | Job parameters for dates, candidate version, smoke mode and model choices | Widgets read action/config/target; model version and gates come from deployed JSON | Missing convenient per-run model selection/approval parameters | +| Scheduling | Inference schedule example is commented; broader workflow resources | Optional paused train cron/timezone; score follows automatic training or runs explicitly | Add independent optional score cadence; new data alone does not launch a job | +| Multi-environment deployment | ci/test/syst/prod catalogs and developer suffixes | dev/test/syst/prod targets and output/model suffixes | Company hosts/grants/policies still require configuration and live validation | +| Compute and dependencies | Job cluster policies, cost tags, runtimes, requirement/lock files | Serverless or policy cluster, explicit wheel and MLflow pin | Version pinning is useful; packaging inputs, worker bounds and per-target compute need improvement | +| CI/CD and project tests | Generated GitHub workflows call company-managed pipelines; unit/integration suites | Repository tests and live proofs; generated project has no CI workflow or test scaffold | Production adoption gap; make generic CI with optional company adapters | +| Identities and operations | Resource permissions and company deployment integration | No generated run_as, notification, timeout or retry settings | Define target-specific identities/grants and operator settings; reference integration does not prove company readiness either | +| Serving and A/B rollout | Endpoint services, traffic configuration, rolling inference and load-test resources | No endpoint deployment/traffic controls in first Bundle | Deferred optional capability; batch-only production does not need it | +| Online feature lookup | Optional Feature Store/Lakebase path | Not in first Bundle | Deferred optional capability | +| Monitoring | Data-quality/model-performance jobs and dashboard resources | Core metrics/profiling exist; no deployed monitoring workflow | Start with failure alerts and scoring summaries; dashboards can follow | + +The reference is not free of configuration issues: the inspected regression +inference job repeats `feature_store_model_enabled` in its parameter list, +and test/syst/prod all use the same `input_test_workspace_host` template +value. It also contains explicit dataset/model placeholders. Copying it +unchanged would not supply the user's three company workspace hosts or a +validated business model. No production claim follows from file presence. + +## Configuration audit + +| Setting | Current surface | Recommendation | +| --- | --- | --- | +| Engine, key, metric, selection mode, model-change mode | Initialization prompts and generated JSON | Keep editable, add task-aware validation | +| Source/output/model names, features, label columns, preprocessing, model parameters | Generated `config/workflow.json` | Clearly mark required dataset edits; these are editable examples, not fixed library limits | +| Training snapshot and fixed dates | JSON defaults: version 0 and 2025 example windows | Require deliberate data-specific values before first deployment | +| Monthly lookback | JSON value 4; previous complete UTC month is holdout | Expose/document window policy; cron alone does not change the split algorithm | +| Row/memory budgets | JSON defaults: 10,000 rows, 64 MiB | Tune for real workload; this is not an exact network-byte or total process-memory cap | +| Metric gates | Initialization and deployed JSON | Add optional multiple guardrails; first keep task-compatible threshold examples | +| Per-run version/manual approval | No dedicated job parameter/action | Add validated run parameters and approval orchestration | +| Selection mode changes after generation | JSON plus generated job graph | JSON-only changes do not add/remove the auto score handoff task; validate consistency | +| Score cadence | No generated schedule | Optional score cron/timezone/pause setting, independent of training | +| Model/schema locations and environment hosts | Bundle target variables/placeholders | Keep per environment; do not hardcode company values into the generic template | +| Dependencies | Wheel `0.9.0`, MLflow `3.16.1`, serverless client 4 in resource template | Preserve reproducibility but centralize release/runtime inputs; upgrading a model does not require upgrading the wheel | +| Policy cluster workers | YAML constants 2 to 4 | Make configurable; worker scale does not distribute local pandas/Polars model execution | +| Concurrent runs = 1 and queue enabled | Job YAML | Keep as correctness constraints, not casual performance knobs | +| Champion/challenger/previous aliases and receipt format | Lifecycle library contract | Keep stable conventions unless a separate compatibility design justifies changes | +| Timeouts/retries/notifications/run_as | Missing from generated defaults | Add before unattended production; rehearsal-only 900-second limits are not template defaults | + +Bundle variables resolve during deployment; job parameters can be overridden +at execution. This distinction should drive the proposed configuration +surface. See [Databricks job parameter documentation](https://docs.databricks.com/aws/en/dev-tools/bundles/job-parameters). +Plain model aliases can redirect a future load without changing the inference +code; Skyulf adds its controlled transition check. See +[Databricks model lifecycle documentation](https://docs.databricks.com/aws/en/machine-learning/manage-model-lifecycle). + +## Workflow size and next order + +The generated `src/workflow.py` is 516 lines. It mixes notebook/widget I/O, +target binding, monthly windows, model lifecycle and prediction table/view +management. The concern is responsibility concentration, not a need for more +Databricks jobs. Keep two jobs and a short user-editable entry point; move +reusable orchestration and publication behavior into tested +`skyulf.integrations.databricks` modules. Keep business FE/model choices in +the project configuration and explicit extension points. + +Recommended next work before expanding Spark (proposals, not delivered features): + +1. Simplify that boundary with behavior-preserving tests and configuration validation. +2. Add manual approval of an existing candidate and readable candidate result tags; + keep all alias writes serialized and retain score-only recovery. +3. Add runtime version parameters and independent score scheduling, with explicit + compatibility checks between configuration and the generated job graph. +4. Add production identities, timeouts, failure notifications and generic project + CI/smoke checks, then validate on the approved company target and real data. +5. Add model-search/multiple-metric gates if required by the use case. Keep + serving, online features, broad monitoring and Spark expansion separately optional. + +## Meaning of QUEUED and no-op + +Two score requests targeted the same job. Concurrency one caused the second +to wait rather than write alongside the first. With no new source inserts, +the first produced `noop=true`: no predictions were appended and the output +Delta version stayed at 2. Here Delta version 2 is the table transaction +version, not model version 2. After the first run, the queued run also checked +for work. Rejected v3 training still triggered the existing score job because +training succeeded; that score used champion v2 and also found no new rows. +Queueing does not periodically check for new data or schedule future runs. + +## Verification in this review + +The focused Bundle/promotion suite initially had two failures caused by stale +test references to `skyulf_pending_alias_event`. The library and archived live +wheel both use `pending_alias_event`; their promotion module lines match. +Only those two test literals were corrected. No production code was changed. +The initial default temporary directory was inaccessible in the sandbox; +reruns used a dedicated repository-local pytest directory. + +- `tests/integration/test_sm20a_bundle_template.py` and + `skyulf-core/tests/integrations/test_mlflow_promotion.py`: **58 passed**. +- Ruff on the changed test file: **passed**. +- The earlier live run evidence remains historical; no new live execution + or company validation was performed in this review. + +Primary Skyulf code: `skyulf-core/templates/databricks/`, +`skyulf-core/skyulf/integrations/databricks/local_retraining.py`, +`local_batch.py`, `local_incremental.py`, and +`skyulf-core/skyulf/integrations/mlflow/{promotion,validation,local_model}.py`. + +Primary reference code: `databricks_template_schema.json`, regression +`databricks.yml.tmpl`, `config/{training,validation,inference}.yml.tmpl`, +`resources/jobs/`, `src/{training,validation,inference,deployment,monitoring}/`, +and generated `.github/workflows/`. diff --git a/initiatives/spark_and_mlflow/37-local-bundle-improvement-program.md b/initiatives/spark_and_mlflow/37-local-bundle-improvement-program.md new file mode 100644 index 000000000..328c9e031 --- /dev/null +++ b/initiatives/spark_and_mlflow/37-local-bundle-improvement-program.md @@ -0,0 +1,331 @@ +# Local Bundle improvement program + +Date: 2026-09-24. Target release: 0.9.0. +Status: SM-30 and SM-31 delivered; SM-32 next. Company-compatible tags and +SM-30 passed [clean live verification](41-company-tags-and-clean-live-validation.md). +See [SM-31 evidence](42-sm31-refactor-plan-and-evidence.md) for the extraction, +110 tests and successful deployed score notebook. Remaining tasks are planned. +Source review: [reference comparison](36-bundle-reference-comparison-and-readiness.md). +Execution authority: [OPEN_QUEUE.md](OPEN_QUEUE.md). + +## Outcome and boundaries + +Build a generic, maintainable pandas/Polars Databricks Bundle suitable for a +real small-data batch workload, with explicit model approval, predictable +prediction refresh, understandable configuration and production operations. +Reuse the existing Skyulf pipeline, evaluation, tuning, registry and publication +services. Do not copy the reference project's parallel implementations. + +Keep the default two persistent jobs, train/lifecycle and score. An approval +action uses the same serialized lifecycle job as training; it does not create +a second alias writer or retrain a registered candidate. Keep admission tables +out of the default Bundle. Keep English documentation and examples. + +The first local Bundle gate already passed for its documented scope. These +tasks extend that baseline; historical evidence must not be rewritten to claim +the new behavior was deployed. Company production readiness requires its own +identity, compute and real-data validation. Do not deploy to company workspaces +or activate schedules as a side effect of creating these tasks. + +Broad Spark execution, HTTP serving, ai_query, A/B, feature lookup and full +monitoring stay explicitly tracked after the local Bundle work. Backend/Canvas +and continuous streaming remain parked. Existing task IDs are reused for +those extensions rather than creating duplicate backlogs. + +## Decisions confirmed by the user + +1. Challenger means the latest successfully trained and registered contender, + not only a model that passed promotion gates. A tied or worse v3 remains + challenger while v2 remains champion. A newer v4 replaces the challenger + pointer; v3's evaluation history stays in its version/run records. +2. Challenger assignment and champion promotion are separate operations. + Evaluation failure or insufficient quality must never move champion. +3. Scoring selection and approval are independent configuration choices: + `score_model_selection = pinned_version | champion` and + `promotion_policy = manual_approval | automatic`. +4. Manual approval of an existing candidate does not train or republish its + artifact. It rechecks pinned evidence, records a controlled transition and + can call the existing score job. It does not bypass quality checks. +5. Append keeps historical predictions; full rebuild publishes a complete + generation for a different model. Both policies survive these changes. + +The proposed field names above become public only through SM-32/SM-33. +Existing `model_selection_mode` configurations need an explicit migration, +not silent reinterpretation. + +## Work packages and acceptance + +### SM-30 — Challenger identity and visible evaluation status + +Files: `skyulf-core/skyulf/integrations/mlflow/promotion.py`, +`skyulf-core/skyulf/integrations/databricks/local_retraining.py`, +`skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py`, +`skyulf-core/tests/integrations/test_mlflow_promotion.py`, +`skyulf-core/tests/integrations/test_databricks_local_retraining.py`, +`tests/integration/test_sm20a_bundle_template.py`. + +- Separate contender nomination from validated promotion. Preserve the + read-only comparison API and do not hide alias mutation inside generic fit. + The serialized lifecycle orchestrator owns nomination after registration. +- Publish `validation_status` (`pending`, `passed`, `rejected`, `error`) and + `validation_reason` on the model version; preserve the complete comparison + in the training run. A first candidate can pass its absolute gate even + though a relative report says `no_champion`. +- Persist `promotion_status` separately; evaluation is not activation. Keep + model-version status writes consistent with existing receipts and report + incomplete/unknown registry outcomes without claiming successful promotion. +- Handle no champion, rejected candidates, replacement of an existing + challenger, repeated nomination and failed evaluation. A stale version + must not displace a newer challenger without an explicit expected version. +- Revisit rollback's current refusal when any challenger exists: a retained + rejected challenger must not make recovery unusable. Preserve or explicitly + reconcile that pointer under the same writer; never silently lose evidence. +- Test real local MLflow versions: v1 -> v2 promotion, tied v3 retained as + challenger, v4 replacement, failed quality, evaluation error, stale writer, + partial tag/alias writes, rollback with retained contender. Check scoring + still uses champion and does not refit. +- Acceptance: the v3 UI explanation matches aliases plus durable status; + promotion checks remain strict. Local completion and UC verification are + recorded separately; SM-43a is the combined deployment gate. + +### SM-31 — Thin template and reusable orchestration + +Files: current template `src/workflow.py`; create +`skyulf-core/skyulf/integrations/databricks/local_workflow.py` for orchestration +and `prediction_output.py` for table/generation/view publication; retain +`local_retraining.py` as the training-window/data service. Add focused tests +under `skyulf-core/tests/integrations/`; retain generated-template tests. + +- Move reusable behavior out of the 516-line generated notebook. The notebook + reads widgets/config, calls the library and serializes its result. +- Preserve both engines, target binding, source bounds, aliases, row keys, + generation provenance, grant-preserving view switches and no-op commits. +- Keep business pipeline configuration and documented customization points in + the project. Avoid a new service layer per helper or duplicated model code. +- Acceptance: behavior-preserving tests for every existing action, installable + wheel import test and generated-project test; no extra persistent job/table. + +### SM-32 — Independent scoring selection and promotion policy + +Detailed contract: [policy design](38-model-selection-and-approval-design.md). +Files: `local_workflow.py`, `promotion.py`, template config/schema/job resources +and `docs/user_guide/databricks_bundle.md`. + +- Support all four policy combinations explicitly. Pinning a scoring version + must remain effective even when registry promotion is automatic. +- Add approve/reject/rollback lifecycle actions for concrete versions, using + the same serialized lifecycle job and authorized identity as training. +- Approval revalidates the saved dataset/version/split, model digest, metric + policy and expected champion. Rejected or stale evidence cannot promote. +- Champion-following score resolves the controlled alias once per run. + Approval can hand off to the existing score job without uploading model/code. +- Preserve score-only retry after a committed promotion. No implicit forced + approval or raw UI-alias adoption; unexpected aliases need reconciliation. +- Acceptance: four-combination tests, approval without fit/log/register calls, + rejected/stale/duplicate approvals, first champion, rollback and pinned-run + stability. Live validation occurs in SM-43a. + +### SM-33 — Validated configuration and runtime parameters + +Files: create `skyulf-core/skyulf/integrations/databricks/workflow_config.py`; +template `databricks_template_schema.json`, config, job YAML and entry point; +generated-project and configuration tests. + +- Separate environment variables, project/model configuration and per-run + inputs. Expose a concrete scoring-version override and lifecycle action, + candidate version and expected champion as validated run parameters. +- Add task-aware initialization for regression/classification, existing source + keys (including composite keys), features/target and editable pipeline. + Do not promise arbitrary FE can be inferred automatically. +- Validate metric/task/threshold compatibility, resource-name boundaries, + stale example dates/source version, incompatible key/schema changes and + model limits before expensive work or writes. +- Migrate `model_selection_mode` explicitly. Validate the generated job graph + against policy configuration; editing JSON alone must not silently change + the expected score handoff. +- Acceptance: strict generated Bundle validation, defaults/migration tests, + actionable negative tests and a per-run version change without redeployment. + +### SM-34 — Independent schedules and explicit training windows + +Files: template schema, job resources, target variables, workflow config and +`local_retraining.py`/`local_workflow.py`; schedule/window tests. + +- Add independent optional train and score Quartz cron/timezone/pause inputs; + start paused. Scoring new data must not require retraining or manual dates. +- Expose and document lookback, holdout duration and label-availability cutoff. + Preserve the existing monthly UTC behavior as an explicit default. Changing + cron must not silently imply a different data-split policy. +- Pin source snapshot and window per training run, including retry evidence. +- Test month/year boundaries, DST/timezones, score-only schedule, manual and + automatic promotion, no-new-data runs and queued overlap with train handoff. +- Acceptance: predictable scheduled jobs and clear distinction between + queueing, scheduling, data progress and model version. + +### SM-35 — Multiple quality gates and understandable metrics + +Files: MLflow `validation.py`, `promotion.py`, existing +`skyulf-core/skyulf/inference/local_evaluation.py`, workflow config and tests. + +- Keep one selection metric and add optional additional absolute guardrails; + reuse existing metric computation and direction definitions. +- Validate metric domains, finite values, class/probability availability and + task compatibility. Keep probability decision thresholds distinct from + model-quality thresholds. No generic default RMSE threshold for real data. +- Compare models on the identical held-out rows; keep minimum improvement + explicitly absolute. Explain every failed gate in run/version evidence. +- Acceptance: regression/classification gates, conflicting secondary gate, + tie, missing metric and first-champion tests; backward-compatible single gate. + +### SM-36 — Existing Core tuning and model search in the Bundle + +Files: `local_workflow.py`, `local_retraining.py`, existing +`skyulf-core/skyulf/pipeline/_pipeline.py` and `modeling/_tuning/` as consumers, +template configuration/examples and integration tests. + +- Expose an optional finite model list/search space/trial/time budget using + existing Core tuning, with train/validation/holdout separation and FE fitted + inside tuning folds where required. Do not optimize on the final holdout. +- Log configuration, trials, selected candidate and final metrics to MLflow. + Retain simple one-model training as the default. +- Add optional explainability artifacts only through existing supported + model APIs, with explicit cost/sample limits and capability checks. +- Acceptance: bounded regression/classification searches, no holdout leakage, + fitted preprocessing persistence and prediction parity for the selected model. + +### SM-37 — Deployment identities and enforced writer ownership + +Files: Bundle targets/job resources, configuration preflight, deployment guide +and identity/permission integration fixtures. + +- Configure environment-specific `run_as`, job permissions, model ownership, + source read and output write privileges, workspace roots and profiles. +- Keep lifecycle writes in one serialized job. Scoring identity executes the + registered model without owning its aliases. Model/API permissions and job + edit permissions must support the claimed exclusive-writer contract. +- Validate test/syst/prod host/catalog/schema mappings and development suffixes; + keep company values out of generic defaults. Preserve selected dev usability. +- Acceptance: intended writer succeeds, scoring/restricted principal cannot + change aliases, concurrent lifecycle requests queue, target isolation holds. + Personal and company evidence are separate; config presence alone is not proof. + +### SM-38 — Operations, retries and basic run visibility + +Files: job resources/variables, workflow result logging, docs and tests. + +- Expose job/task timeouts, bounded retries/backoff and failure notifications; + retain concurrency one and queueing as correctness requirements. +- Surface selected model, source snapshot/progress, input/output counts, + no-op reason, policy/gate decision and prediction generation without leaking + raw records. Reuse SM-23a metric contracts instead of a competing system. +- Document retry after failed score, interrupted publication, pending alias + receipt and permission failure. Do not silently retry uncertain promotion. +- Acceptance: failure injection and retry tests, no duplicate predictions or + unintended retraining, sanitized diagnostics, notification configuration. + +### SM-39 — Reproducible packaging and configurable compute + +Files: template artifact/dependency and compute resources, initialization +schema, release/build manifests and packaging tests. + +- Centralize compatible wheel/runtime/MLflow version inputs with pinned + dependencies; retain model artifact dependency requirements. +- Make policy-cluster worker bounds, approved policy/runtime/node/cost settings + configurable per target. Keep serverless dev validation available. +- Prefer a reproducible build/copy/validate path over manually editing wheel + filenames across resources. Distinguish model replacement from library upgrades. +- Acceptance: clean-environment install/load/score, matching wheel release, + serverless and policy target generation/strict validation. Live policy + compatibility remains part of the company gate. + +### SM-40 — Generated-project tests and generic CI/CD + +Files: generated `tests/`, dependency manifest, CI workflow/example adapter +and template documentation; existing repository template tests. + +- Generate project smoke/config/pipeline tests plus validate/build/test steps + that run outside this repository. Pin a release artifact for deployments. +- Provide generic dev/test/syst/prod promotion with explicit environment + approvals. Company managed-pipeline integration is an optional adapter, + not a hardcoded private dependency. +- Do not deploy or run chargeable jobs on pull requests by default. Document + scoped credentials, cleanup and how to add an authorized live test stage. +- Acceptance: a generated project passes its own CI locally and in the chosen + CI environment; company deployment is tested separately. + +### SM-41 — Source recovery and retained generation lifecycle + +Files: `local_incremental.py`, `local_publish.py`, `prediction_output.py`, +workflow config/operator actions and recovery tests. + +- Define explicit recovery for expired CDF history, source replacement, + changed keys/schema and oversized initial/full rebuilds. Fail before writes + when a supported recovery cannot be proven; do not silently reset progress. +- Add an explicit bounded full-refresh/recovery path with audit evidence; + define its interaction with the same model version and rollback. +- Define optional update/delete semantics separately from the insert-only + default; never present append mode as generic CDC support without tests. +- Add opt-in generation retention/cleanup preview. Never delete active or + protected rollback generations; deletion requires the scoped operator action. +- Acceptance: no duplicates/lost source progress, safe interrupted recovery, + preserved active view/grants, protected-generation tests and clear limits. + +### SM-42 — User-facing examples and first-run documentation + +Files: generated README/examples/config and `docs/user_guide/databricks_bundle.md`. + +- Provide editable regression and classification examples for pandas/Polars; + explain source keys, labels, artifact FE/model and UC object responsibilities. +- Walk through manual approval and automatic promotion, both output policies, + score-only reruns, rollback, scheduling and runtime version selection. +- Document which settings need redeploy, which are per-run, and which are + safety contracts. Explain RMSE units, quality versus probability thresholds, + challenger versus approval, model version versus Delta version and no-op. +- Acceptance: a clean generated project can follow the guide without editing + library code; commands and output expectations match tests and live evidence. + +### SM-43a / SM-43b — Final acceptance, not inferred readiness + +SM-43a: personal-workspace rehearsal after the local improvements. Exercise +both engines across representative regression/classification models, real +fitted FE, manual and automatic selection, retained failed challenger, +score-only new data, both output policies, retry/rollback and concurrency. +Use scoped resources and bounded compute; keep a resource/run inventory. + +SM-43b: company target rehearsal after actual profiles/hosts, catalogs/schemas, +run identities, policies and representative data are confirmed. Verify UC +access, policy compute, dependencies, CI deployment and operational ownership. +Do not guess or hardcode missing company identifiers. An unavailable company +environment does not prevent completion of the local engineering tasks. + +Acceptance for both: exact code/wheel/config identity, run IDs, metrics, rows, +aliases/statuses, grants, recovery results and limitations recorded. A written +plan, unit tests or personal serverless success cannot close the company gate. + +## Existing extension tasks retained + +| Existing task | Coverage retained from the comparison | Order | +| --- | --- | --- | +| SM-19a | HTTP endpoint deployment, pyfunc request/output parity and load/cold-start checks | After local Bundle acceptance | +| SM-19b | ai_query contract, named inputs, permissions and endpoint error handling | After compatible serving | +| SM-19d | A/B/canary traffic, endpoint updates, readiness and rollback; batch rollout only as a separate explicit option | After serving parity | +| SM-21a/b | UC feature lookup, point-in-time correctness, optional online publication/freshness | After local Bundle; online depends on serving | +| SM-23a/b | Batch quality/drift/delayed labels and endpoint monitoring/dashboard options | Basic operational summaries are SM-38; managed monitoring remains optional | +| SM-17/24c/20b | Existing node/model Spark coverage, Spark workflow and Bundle choice | After the local improvement gate | +| SM-24b/24d | Optional dynamic Jobs operations and exact transport budget | Only when current workflow/decoded-row bounds are insufficient | +| SM-18/19c | Backend/Canvas/legacy bridge and continuous streaming | Remain parked | + +## Coverage and completion rules + +The reference review's configuration, packaging, identity, CI, data recovery, +candidate visibility and workflow-size findings map to SM-30 through SM-43. +Its serving, online features and monitoring findings map to the existing +extension tasks above. No finding is treated as complete merely because a +related library primitive exists. + +For each task: reproduce the relevant missing behavior, write focused tests, +implement through existing services, update English examples/docs and record +commands/results. Run Ruff/type checks and relevant integration suites; run +strict generated Bundle validation when configuration changes. Record local +implementation and live validation separately. Update OPEN_QUEUE and HANDOFF +after each verified slice. Do not mark the whole program done after SM-30. diff --git a/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md b/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md new file mode 100644 index 000000000..97a2081f3 --- /dev/null +++ b/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md @@ -0,0 +1,136 @@ +# Independent model selection and approval + +Date: 2026-09-24. User-approved direction for SM-32/SM-33. +Status: design; not current Bundle functionality. +Parent: [local Bundle improvement program](37-local-bundle-improvement-program.md). + +## Two independent decisions + +`score_model_selection` decides which model a score run uses: + +- `pinned_version`: load the configured concrete version; a permitted runtime + override is recorded and applies only to that run unless explicitly persisted. +- `champion`: resolve the controlled champion to a concrete version once at + run start. An alias move during execution does not change that run's model. + +`promotion_policy` decides how the registry champion changes: + +- `manual_approval`: train/register/nominate/evaluate, then await an explicit + approve or reject lifecycle action on that existing model version. +- `automatic`: promote after all configured quality and improvement checks + pass; a failed check leaves champion unchanged and retains the challenger. + +| Scoring selection | Promotion policy | Expected behavior | +| --- | --- | --- | +| pinned_version | manual_approval | Human approval governs registry aliases; scoring remains on its explicit pin | +| pinned_version | automatic | Registry champion may advance automatically; scoring still keeps its explicit pin | +| champion | manual_approval | Training produces a contender; scoring follows the old champion until approval | +| champion | automatic | Passing contender becomes champion; the next score follows it | + +The promotion operation does not silently rewrite a scoring pin. For a +champion-following project with no champion, score fails clearly before writing. +An initial candidate still needs the absolute-quality gate and the configured +manual/automatic decision; no implicit ungated bootstrap. + +## Lifecycle and job ownership + +### Recent challenger history (requested follow-up) + +Add previous_challenger as a pointer to the last contender displaced by a +new nomination. It is not the complete model history or an automatic fallback. +This extension is planned for SM-32; the current implementation has no such alias. + +| Transition | Champion | Challenger | Previous challenger | +| --- | --- | --- | --- | +| Before a new candidate | v2 | v3 | unset | +| Nominate v4 | v2 | v4 | v3 | +| Promote v4 | v4 | unset | v3 | + +The old champion becomes previous_champion through the existing promotion +path. Promotion itself must not move the new champion into previous_challenger. +Another contender replacing v4 before promotion replaces that history pointer +with v4; all older version evidence remains available. + +All changes use the same serialized writer, expected-version checks and +durable receipts. Repeated nomination must not rotate history. Partial writes +must remain reconcilable. Promotion or rollback involving the history version +must explicitly reconcile the pointer so current and historical roles do not +silently conflict. Add tests for replacement, retry, promotion, rollback, +uncontrolled history pointers and unknown write outcomes. + +### Serialized lifecycle actions + +Keep two persistent jobs. The lifecycle job accepts train, approve, reject or +rollback; the score job owns prediction publication. All lifecycle mutations +share the same serialized writer identity and job queue. Operator actions must +not create a third independent writer that races scheduled training. + +```mermaid +flowchart TD + T["Train and register model"] --> C["Nominate latest challenger"] + C --> E["Evaluate pinned holdout"] + E --> Q{"All quality gates pass?"} + Q -->|"No"| R["Record rejection; retain challenger and current champion"] + Q -->|"Yes"| P{"Promotion policy"} + P -->|"Automatic"| A["Checked promotion and committed receipt"] + P -->|"Manual approval"| W["Await explicit approval of this version"] + W --> V["Recheck evidence and expected registry state"] + V --> A + A --> H["Optional handoff to existing score job"] + H --> S{"Scoring selection"} + S -->|"Pinned version"| F["Load explicit version"] + S -->|"Champion"| G["Resolve controlled champion once"] + F --> O["Apply chosen append or full-rebuild policy"] + G --> O +``` + +Manual approval inputs identify the existing candidate version, expected +champion and pinned evaluation/policy evidence. Approval loads those artifacts +and rechecks them; it must not call fit, register another version or upload +another model. Repeated successful requests return/reconcile the original +receipt rather than causing another transition. Stale, rejected, forged or +incompatible evidence is refused. + +A manual rejection records the decision and reason without changing champion. +The challenger remains the latest contender until replaced by a newer one. +Approval does not offer an implicit force override. If business exceptions +are later needed, they require a separately designed policy and audit path. + +After promotion, the old champion becomes previous_champion. A promoted model +stops being challenger. Retained candidates and rollback interactions must +not lose version history. Controlled rollback uses the same writer and can +hand off to score using its configured selector/output policy. + +## Compatibility and failure behavior + +- Migrate old `auto_champion` explicitly to champion selection plus automatic + promotion. Preserve pinned mode's lack of implicit promotion; document the + new manual action rather than silently changing old configurations. +- Code/model uploads are not required for an alias-only approved change. + New code, dependencies or project configuration still require deployment. +- The generated job graph and effective configuration must agree about score + handoff; reject incompatible partial migrations. +- Raw Catalog UI alias edits are not a replacement for controlled approval. + Alias/receipt disagreement stops the controlled workflow pending reconciliation. +- Promotion and prediction publication remain separate transactions. If score + fails, preserve prior output and retry score without retraining or reapproval. +- Unknown alias outcomes do not trigger blind mutation retries. Persist the + pending/committed receipt and expose the operator recovery action. +- A pinned override cannot bypass trusted artifact, schema, budget or target + compatibility checks. It deliberately chooses a version rather than claiming + that version passed automatic promotion criteria. + +## Acceptance scenarios + +1. v2 champion, tied v3 challenger: manual or automatic score still uses v2. +2. A passing v4 waits in manual mode; approval moves champion without training. +3. Pinned v2 remains selected even after automatic promotion of v4. +4. Two concurrent approval/train requests are serialized and stale evidence + cannot overwrite the latest decision. +5. New source rows score without retraining; no new rows produce a no-op. +6. Full rebuild publishes only a complete compatible generation; append keeps + old-version rows and records the new version on later predictions. +7. First champion requires quality approval; absent champion never loads latest + as an undocumented fallback. +8. Failed score can be retried, uncertain alias writes require reconciliation, + and rollback works with the retained-challenger semantics. diff --git a/initiatives/spark_and_mlflow/39-serving-and-feature-lookup-delivery-plan.md b/initiatives/spark_and_mlflow/39-serving-and-feature-lookup-delivery-plan.md new file mode 100644 index 000000000..e79d2baff --- /dev/null +++ b/initiatives/spark_and_mlflow/39-serving-and-feature-lookup-delivery-plan.md @@ -0,0 +1,29 @@ +# Serving and feature lookup delivery contract + +Date: 2026-09-24. Status: explicitly requested backlog, not implemented. +Prerequisite: SM-43a local Bundle acceptance. Existing task IDs are retained. +These capabilities are delivered in sequence; users select only the features +their generated project needs. The batch-only project keeps its two jobs. + +| Order / task | Deliverable | Completion evidence | +| --- | --- | --- | +| 1 / SM-19a | Optional HTTP endpoint for the existing trusted FE+model artifact; explicit version deployment, request/output schema, readiness and endpoint configuration | Real endpoint predictions match local predictions for supported pandas/Polars artifacts; authentication, invalid/missing inputs, warm/cold requests and bounded load are tested | +| 2 / SM-19b | Optional ai_query use of a compatible endpoint with named feature inputs, explicit output contract and caller privileges | SQL predictions match HTTP/local outputs; null/type/order handling, denied access and endpoint failures are tested; no implicit Spark FE conversion | +| 3 / SM-19d | Configurable A/B or canary serving with pinned model versions, explicit traffic allocation, rollout readiness and rollback | Two-version routing, traffic totals, failed rollout recovery and restoring the prior configuration are verified; changing an alias alone is not claimed to update a serving endpoint | +| 4 / SM-21a | Optional UC feature lookup with explicit entity/time keys, selected columns and point-in-time training joins | No future-feature leakage, duplicate/missing key behavior and prediction input assembly match the saved model contract; external feature preparation stays separate from fitted artifact FE | +| 5 / SM-21b | Optional online feature publication/lookup with explicit store resources, freshness policy and serving integration | Offline/online feature parity, stale/missing values, update propagation, access controls and endpoint prediction parity are verified | + +Implementation locations: add optional serving/feature adapters under +`skyulf-core/skyulf/integrations/databricks/`, reuse existing local MLflow model +packaging and prediction contracts, and extend the Bundle schema/resources +only behind feature choices. Add corresponding integration tests and English +examples under the generated project and user guide. + +Each task begins with platform/API verification and a concrete resource plan. +Validate generated Bundle configuration strictly before a scoped live test. +Endpoints and online stores have persistent resources and costs distinct from +the prior serverless batch rehearsal; retain exact resource/run inventories. +No endpoint/store is provisioned by this planning change. + +Monitoring uses existing SM-23a/b contracts. Continuous streaming remains +parked under SM-19c; it is not required to deliver the five tasks above. diff --git a/initiatives/spark_and_mlflow/40-sm30-challenger-validation-report.md b/initiatives/spark_and_mlflow/40-sm30-challenger-validation-report.md new file mode 100644 index 000000000..3a10ed8c7 --- /dev/null +++ b/initiatives/spark_and_mlflow/40-sm30-challenger-validation-report.md @@ -0,0 +1,71 @@ +# SM-30 challenger lifecycle validation + +Date: 2026-09-24. Scope: local implementation and verification; not deployed. + +## Delivered behavior + +Bundle training explicitly nominates a registered contender before comparison. +Generic `train_local_candidate` does not mutate aliases unless its caller +provides `on_registered`; the Bundle supplies `ChallengerLifecycle.registered`. +Training and all alias operations require the same serialized writer. + +Model-version tags show `validation_status` (pending, passed, rejected, error), +`validation_reason`, and `promotion_status`. A rejected contender stays visible +as challenger; the next registered contender replaces that pointer. Promotion +still requires fresh evidence and all existing gates. A first model uses its +absolute quality threshold before initialization. + +Pinned scoring keeps its concrete model version. Training resolves the actual +champion for comparison; a stale explicit champion_version fails before fit. +An evaluation or final evidence-read failure records error for a pending +contender. Completed validation is not overwritten by later promotion failure. +Uncertain registry writes retain pending receipts for reconciliation. + +Rollback preserves a separate contender with a verified lifecycle receipt. +It still refuses an uncontrolled alias or one pointing at either rollback +participant. Repeated nomination is idempotent; an older contender cannot +replace a newer one through the nomination API. + +## Verification scope + +The real local MLflow tests run the generated workflow for both pandas and +Polars: initialize v1, promote improved v2, retain tied v3, nominate manual v4 +without changing the score pin, and retain failed-evaluation v5. Only Spark's +source-read boundary is substituted with a bounded temporal dataset. + +Registry tests additionally cover retained-challenger rollback, fresh report +checks, first-model cleanup, repeated/stale nominations and partial status +writes. A partial registry transition must block controlled champion reads. +Bundle tests cover failure during final evidence checking and rejection of a +stale configured comparison version before training. + +The generated README, Bundle guide, registry guide and 0.9.0 changelog describe +the new semantics. A second code review found no remaining actionable issue +after fixing stale pinned-training expectations and final-comparison errors. + +Final verification: + +- 104 tests passed in 74.57 seconds across MLflow promotion, validation, + registry, Databricks local retraining, Bundle template and both-engine + lifecycle suites. Log: `rehearsals/sm30-final.log`. +- Ruff passed on all eight changed Python files; scoped ty passed on the + three library modules and two Core test modules. +- `mkdocs build --strict` returned exit code 0. Log: + `rehearsals/sm30-docs-verified.log`. The existing unlisted segmentation page + produced an informational message, not a strict-build failure. +- `git diff --check` passed. No commit or live deployment was performed. + +## Boundaries and next work + +No cloud job, alias, table, endpoint or schedule was changed. The retained +live SM-29 v3 record still reflects the previous implementation. SM-43a +provides the combined live acceptance gate for this improvement program. + +SM-31 next extracts reusable orchestration from the generated workflow. +SM-32 separates manual/automatic promotion from pinned/champion scoring and +adds approval of an existing candidate without retraining. Production writer +ownership remains an explicit SM-37 and SM-43b gate. + +Serving, ai_query, A/B and feature lookup remain approved work in +[the extension delivery contract](39-serving-and-feature-lookup-delivery-plan.md), +after SM-43a. They are not implemented by SM-30. diff --git a/initiatives/spark_and_mlflow/41-company-tags-and-clean-live-validation.md b/initiatives/spark_and_mlflow/41-company-tags-and-clean-live-validation.md new file mode 100644 index 000000000..860b91bd5 --- /dev/null +++ b/initiatives/spark_and_mlflow/41-company-tags-and-clean-live-validation.md @@ -0,0 +1,90 @@ +# Company-compatible tags and clean SM-30 verification + +Date: 2026-09-24. Status: 104 local tests and live verification passed. +This is the user-requested prerequisite before SM-31. + +## Tag contract + +The reference training notebooks attach data versions to runs and attach the +following metadata to registered model versions. Skyulf now uses these names +on its training run and model version: + +| Tag | Meaning | +| --- | --- | +| train_data_destination | Full training source table name | +| test_data_destination | Full evaluation source table name | +| train_data_version | Pinned Delta source version used for fit | +| test_data_version | Pinned Delta source version used for evaluation | +| model_type | Selected Core modeling type | +| candidate_date_tag | Training workflow date, YYYY-MM-DD in UTC | +| risk_category | Optional project classification from workflow.json | + +Skyulf splits one snapshot by event and label times, so its train/test table +names and Delta versions may match. The reference can use separate tables. +train_start, test_start, and data_end make our split readable; engine records +pandas or Polars. task=training replaces phase=candidate_training. +The exact dataset identity stays in training_data.json and the comparison +artifact instead of a long concatenated run tag. An unusually long UC value +points to training_data.json; the artifact and run tags retain the full value. + +The reference also copies version metadata onto the registered model object. +Skyulf keeps it on each version so a rejected contender cannot make top-level +metadata appear to describe champion. The reference best_model_name belongs +to model search, planned in SM-36; the single-candidate workflow uses model_type. +PayingRegNo is a separate compute cost tag, configurable through the existing +policy-compute cost_tag_key/cost_tag_value fields. These tests use serverless. + +validation_status remains pending/passed/rejected/error. validation_reason +uses plain English, such as "No improvement over champion". Comparison +artifacts retain stable machine reason codes. promotion_status records +promotion separately; aliases identify current champion/challenger roles. + +Technical event tags remain for interrupted-write recovery and receipt +verification. Their JSON uses action/from/proof/parent/state/previous instead +of single-letter fields; older receipts remain readable. Event IDs and hashes +are integrity references, not user settings. The 256-byte value limit remains. + +## Reset and rehearsal scope + +The user explicitly requested deletion and recreation. CLI inventory verified +owners, exact table/model contents, empty volumes and no active runs. Function +entries corresponded to the registered models. + +Deleted job IDs: 1106811466161550, 793298964293930, 1046235940974377, +290396749537917. Deleted schemas including their test tables/models: +workspace.skyulf_sm27_sm29_20260924 and workspace.skyulf_bundle_first_20260924. +The following inventory showed no jobs and only default/information_schema. +Historical local evidence and test source files were preserved. + +New target: workspace.skyulf_lifecycle_test. One source table, one model and +one predictions table per engine. The generic Bundle deploys two jobs. +An ephemeral four-task run performs setup, independent pandas and Polars +lifecycles, then appended-row/no-op checks. No schedules are activated. +Each task and the overall run have a 900-second timeout and no automatic retry. + +First submission 425389607887141 was cancelled after a local wheel ACL blocked +upload. Identical bytes were copied into a readable workspace file; +replacement run: 607409241163605. Wheel SHA-256: +e76934549cd47b768c818f5fded2163a38ec92a9dbeeaa7ba0bb4a7d54c51481c. + +Local tests: 104 passed in 79.20 seconds, rehearsals/tags-final.log. +All four tasks in run 607409241163605 returned SUCCESS. Polars finished with +champion=2 and rejected challenger=3. Pandas additionally nominated v4, +retained v5 with evaluation error, and rolled champion from v2 back to v1 +while preserving challenger v5. Each successful training version had matching +company tags on its run and version, all six regression metrics, readable +receipt fields, and the full provenance artifact. + +The final audit appended ten rows to the original 160-row source. Both output +tables contained 170 unique keys. Replaying both scorers returned noop=true +without changing their Delta commit versions. The main Polars output kept +160 v1 rows and appended ten v2 rows; the pandas rollback output used v1. + +A later local wording correction distinguishes positive improvements below +the configured minimum from no improvement; its targeted test passed. The +live tie scenario keeps the same tested wording. It will ship in the SM-31 wheel. +Exact CLI inventories and scripts are under rehearsals/sm30_live/. + +Reference: supplied dbml-mlops-template training notebook and +src/training/services/registry_service.py.tmpl. Registration tag forwarding +uses the [MLflow client API](https://mlflow.org/docs/latest/api_reference/python_api/mlflow.client.html). diff --git a/initiatives/spark_and_mlflow/42-sm31-refactor-plan-and-evidence.md b/initiatives/spark_and_mlflow/42-sm31-refactor-plan-and-evidence.md new file mode 100644 index 000000000..971692892 --- /dev/null +++ b/initiatives/spark_and_mlflow/42-sm31-refactor-plan-and-evidence.md @@ -0,0 +1,55 @@ +# SM-31 thin Bundle orchestration implementation plan + +**Goal:** Preserve the verified lifecycle and publication behavior in reusable +Core services, leaving a small generated notebook boundary. + +**Architecture:** local_workflow.py owns target binding, train/score selection +and orchestration. prediction_output.py owns output schema checks, generation +provenance and grant-preserving view activation. The notebook reads widgets, +loads the editable business config, invokes run_action and serializes results. + +**Spec:** SM-31 in 37-local-bundle-improvement-program.md. +**Baseline:** User-requested SM-30/tag live run 607409241163605 passed first. +Work continues in the existing 090 checkout, preserving uncommitted changes. + +- [x] Pin the notebook-to-library delegation contract with a failing test. +- [x] Move existing function bodies into two Core modules without changing + selection, validation, output, admission or failure semantics. +- [x] Move service behavior tests into Core; keep generated config/job and + notebook boundary tests, including pandas/Polars real MLflow lifecycle tests. +- [x] Run focused/full relevant suites, Ruff and scoped ty; review the extraction. +- [x] Build a wheel, verify imports outside the source checkout, regenerate and + validate the Bundle, and verify its thin score entry point in the test workspace. +- [x] Update the English operator guide, changelog, queue and handoff with + exact local/live evidence and the next task. + +No new job type, control table, alias policy or automatic schedule is added. + +## Local evidence + +The notebook is 44 lines. AST review against the archived pre-extraction +workflow confirmed unchanged function/class bodies and constants. Every +existing test was retained; service tests now live in Core, seven generated +project tests remain in the root suite, and six notebook-boundary cases cover +both engines and all three actions. Real local MLflow lifecycle tests still +enter through the generated notebook's imported run_action. + +110 tests passed in 90.08 seconds (rehearsals/sm31-final.log). Ruff and scoped +ty passed on all changed library modules and Core tests. A no-dependency +installation into an isolated target directory passed import and target +selection checks with Python -I, verifying module paths came from the wheel. + +SM-31 wheel SHA-256: +b0a5113db1dbc05eddd2c2164c1abc16510acda2e2207c1a2cfdd4d9fb455f01. +The same two test jobs were updated after strict Bundle validation. The +rehearsal uses a distinct SM-31 wheel path to avoid cached old code. +Score verification run 383572337148835 and task 922087987590767 returned +SUCCESS. The installed-library notebook returned noop=true, zero new inputs +and outputs, and unchanged Delta commit version 2. This is a deployed score +check after extraction; fresh training through the extracted modules was +validated locally with both engines, while the preceding SM-30 live run used +the equivalent pre-extraction orchestrator. No new live model was trained by SM-31. + +Strict MkDocs completed with exit code 0. A freshly initialized final-template +project also passed strict Bundle validation. git diff --check passed. +No commit was made. Next: SM-32 independent approval and score model selection. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 9578f53ae..8d7b7c034 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,5 +1,56 @@ # Session handoff - 2026-09-24 +## Current priority: SM-30 through SM-43 + +The user approved the [local Bundle improvement program](37-local-bundle-improvement-program.md) +and explicitly requested [independent scoring selection and promotion policy](38-model-selection-and-approval-design.md). +**SM-30, company tags and SM-31 are complete; SM-32 is next READY.** +Latest follow-up: Bundle initialization now asks for optional risk_category, +PayingRegNo has an explicit policy-compute example, and new receipts use +from_version while reading older formats. 44 relevant tests and real CLI +generation/strict serverless validation passed. No live resources changed. +The requested previous_challenger replacement-history alias is specified in +the SM-32 design and queue, not implemented yet. +The user requested readable/company-compatible tags and a clean live reset +before SM-31. [The clean rehearsal](41-company-tags-and-clean-live-validation.md) +passed all four tasks in run 607409241163605. [SM-31 evidence](42-sm31-refactor-plan-and-evidence.md) +records 110 passing tests, Ruff, scoped ty, strict MkDocs, installed-wheel imports, +and a successful deployed score run 383572337148835. Changes remain uncommitted. + +The old four test jobs and two schemas were deleted as requested. Retain the +new workspace.skyulf_lifecycle_test schema and exactly two skyulf_lifecycle +jobs (train 155738051514173, score 684955889505992). One source and two engine +prediction tables each contain 170 rows. Main model_polars has champion=2, +challenger=3 rejected. model_pandas has champion=1 and challenger=5 error after +the explicit rollback test. Both scorers replayed without new commits. +No schedule is active. The notebook is now 44 lines, delegating to Core +local_workflow.py and prediction_output.py. Keep business config in the project. + +SM-30 changes challenger semantics: a trained/registered contender such as +tied v3 remains challenger, with evaluation status/reason visible; only +promotion depends on passing quality gates. Newer contenders replace that +pointer while retaining history. Rollback now preserves a separate contender +with a verified receipt. Real local MLflow tests cover pandas and Polars, +including manual nomination, tied candidates and comparison errors. + +Next separate pinned/champion selection from +manual/automatic promotion, expose validated runtime/configuration choices +and independent schedules, improve metrics/search, identities/operations, +packaging, generated CI, data recovery and documentation. SM-43a verifies the +combined personal-workspace workflow; SM-43b separately gates company use. +The explicitly requested serving, ai_query, A/B and offline/online feature +tasks follow SM-43a; see [their contract](39-serving-and-feature-lookup-delivery-plan.md). +Broad Spark and monitoring also remain later; SM-18 and +continuous streaming remain parked. Keep two jobs and no default control tables. + +Preserve the earlier uncommitted two-literal test correction in +`skyulf-core/tests/integrations/test_mlflow_promotion.py`: the actual tag is +`pending_alias_event`. The preceding review ran 58 Bundle/promotion tests +successfully; that evidence does not validate the newly planned semantics. +The notes below describe historical resources that the user subsequently +requested to delete. Use the new inventory above for the current workspace. +SM-43a still owns combined acceptance for the remaining improvement program. + ## Current state after SM-27/SM-29 The combined personal-workspace live rehearsal passed; SM-27 and SM-29 are diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 4b4e7b3d4..e32971b10 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -6,8 +6,10 @@ automatic champion selection, failed-score recovery and serialized handoff. This is functional completion for the selected workflow. Production must still enforce one exclusive alias writer; both test jobs used a human owner, and live contention was exercised for score requests, not concurrent trains. -See [the combined live evidence](35-sm27-sm29-live-validation-report.md). Spark -expansion follows the validated first Bundle. SM-15L +See [the combined live evidence](35-sm27-sm29-live-validation-report.md). The +current priority is the approved SM-30 through SM-43 local Bundle improvement +program below, starting with challenger semantics. Broad Spark expansion +waits for its local acceptance gate (SM-43a). SM-15L provides explicit-period UC output. SM-15I adds automatic new-row scoring for the first Bundle; SM-18 and streaming remain parked. @@ -26,6 +28,72 @@ DONE = kanıtla tamamlandı. SM-00 commit: `105a6fe4`. DEFERRED = user postponed this work; PARKED = do not implement until resumed. SUPERSEDED = replaced by a later user-directed scope; not a completed feature. +## Active priority: local Bundle improvements before Spark + +The user approved the comparison findings and clarified that a newly trained +contender remains challenger even when it fails promotion. The user also +explicitly approved separating manual/automatic promotion from score model +selection. These are new requirements; prior DONE rows retain their original +scope and do not imply the improvements below already exist. + +Read [the improvement program](37-local-bundle-improvement-program.md) and +[the independent selection/approval design](38-model-selection-and-approval-design.md). +Each task includes implementation locations and concrete acceptance checks. +**SM-30, company-compatible tags and SM-31 are complete; SM-32 is READY.** See +[the implementation evidence](40-sm30-challenger-validation-report.md): 104 +tests passed, including real MLflow lifecycles with pandas and Polars. +See [the clean live rehearsal](41-company-tags-and-clean-live-validation.md). +SM-31 passed 110 tests and its deployed thin score notebook passed live; see +[the extraction evidence](42-sm31-refactor-plan-and-evidence.md). +SM-43a remains the later combined acceptance for the full improvement program. +Keep two jobs and reuse Core services. Manual approval must act +on an existing candidate without retraining or reuploading the model. + +| Order | Task | Dependencies | Status | Acceptance / deliverable | +| --- | --- | --- | --- | --- | +| SM-30 | Challenger nomination and visible evaluation status | Existing SM-22c/29 | DONE | 104 local tests and live run 607409241163605 passed; company tags, both engines, retained contender, replacement, error and rollback verified | +| SM-31 | Thin template and reusable workflow/publication services | SM-30 | DONE | 44-line notebook, two Core services, 110 tests, wheel installation/import, strict generation validation and live score run 383572337148835 passed | +| SM-32 | Independent score selection and promotion policy | SM-31 | READY | Four pinned/champion and manual/automatic combinations; approve/reject/rollback existing versions via one writer; score handoff without fit; previous_challenger history on contender replacement | +| SM-33 | Validated config, migration and runtime parameters | SM-32 | WAIT | Per-run version/action/evidence inputs; task/column/key setup; migrate old mode and reject config/job-graph disagreement | +| SM-34 | Independent score/train schedules and training windows | SM-33 | WAIT | Editable paused score/train cron/timezone, explicit lookback/holdout/label windows; scoring needs no manual dates or retraining | +| SM-35 | Multi-metric quality gates and clear thresholds | SM-33 | WAIT | One selection metric plus optional guardrails; task/domain validation, first-model gate, failed-gate explanations and no probability-threshold confusion | +| SM-36 | Core tuning, model search and optional explainability | SM-35 | WAIT | Existing Core search/trials and FE reused with budgets, protected holdout, MLflow evidence and selected-model inference parity | +| SM-37 | Production identities and enforced writer ownership | SM-32, SM-33 | WAIT | Per-target run_as/permissions/hosts/roots; one lifecycle writer; scoring cannot move aliases; actual denial and lifecycle queue evidence | +| SM-38 | Operational limits, retry/recovery and run summaries | SM-34, SM-37 | WAIT | Configurable timeouts/retries/notifications; source/model/count/no-op summaries; score-only recovery and no blind alias retry | +| SM-39 | Reproducible packaging and per-target compute | SM-33 | WAIT | Central compatible wheel/runtime pins, clean install/load, configurable policy/worker/cost settings and strict target validation | +| SM-40 | Generated-project tests and generic CI/CD | SM-37, SM-38, SM-39 | WAIT | Standalone project tests/build/validate and optional company adapter; explicit deployment approvals; no default chargeable PR runs | +| SM-41 | CDF recovery, full refresh and generation retention | SM-31, SM-33, SM-38 | WAIT | Explicit CDF-expiry/source-change recovery; preserve active outputs/grants and rollback generations; update/delete policy never silently inferred | +| SM-42 | Complete first-run examples and operator guide | SM-30 through SM-41 | WAIT | pandas/Polars regression/classification examples; manual/auto and append/full instructions, config-vs-runtime settings, scheduling and recovery | +| SM-43a | Combined personal-workspace acceptance | SM-42 | WAIT | Representative real-data FE/models, both engines, manual/auto, retained challenger, new rows, no-op, failure/rollback/queue; exact run/resource evidence | +| SM-43b | Company-target production readiness gate | SM-43a; confirmed company environment | WAIT | Approved identities/UC/policy compute/dependency/CI/data checks in the actual company target; no inference from personal serverless tests | + +The tasks are sequenced by this table when dependencies allow. SM-43b needs +actual company settings and access; it must not prevent unrelated local work. +No new live resources or company deployments are authorized merely by a queue +status. Existing explicit live authorizations retain their original scope. + +## Approved extensions after the local improvement gate + +The user explicitly requested serving, A/B, ai_query and online feature lookup. +These existing IDs are required backlog work, implemented after SM-43a in the +listed order, while each feature remains opt-in for generated projects. +See [the delivery contract](39-serving-and-feature-lookup-delivery-plan.md). + +| Task | Status | Dependency / scope | +| --- | --- | --- | +| SM-19a | LATER | SM-43a; HTTP serving, fitted artifact parity, readiness and load/cold-start checks | +| SM-19b | LATER | SM-19a; SQL ai_query invocation, named inputs, privileges and failure behavior | +| SM-19d | LATER | SM-19a; A/B/canary routing, endpoint update/rollback; batch rollout separately explicit | +| SM-21a | LATER | SM-43a; UC feature lookup, keys and point-in-time correctness | +| SM-21b | LATER | SM-21a/19a; optional online publication, freshness and serving lookup | +| SM-23a | LATER | SM-43a; batch quality/drift/delayed-label reporting and optional dashboards; SM-38 covers basic operations first | +| SM-23b | LATER | SM-19a; endpoint inference tables and version-aware model-performance monitoring | +| SM-19c | PARKED | Continuous streaming remains outside the current user-approved implementation sequence | + +SM-17/24c/20b remain later Spark enhancements after SM-43a. SM-18 stays parked. + +## Earlier implementation and live evidence + | Sıra | Görev | Bağımlılık | Durum | Kısa bitiş ölçütü | | --- | --- | --- | --- | --- | | SM-00 | Baseline ve Spark test ortamı | — | DONE | Güncel master: 231 baseline; 2 Spark smoke; [kanıt](BASELINE.md) | @@ -98,6 +166,13 @@ No library fix was required by this rehearsal. Source updates/deletes, company targets, policy compute and broad Spark execution remain outside this evidence. Production must still enforce one serialized alias writer. +The subsequent [reference comparison and readiness review](36-bundle-reference-comparison-and-readiness.md) +separates this completed functional scope from remaining production adoption +work: manual approval UX, runtime parameters, independent score scheduling, +workflow simplification, identities/operations and generated-project CI. +The user subsequently approved that work; the new task definitions and the +corrected challenger semantics are recorded in SM-30 through SM-43 above. + ## Local-first path to the first Bundle These tasks were identified in the reference review; the latest user direction diff --git a/skyulf-core/skyulf/integrations/databricks/local_retraining.py b/skyulf-core/skyulf/integrations/databricks/local_retraining.py index 119213388..2317626cb 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_retraining.py +++ b/skyulf-core/skyulf/integrations/databricks/local_retraining.py @@ -1,13 +1,14 @@ """Bounded, label-aware local candidate training from a pinned Delta snapshot. This adapter uses Spark only for a narrow, bounded read. Fit and evaluation run -on the recorded local engine; publication never changes a registry alias. +on the recorded local engine. Alias management requires an explicit caller hook. """ from __future__ import annotations import math import pickle +from collections.abc import Callable from dataclasses import asdict, dataclass from datetime import UTC, datetime from importlib.metadata import version @@ -19,7 +20,7 @@ from ...data.dataset import SplitDataset from ...inference.local_evaluation import evaluate_local_holdout -from ..mlflow.registry import register_model, resolve_model +from ..mlflow.registry import ResolvedModel, register_model, resolve_model from ..mlflow.tracking import TrackingConfig, track_run from ..mlflow.validation import ModelComparisonReport, compare_registered_local_models from ._contracts import column_name, table_name @@ -209,12 +210,23 @@ def train_local_candidate( engine: Literal["pandas", "polars"] = "pandas", champion_version: str | None = None, quality_threshold: float | None = None, + on_registered: Callable[[ResolvedModel], None] | None = None, + risk_category: str | None = None, ) -> LocalCandidateResult: - """Fit, log, register and compare a candidate without changing any aliases.""" + """Fit, register and compare; optionally notify an explicit lifecycle owner. + + By default no aliases change. The on_registered hook runs after successful + registration and before comparison, allowing the caller to nominate a + contender without making the generic training service an alias writer. + """ if not isinstance(spec, LocalTrainingSpec): raise TypeError("spec must be LocalTrainingSpec.") if engine not in ("pandas", "polars"): raise ValueError("engine must be pandas or polars.") + if risk_category is not None and ( + not isinstance(risk_category, str) or len(risk_category.encode("utf-8")) > 256 + ): + raise ValueError("risk_category must be text of at most 256 UTF-8 bytes.") if ( type(min_improvement) not in (int, float) or not math.isfinite(min_improvement) @@ -279,7 +291,25 @@ def train_local_candidate( "code_version": version("skyulf-core"), } ) - run.set_tags({"dataset_id": spec.dataset_id, "phase": "candidate_training"}) + tags = { + "task": "training", + "train_data_destination": spec.table, + "test_data_destination": spec.table, + "train_data_version": str(spec.version), + "test_data_version": str(spec.version), + "train_start": spec.start.astimezone(UTC).isoformat(), + "test_start": spec.holdout_start.astimezone(UTC).isoformat(), + "data_end": spec.cutoff.astimezone(UTC).isoformat(), + "model_type": str(config["modeling"]["type"]), + "candidate_date_tag": datetime.now(UTC).date().isoformat(), + "engine": engine, + } + if risk_category: + tags["risk_category"] = risk_category + run.set_tags(tags) + run.client.log_dict( + run.run_id, {"dataset_id": spec.dataset_id, **tags}, "training_data.json" + ) run.log_metrics(metrics) model_uri = _log_local_model(artifact_path, run_id=run.run_id, tracking_uri=tracking_uri) run_id = run.run_id @@ -288,6 +318,10 @@ def train_local_candidate( model_name, tracking_uri=tracking_uri, registry_uri=registry_uri, + tags={ + key: value if len(value.encode("utf-8")) <= 256 else "See training_data.json" + for key, value in tags.items() + }, ) candidate = resolve_model( model_name, @@ -295,6 +329,8 @@ def train_local_candidate( tracking_uri=tracking_uri, registry_uri=registry_uri, ) + if on_registered is not None: + on_registered(candidate) report = compare_registered_local_models( candidate, champion, diff --git a/skyulf-core/skyulf/integrations/databricks/local_workflow.py b/skyulf-core/skyulf/integrations/databricks/local_workflow.py new file mode 100644 index 000000000..83129c292 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_workflow.py @@ -0,0 +1,345 @@ +"""Reusable bounded local training and scoring orchestration for Databricks jobs. + +The caller serializes all lifecycle writes for each model and output. Importing +this module creates no Spark session, registry connection or cloud resource. +""" + +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import polars as pl + +from ..mlflow.challenger import ChallengerLifecycle +from ..mlflow.promotion import ( + AliasChangeReceipt, + ExclusiveAliasWriterAdmission, + controlled_champion_version, + initialize_champion, + promote_candidate, + stage_challenger, +) +from ..mlflow.registry import RegistryModelNotFoundError, resolve_model +from .admission import SingleWriterAdmission +from .local_incremental import run_incremental_local_batch +from .local_retraining import ( + LocalTrainingSpec, + read_training_snapshot, + split_labeled_snapshot, + train_local_candidate, +) +from .local_sdk import ( + InputSource, + LocalWorkflowConfig, + ModelSelection, + OutputSink, + prepare_local_workflow, +) +from .prediction_output import ( + _IDENTIFIER, + _TABLE_NAME, + _activate_prediction_view, + _managed_prediction_view_exists, + _scoring_target, + provision_prediction_table, +) + +_TABLE_FIELDS = ( + "training_table", + "score_source_table", + "prediction_table", + "model_name", +) + + +@dataclass(frozen=True, slots=True) +class AutoTrainingOutcome: + """Expose both candidate evidence and the optional alias change in job output.""" + + candidate: Any + alias_change: AliasChangeReceipt | None + + +def _selection_mode(config: dict[str, Any]) -> str: + """Reject a selection policy that could silently load a wrong model.""" + mode = config.get("model_selection_mode", "pinned_version") + if mode not in ("pinned_version", "auto_champion"): + raise ValueError("model_selection_mode must be pinned_version or auto_champion.") + return mode + + +def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: + """Bind only UC object names to one validated Bundle target.""" + for name in ("catalog", "input_schema", "output_schema", "metadata_schema"): + if not _IDENTIFIER.fullmatch(bindings.get(name, "")): + raise ValueError(f"Invalid {name} for a Unity Catalog identifier.") + suffix = bindings.get("resource_suffix", "") + if suffix and (not suffix.startswith("_") or not _IDENTIFIER.fullmatch(suffix)): + raise ValueError("Invalid resource_suffix for a Unity Catalog identifier.") + resolved = config.copy() + for name in _TABLE_FIELDS: + value = config[name] + if type(value) is not str: + raise ValueError(f"{name} must be a string.") + for key, replacement in bindings.items(): + value = value.replace("{" + key + "}", replacement) + if not _TABLE_NAME.fullmatch(value): + raise ValueError(f"{name} must resolve to a three-part UC name.") + if name in {"prediction_table", "model_name"}: + schema = "output_schema" if name == "prediction_table" else "metadata_schema" + expected = f"{bindings['catalog']}.{bindings[schema]}." + if not value.startswith(expected): + raise ValueError(f"{name} must use the active target's {schema}.") + if suffix and not value.endswith(suffix): + raise ValueError(f"{name} must include the active target's resource_suffix.") + resolved[name] = value + return resolved + + +def _scoring_config(config: dict[str, Any]) -> LocalWorkflowConfig: + """Bind the pinned local model and source for incremental scoring.""" + return LocalWorkflowConfig( + runtime="databricks", + engine=config["engine"], + source=InputSource( + kind="uc_table", + table=config["score_source_table"], + read_mode="incremental", + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ), + model=ModelSelection( + kind="local_pipeline", + name=config["model_name"], + version=config["model_version"], + tracking_uri=config.get("tracking_uri", "databricks"), + registry_uri=config.get("registry_uri", "databricks-uc"), + ), + sink=OutputSink(kind="uc_delta", table=config["prediction_table"]), + ) + + +def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: + """Keep the evaluation split and source snapshot identical across actions.""" + return LocalTrainingSpec( + table=config["training_table"], + version=config["training_version"], + start=datetime.fromisoformat(config["start"]), + holdout_start=datetime.fromisoformat(config["holdout_start"]), + cutoff=datetime.fromisoformat(config["cutoff"]), + event_column=config["event_column"], + label_time_column=config["label_time_column"], + row_keys=tuple(config["row_keys"]), + input_columns=tuple(config["input_columns"]), + target_column=config["target_column"], + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ) + + +def _monthly_training_spec(spark: Any, config: dict[str, Any], now: datetime) -> LocalTrainingSpec: + """Pin one Delta version and a UTC calendar window for monthly training.""" + if now.tzinfo is None or now.utcoffset() is None: + raise ValueError("Monthly training needs a timezone-aware run instant.") + lookback = config.get("monthly_lookback_months") + if type(lookback) is not int or not 2 <= lookback <= 120: + raise ValueError("monthly_lookback_months must be an integer from 2 to 120.") + cutoff = now.astimezone(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0) + + def months_before(count: int) -> datetime: + """Preserve the first-of-month boundary across year rollover.""" + index = cutoff.year * 12 + cutoff.month - 1 - count + return datetime(index // 12, index % 12 + 1, 1, tzinfo=UTC) + + table = config["training_table"] + if not _TABLE_NAME.fullmatch(table): + raise ValueError("training_table must be a three-part UC name.") + latest = ( + spark.sql(f"DESCRIBE HISTORY {table}") + .select("version") + .orderBy("version", ascending=False) + .first() + ) + if latest is None or type(latest["version"]) is not int: + raise ValueError("Training source has no concrete Delta version.") + return LocalTrainingSpec( + table=table, + version=latest["version"], + start=months_before(lookback), + holdout_start=months_before(1), + cutoff=cutoff, + event_column=config["event_column"], + label_time_column=config["label_time_column"], + row_keys=tuple(config["row_keys"]), + input_columns=tuple(config["input_columns"]), + target_column=config["target_column"], + max_rows=config["max_rows"], + max_bytes=config["max_bytes"], + ) + + +def _monthly_champion_version(config: dict[str, Any]) -> str | None: + """Resolve the current champion once while allowing first-model training.""" + try: + champion = resolve_model( + config["model_name"], + alias="champion", + tracking_uri=config.get("tracking_uri", "databricks"), + registry_uri=config.get("registry_uri", "databricks-uc"), + ) + except RegistryModelNotFoundError: + return None + return champion.version + + +def _automatic_promotion( + spark: Any, + config: dict[str, Any], + spec: LocalTrainingSpec, + candidate: Any, + *, + promote: bool = True, +) -> AliasChangeReceipt | None: + """Record contender evidence separately from any optional champion transition.""" + report = candidate.comparison + frame = read_training_snapshot(spark, spec) + _, heldout, _ = split_labeled_snapshot(frame, spec) + native = pl.from_pandas(heldout) if config["engine"] == "polars" else heldout + options = { + "target_column": spec.target_column, + "admission": ExclusiveAliasWriterAdmission(), + "max_rows": spec.max_rows, + "max_bytes": spec.max_bytes, + "tracking_uri": config.get("tracking_uri", "databricks"), + "registry_uri": config.get("registry_uri", "databricks-uc"), + } + stage_challenger( + report, + native, + expected_champion_version=report.champion_version, + expected_challenger_version=report.candidate_version, + **options, + ) + if not promote: + return None + if report.champion_version is None: + value = report.candidate_metrics[report.metric] + threshold = report.quality_threshold + if threshold is None or not ( + value <= threshold if report.metric_direction == "minimize" else value >= threshold + ): + return None + return initialize_champion(report, native, **options) + if not report.eligible: + return None + return promote_candidate( + report, + native, + expected_champion_version=report.champion_version, + **options, + ) + + +def run_action( + spark: Any, + config: dict[str, Any], + action: str, + *, + experiment_name: str | None = None, + artifact_path: str | Path | None = None, + now: datetime | None = None, +) -> Any: + """Delegate training or scoring to Skyulf's existing services.""" + tracking_uri = config.get("tracking_uri", "databricks") + registry_uri = config.get("registry_uri", "databricks-uc") + selection_mode = _selection_mode(config) + if action in {"train", "train_monthly"}: + if experiment_name is None or artifact_path is None: + raise ValueError("Training needs an experiment and temporary artifact path.") + monthly = action == "train_monthly" + if selection_mode == "auto_champion" and config.get("quality_threshold") is None: + raise ValueError("auto_champion requires an absolute quality_threshold.") + spec = ( + _monthly_training_spec(spark, config, now or datetime.now(UTC)) + if monthly + else _training_spec(config) + ) + if selection_mode == "auto_champion": + champion_version = controlled_champion_version( + config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri + ) + else: + champion_version = _monthly_champion_version(config) + expected = config.get("champion_version") + if expected is not None and str(expected) != champion_version: + raise ValueError("champion_version does not match the current champion.") + lifecycle = ChallengerLifecycle( + config["model_name"], + expected_champion_version=champion_version, + admission=ExclusiveAliasWriterAdmission(), + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + try: + candidate = train_local_candidate( + spark, + spec, + config["pipeline"], + model_name=config["model_name"], + tracking_uri=tracking_uri, + registry_uri=registry_uri, + experiment_name=experiment_name, + run_name="candidate_training", + artifact_path=artifact_path, + metric=config["metric"], + min_improvement=config["min_improvement"], + engine=config["engine"], + champion_version=champion_version, + quality_threshold=config.get("quality_threshold"), + on_registered=lifecycle.registered, + risk_category=config.get("risk_category"), + ) + alias_change = _automatic_promotion( + spark, + config, + spec, + candidate, + promote=selection_mode == "auto_champion", + ) + except Exception as error: # noqa: BLE001 - preserve failure and lifecycle evidence + try: + lifecycle.failed() + except Exception as status_error: # noqa: BLE001 - retain the original failure + raise error from status_error + raise + if selection_mode == "auto_champion": + return AutoTrainingOutcome( + candidate=candidate, + alias_change=alias_change, + ) + return candidate + if action == "score": + if selection_mode == "auto_champion": + champion_version = controlled_champion_version( + config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri + ) + if champion_version is None: + raise ValueError("auto_champion scoring requires a committed champion.") + config = {**config, "model_version": champion_version} + target = _scoring_target(config) + if config.get("model_change_mode", "incremental_append") == "full_rebuild": + _managed_prediction_view_exists(spark, config["prediction_table"]) + score_config = {**config, "prediction_table": target} + prepared = prepare_local_workflow(_scoring_config(score_config)) + provision_prediction_table(spark, score_config, prepared) + result = run_incremental_local_batch( + spark, + prepared, + row_keys=tuple(config["row_keys"]), + admission=SingleWriterAdmission(), + ) + if config.get("model_change_mode", "incremental_append") == "full_rebuild": + _activate_prediction_view(spark, config["prediction_table"], target) + return result + raise ValueError(f"Unknown workflow action: {action}.") diff --git a/skyulf-core/skyulf/integrations/databricks/prediction_output.py b/skyulf-core/skyulf/integrations/databricks/prediction_output.py new file mode 100644 index 000000000..c20cae3f4 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/prediction_output.py @@ -0,0 +1,192 @@ +"""Validate and publish local model prediction tables and full-rebuild views.""" + +import re +from typing import Any + +_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") + +_TABLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){2}\Z") + +_OUTPUT_TYPES = { + "float64": ("double", "DOUBLE"), + "int64": ("long", "BIGINT"), + "string": ("string", "STRING"), + "bool": ("boolean", "BOOLEAN"), +} + + +def _scoring_target(config: dict[str, Any]) -> str: + """Choose a stable append target or a physical model-version generation.""" + mode = config.get("model_change_mode", "incremental_append") + if type(mode) is not str or mode not in {"incremental_append", "full_rebuild"}: + raise ValueError("model_change_mode must be incremental_append or full_rebuild.") + base = config["prediction_table"] + version = config["model_version"] + if not _TABLE_NAME.fullmatch(base): + raise ValueError("prediction_table must be a three-part UC name.") + if ( + type(version) is not str + or not version.isascii() + or not version.isdecimal() + or version[0] == "0" + ): + raise ValueError("model_version must be a concrete positive version.") + if mode == "full_rebuild": + return f"{base}_v{version}" + return base + + +def _managed_prediction_view_exists(spark: Any, logical: str) -> bool: + """Reject a table or unrelated view before creating prediction resources.""" + if not spark.catalog.tableExists(logical): + return False + if spark.catalog.getTable(logical).tableType.upper() != "VIEW": + raise ValueError("Full rebuild needs a view name, but a physical table already uses it.") + marker = spark.sql(f"SHOW TBLPROPERTIES {logical} ('skyulf.mode')").first() + if marker is None or marker["value"] != "full_rebuild": + raise ValueError("Existing prediction view is not managed by Skyulf full rebuild.") + return True + + +def _activate_prediction_view(spark: Any, logical: str, generation: str) -> None: + """Expose a complete generation without replacing prior prediction tables.""" + if ( + not _TABLE_NAME.fullmatch(logical) + or not _TABLE_NAME.fullmatch(generation) + or not re.fullmatch(re.escape(logical) + r"_v[1-9][0-9]*", generation) + ): + raise ValueError("Prediction view and generation names must match one UC target.") + physical = spark.table(generation) + if not physical.limit(1).count(): + raise ValueError("A full-rebuild generation must contain predictions before activation.") + if not _managed_prediction_view_exists(spark, logical): + spark.sql( + f"CREATE VIEW {logical} TBLPROPERTIES ('skyulf.mode' = 'full_rebuild') " + f"AS SELECT * FROM {generation}" + ).collect() + return + active_columns = tuple( + (field.name, field.dataType.typeName()) for field in spark.table(logical).schema.fields + ) + candidate_columns = tuple( + (field.name, field.dataType.typeName()) for field in physical.schema.fields + ) + if active_columns != candidate_columns: + raise ValueError("New prediction generation differs from the active view schema.") + definition = spark.sql(f"SHOW CREATE TABLE {logical}").first() + if definition is not None: + sql = definition["createtab_stmt"].casefold().replace("`", "") + if re.search(r"\bfrom\s+" + re.escape(generation.casefold()) + r"\b", sql): + return + spark.sql(f"ALTER VIEW {logical} AS SELECT * FROM {generation}").collect() + + +def _prediction_columns( + config: dict[str, Any], prepared: Any, source: Any +) -> tuple[tuple[str, str, str], ...]: + """Derive an exact Delta target schema from source keys and saved model outputs.""" + keys = tuple(config["row_keys"]) + inputs = tuple(prepared.artifact.manifest.input_columns) + if not keys or tuple(config["input_columns"]) != inputs: + raise ValueError("Configured keys or model inputs differ from the fitted model.") + names = (*keys, *inputs) + if any(not _IDENTIFIER.fullmatch(name) for name in names): + raise ValueError("Source keys and model inputs need simple column identifiers.") + if len({name.lower() for name in names}) != len(names): + raise ValueError("Source keys and model inputs must be distinct.") + if not set(names).issubset(source.columns): + raise ValueError("Scoring source lacks a row key or fitted model input column.") + columns = [] + for key in keys: + kind = source.schema[key].dataType.typeName() + if kind not in {"string", "long"}: + raise ValueError(f"Source row key {key!r} must be STRING or BIGINT.") + columns.append((key, kind, "STRING" if kind == "string" else "BIGINT")) + for output in prepared.preflight.output_schema: + if not _IDENTIFIER.fullmatch(output.name) or output.dtype not in _OUTPUT_TYPES: + raise ValueError("Saved model output has an unsupported name or type.") + kind, sql_type = _OUTPUT_TYPES[output.dtype] + columns.append((output.name, kind, sql_type)) + columns.extend((name, "string", "STRING") for name in ("run_id", "model_name", "model_version")) + if len({name.lower() for name, _, _ in columns}) != len(columns): + raise ValueError("Prediction columns collide with keys or metadata.") + return tuple(columns) + + +def _check_existing_table(spark: Any, name: str, columns: tuple[tuple[str, str, str], ...]) -> None: + """Reject an existing prediction target with a different schema.""" + actual = {field.name: field.dataType.typeName() for field in spark.table(name).schema.fields} + expected = {column: kind for column, kind, _ in columns} + if actual != expected: + raise ValueError(f"Existing prediction table {name} differs from the model output schema.") + + +def _generation_properties(config: dict[str, Any], prepared: Any) -> dict[str, str]: + """Bind a full-rebuild table to one concrete saved model artifact.""" + digest = prepared.preflight.model_digest + if type(digest) is not str or not re.fullmatch(r"[0-9a-f]{64}", digest): + raise ValueError("Pinned model has no valid artifact digest.") + return { + "skyulf.mode": "full_rebuild", + "skyulf.model_name": config["model_name"], + "skyulf.model_version": config["model_version"], + "skyulf.model_digest": digest, + } + + +def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any) -> bool: + """Preflight an existing source/model and create only a missing output table.""" + source_name = config["score_source_table"] + target_name = config["prediction_table"] + for name in (source_name, target_name, config["model_name"]): + if not _TABLE_NAME.fullmatch(name): + raise ValueError("Scoring needs valid three-part Unity Catalog names.") + if source_name == target_name: + raise ValueError("Prediction output must differ from the source table.") + if not spark.catalog.tableExists(source_name): + raise ValueError(f"Existing input source table is missing: {source_name}.") + if not prepared.preflight.ready: + raise ValueError("The pinned registered model failed Skyulf preflight.") + source = spark.table(source_name) + columns = _prediction_columns(config, prepared, source) + detail = spark.sql(f"DESCRIBE DETAIL {source_name}").first() + properties = detail["properties"] or {} + if not any( + key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" + for key, value in properties.items() + ): + raise ValueError("Scoring source must have Delta Change Data Feed enabled.") + target_exists = spark.catalog.tableExists(target_name) + generation = config.get("model_change_mode") == "full_rebuild" + generation_properties = _generation_properties(config, prepared) if generation else {} + if target_exists: + if generation: + actual_properties = ( + spark.sql(f"DESCRIBE DETAIL {target_name}").first()["properties"] or {} + ) + if any( + actual_properties.get(key) != value for key, value in generation_properties.items() + ): + raise ValueError( + "Existing prediction generation belongs to another model or workflow." + ) + _check_existing_table(spark, target_name, columns) + if not target_exists: + if ( + source.select(*config["row_keys"], *config["input_columns"]) + .limit(config["max_rows"] + 1) + .count() + > config["max_rows"] + ): + raise ValueError("Initial scoring source exceeds the configured max_rows budget.") + definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) + table_properties = "" + if generation: + properties = ", ".join( + f"'{key}' = '{value}'" for key, value in generation_properties.items() + ) + table_properties = f" TBLPROPERTIES ({properties})" + spark.sql( + f"CREATE TABLE {target_name} ({definition}) USING DELTA{table_properties}" + ).collect() + return not target_exists diff --git a/skyulf-core/skyulf/integrations/mlflow/challenger.py b/skyulf-core/skyulf/integrations/mlflow/challenger.py new file mode 100644 index 000000000..54e349f06 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/challenger.py @@ -0,0 +1,133 @@ +"""Nominate registered contenders independently of promotion eligibility.""" + +from uuid import uuid4 + +from .promotion import ( + AliasAdmission, + AliasChangeReceipt, + AliasConflictError, + _active_marker, + _admission, + _assert_no_pending, + _checked_challenger_event, + _commit_change, + _read_optional_alias, + alias_resource_id, +) +from .registry import ResolvedModel, _make_client, _require_mlflow, resolve_model + + +class ChallengerLifecycle: + """Track one explicit training orchestrator's registered contender. + + Pass registered as the training service's on_registered callback. Generic + training remains alias-free unless the caller explicitly opts into this + externally serialized lifecycle. Evaluation and promotion stay separate. + """ + + def __init__( + self, + model_name: str, + *, + expected_champion_version: str | None, + admission: AliasAdmission, + tracking_uri: str | None = None, + registry_uri: str | None = None, + ) -> None: + """Bind the expected champion and one shared alias writer.""" + self.model_name = model_name + self.expected_champion_version = expected_champion_version + self.admission = admission + self.tracking_uri = tracking_uri + self.registry_uri = registry_uri + self.candidate: ResolvedModel | None = None + + def registered(self, candidate: ResolvedModel) -> None: + """Publish a registered contender as pending before its comparison runs.""" + if not isinstance(candidate, ResolvedModel) or candidate.name != self.model_name: + raise ValueError("Registered candidate must belong to the lifecycle model.") + _admission(self.admission, self.registry_uri) + fresh = resolve_model( + candidate.name, + version=candidate.version, + tracking_uri=self.tracking_uri, + registry_uri=self.registry_uri, + ) + if fresh.digest != candidate.digest or not candidate.digest: + raise ValueError("Candidate artifact digest changed before nomination.") + client = _make_client(_require_mlflow(), self.tracking_uri, self.registry_uri) + with self.admission.hold(alias_resource_id(candidate.name)): + _assert_no_pending(client, candidate.name) + champion = _read_optional_alias(client, candidate.name, "champion") + if champion != self.expected_champion_version: + raise AliasConflictError("Champion changed before challenger nomination.") + if candidate.version == champion: + raise AliasConflictError("Champion cannot also be its own challenger.") + existing = _read_optional_alias(client, candidate.name, "challenger") + if existing is not None: + _checked_challenger_event(client, candidate.name, existing) + if int(existing) > int(candidate.version): + raise AliasConflictError("A newer challenger already exists.") + if existing == candidate.version: + self.candidate = candidate + return + receipt = AliasChangeReceipt( + event_id=uuid4().hex, + kind="nomination", + model_name=candidate.name, + alias="challenger", + prior_version=existing, + new_version=candidate.version, + comparison_sha256=candidate.digest, + parent_event_id=( + _active_marker(client, candidate.name, champion) if champion else None + ), + ) + _commit_change( + client, + receipt, + [("challenger", candidate.version, existing)], + version_tags={ + "validation_status": "pending", + "validation_reason": "Waiting for evaluation", + "promotion_status": "not_promoted", + }, + ) + self.candidate = candidate + + def failed(self) -> None: + """Retain the contender and record failure without copying raw exception text.""" + candidate = self.candidate + if candidate is None: + return + client = _make_client(_require_mlflow(), self.tracking_uri, self.registry_uri) + with self.admission.hold(alias_resource_id(candidate.name)): + version = client.get_model_version(candidate.name, candidate.version) + if (version.tags or {}).get("validation_status") != "pending": + return + _assert_no_pending(client, candidate.name) + if _read_optional_alias(client, candidate.name, "challenger") != candidate.version: + raise AliasConflictError("Challenger changed before failure recording.") + _checked_challenger_event(client, candidate.name, candidate.version) + receipt = AliasChangeReceipt( + event_id=uuid4().hex, + kind="evaluation_error", + model_name=candidate.name, + alias="challenger", + prior_version=candidate.version, + new_version=candidate.version, + comparison_sha256=None, + parent_event_id=_active_marker( + client, candidate.name, candidate.version, "challenger" + ), + ) + _commit_change( + client, + receipt, + [], + version_tags={ + "validation_status": "error", + "validation_reason": "Evaluation could not be completed", + "promotion_status": "not_promoted", + }, + ) diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py index 4f45d6735..3035c65fc 100644 --- a/skyulf-core/skyulf/integrations/mlflow/promotion.py +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -250,7 +250,16 @@ def _event_payload(receipt: AliasChangeReceipt, status: str) -> dict[str, str | def _write_event(client: Any, receipt: AliasChangeReceipt, status: str) -> None: """Persist a prepared or committed transition on its destination version.""" - value = json.dumps(_event_payload(receipt, status), sort_keys=True, separators=(",", ":")) + labels = { + "k": "action", + "p": "from_version", + "h": "proof", + "e": "parent", + "s": "state", + "o": "previous", + } + payload = {labels[key]: value for key, value in _event_payload(receipt, status).items()} + value = json.dumps(payload, sort_keys=True, separators=(",", ":")) if len(value.encode("utf-8")) > 256: raise ValueError("UC model-version receipt exceeds the 256-byte tag value limit.") client.set_model_version_tag( @@ -258,6 +267,27 @@ def _write_event(client: Any, receipt: AliasChangeReceipt, status: str) -> None: ) +def _read_event(raw: str | None) -> Any: + """Decode readable receipts while retaining compatibility with compact receipts.""" + payload = json.loads(raw) if raw is not None else None + if isinstance(payload, dict) and "action" in payload: + labels = { + "action": "k", + "from": "p", + "from_version": "p", + "proof": "h", + "parent": "e", + "state": "s", + "previous": "o", + } + if any(key not in labels for key in payload): + raise ValueError("Unexpected lifecycle receipt field.") + if "from" in payload and "from_version" in payload: + raise ValueError("Ambiguous prior-version fields in lifecycle receipt.") + return {labels[key]: value for key, value in payload.items()} + return payload + + def _verify_original_receipt(client: Any, receipt: AliasChangeReceipt) -> bool: """Refuse forged receipts; return true for a pre-multi-alias promotion.""" try: @@ -268,7 +298,7 @@ def _verify_original_receipt(client: Any, receipt: AliasChangeReceipt) -> bool: raise _translate_error(exc, name=receipt.model_name, version=receipt.new_version) from exc expected = _event_payload(receipt, "committed") try: - stored = json.loads(raw) if raw is not None else None + stored = _read_event(raw) except (TypeError, json.JSONDecodeError) as exc: raise ValueError("Promotion receipt is malformed.") from exc if stored == expected: @@ -283,6 +313,8 @@ def _commit_change( client: Any, receipt: AliasChangeReceipt, updates: list[tuple[str, str | None, str | None]], + *, + version_tags: dict[str, str] | None = None, ) -> None: """Prepare, apply verified alias updates, then persist their common receipt. @@ -331,8 +363,16 @@ def _commit_change( f"Alias outcome unknown; inspect prepared event {receipt.event_id}." ) from exc try: - if receipt.kind == "promotion": + if receipt.kind in {"promotion", "initial"}: client.delete_registered_model_tag(receipt.model_name, _CHALLENGER_TAG) + tags = dict(version_tags or {}) + if receipt.kind in {"promotion", "initial"}: + tags["promotion_status"] = "promoted" + for key, value in tags.items(): + client.set_model_version_tag(receipt.model_name, receipt.new_version, key, value) + stored = client.get_model_version(receipt.model_name, receipt.new_version).tags or {} + if any(stored.get(key) != value for key, value in tags.items()): + raise AliasOutcomeUnknownError("Model version status was not verified.") _write_event(client, receipt, "committed") tag = _ACTIVE_TAG if receipt.alias == _ALIAS else _CHALLENGER_TAG client.set_registered_model_tag( @@ -358,23 +398,26 @@ def _validated_report( heldout: pd.DataFrame | pl.DataFrame, *, target_column: str, - expected_champion_version: str, + expected_champion_version: str | None, max_rows: int, max_bytes: int, tracking_uri: str | None, registry_uri: str | None, + require_eligible: bool = True, ) -> str: """Re-evaluate the pinned candidate and return its comparison digest.""" if not isinstance(report, ModelComparisonReport): raise TypeError("report must be a ModelComparisonReport.") - if ( - type(expected_champion_version) is not str - or expected_champion_version != report.champion_version - or not expected_champion_version.isascii() - or not expected_champion_version.isdigit() + if expected_champion_version != report.champion_version or ( + expected_champion_version is not None + and ( + type(expected_champion_version) is not str + or not expected_champion_version.isascii() + or not expected_champion_version.isdigit() + ) ): raise ValueError("Expected champion version must match the comparison report.") - if not report.eligible or report.reason != "candidate_improved": + if require_eligible and (not report.eligible or report.reason != "candidate_improved"): raise ValueError("Comparison does not approve candidate promotion.") candidate = resolve_model( report.model_name, @@ -382,11 +425,15 @@ def _validated_report( tracking_uri=tracking_uri, registry_uri=registry_uri, ) - champion = resolve_model( - report.model_name, - version=expected_champion_version, - tracking_uri=tracking_uri, - registry_uri=registry_uri, + champion = ( + resolve_model( + report.model_name, + version=expected_champion_version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + if expected_champion_version is not None + else None ) fresh = compare_registered_local_models( candidate, @@ -402,7 +449,7 @@ def _validated_report( tracking_uri=tracking_uri, registry_uri=registry_uri, ) - if fresh != report or not fresh.eligible: + if fresh != report or (require_eligible and not fresh.eligible): raise ValueError("Pinned comparison no longer matches the supplied report.") return hashlib.sha256( json.dumps(asdict(fresh), sort_keys=True, allow_nan=False).encode() @@ -470,7 +517,16 @@ def initialize_champion( comparison_sha256=digest, parent_event_id=None, ) - _commit_change(client, receipt, [(_ALIAS, report.candidate_version, None)]) + challenger = _read_optional_alias(client, report.model_name, _CHALLENGER) + if challenger is not None and challenger != report.candidate_version: + raise AliasConflictError("A different challenger exists before initialization.") + updates: list[tuple[str, str | None, str | None]] = [ + (_ALIAS, report.candidate_version, None) + ] + if challenger is not None: + _checked_challenger_event(client, report.model_name, challenger) + updates.append((_CHALLENGER, None, challenger)) + _commit_change(client, receipt, updates) return receipt @@ -479,7 +535,7 @@ def stage_challenger( heldout: pd.DataFrame | pl.DataFrame, *, target_column: str, - expected_champion_version: str, + expected_champion_version: str | None, admission: AliasAdmission, max_rows: int, max_bytes: int, @@ -487,7 +543,7 @@ def stage_challenger( tracking_uri: str | None = None, registry_uri: str | None = None, ) -> AliasChangeReceipt: - """Assign a validated candidate to challenger without moving champion.""" + """Record a freshly checked contender, even when promotion quality fails.""" _admission(admission, registry_uri) digest = _validated_report( report, @@ -498,16 +554,19 @@ def stage_challenger( max_bytes=max_bytes, tracking_uri=tracking_uri, registry_uri=registry_uri, + require_eligible=False, ) client = _make_client(_require_mlflow(), tracking_uri, registry_uri) with admission.hold(alias_resource_id(report.model_name)): - if _read_alias(client, report.model_name) != expected_champion_version: + if _read_optional_alias(client, report.model_name, _ALIAS) != expected_champion_version: raise AliasConflictError("Champion alias differs from expected version.") existing = _read_optional_alias(client, report.model_name, _CHALLENGER) if existing != expected_challenger_version: raise AliasConflictError("Challenger alias differs from expected version.") if existing == report.candidate_version: - raise AliasConflictError("Candidate already holds challenger alias.") + _checked_challenger_event(client, report.model_name, existing) + if report.candidate_version == expected_champion_version: + raise AliasConflictError("Champion cannot also be its own challenger.") receipt = AliasChangeReceipt( event_id=uuid4().hex, kind="challenger", @@ -516,12 +575,66 @@ def stage_challenger( prior_version=existing, new_version=report.candidate_version, comparison_sha256=digest, - parent_event_id=_active_marker(client, report.model_name, expected_champion_version), + parent_event_id=( + _active_marker(client, report.model_name, expected_champion_version) + if expected_champion_version is not None + else None + ), + ) + passed = report.eligible + reason = { + "candidate_improved": "Improved over champion", + "insufficient_improvement": "No improvement over champion", + "quality_gate_failed": "Quality threshold not met", + }.get(report.reason, report.reason) + if report.reason == "insufficient_improvement" and (report.improvement or 0) > 0: + reason = "Improvement below required minimum" + if report.champion_version is None: + value = report.candidate_metrics[report.metric] + threshold = report.quality_threshold + passed = threshold is not None and ( + value <= threshold if report.metric_direction == "minimize" else value >= threshold + ) + reason = ( + "First model passed quality threshold" + if passed + else "First model quality not approved" + ) + _commit_change( + client, + receipt, + [(_CHALLENGER, report.candidate_version, existing)], + version_tags={ + "validation_status": "passed" if passed else "rejected", + "validation_reason": reason, + "promotion_status": "not_promoted", + }, ) - _commit_change(client, receipt, [(_CHALLENGER, report.candidate_version, existing)]) return receipt +def _checked_challenger_event(client: Any, name: str, version: str) -> dict[str, Any]: + """Require a durable contender event before preserving or updating its alias.""" + event_id = _active_marker(client, name, version, _CHALLENGER) + if event_id is None: + raise AliasConflictError("Challenger alias lacks a controlled lifecycle event.") + try: + raw = client.get_model_version(name, version).tags.get(_event_tag(event_id)) + event = _read_event(raw) + except (TypeError, ValueError) as exc: + raise AliasConflictError("Challenger receipt is malformed.") from exc + if ( + not event_id + or not isinstance(event, dict) + or ( + event.get("s") != "committed" + or event.get("k") not in {"nomination", "challenger", "evaluation_error"} + ) + ): + raise AliasConflictError("Challenger lacks a committed lifecycle receipt.") + return event + + def _verify_staged_challenger( client: Any, report: ModelComparisonReport, comparison_sha256: str ) -> str: @@ -535,7 +648,7 @@ def _verify_staged_challenger( raw = client.get_model_version(report.model_name, report.candidate_version).tags.get( _event_tag(event_id) ) - event = json.loads(raw) if raw is not None else None + event = _read_event(raw) except Exception as exc: # noqa: BLE001 - registry transport boundary raise AliasConflictError("Challenger staging event cannot be verified.") from exc if not isinstance(event, dict) or ( @@ -628,8 +741,11 @@ def rollback_promotion( if _active_marker(client, receipt.model_name, current) != receipt.event_id: raise AliasConflictError("A newer promotion superseded this rollback receipt.") legacy = _verify_original_receipt(client, receipt) - if _read_optional_alias(client, receipt.model_name, _CHALLENGER) is not None: - raise AliasConflictError("Clear the newer challenger before rollback.") + challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) + if challenger is not None: + _checked_challenger_event(client, receipt.model_name, challenger) + if challenger in {current, receipt.prior_version}: + raise AliasConflictError("Challenger conflicts with the rollback versions.") if not legacy and ( _read_optional_alias(client, receipt.model_name, _PREVIOUS) != receipt.prior_version ): diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py index f1e3ece02..6adb48ce6 100644 --- a/skyulf-core/skyulf/integrations/mlflow/registry.py +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -283,6 +283,7 @@ def register_model( *, tracking_uri: str | None = None, registry_uri: str | None = None, + tags: dict[str, str] | None = None, ) -> Any: """Publish a run artifact as a new registered-model version explicitly. @@ -301,7 +302,8 @@ def register_model( if _error_code(exc) not in {"RESOURCE_ALREADY_EXISTS", "ALREADY_EXISTS"}: raise _translate_error(exc, name=name, version="new") from exc try: - return client.create_model_version(name=name, source=model_uri, run_id=run_id) + options = {"tags": tags} if tags is not None else {} + return client.create_model_version(name=name, source=model_uri, run_id=run_id, **options) except Exception as exc: # noqa: BLE001 - translate MLflow's backend errors at the boundary raise _translate_error(exc, name=name, version="new") from exc diff --git a/skyulf-core/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json index d7c478736..98731a431 100644 --- a/skyulf-core/templates/databricks/databricks_template_schema.json +++ b/skyulf-core/templates/databricks/databricks_template_schema.json @@ -128,7 +128,7 @@ "order": 10, "type": "string", "default": "CostCenter", - "description": "Approved cluster cost tag key", + "description": "Approved cluster cost tag key, for example CostCenter or PayingRegNo", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, @@ -136,8 +136,15 @@ "order": 11, "type": "string", "default": "REPLACE_WITH_COST_TAG", - "description": "Approved cluster cost tag value", + "description": "Approved cluster cost tag value; for PayingRegNo, enter your paying registration number", "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} + }, + "risk_category": { + "order": 20, + "type": "string", + "default": "", + "description": "Optional business risk label (e.g. Low, Medium, High); leave blank when unused. This label does not change promotion gates.", + "pattern": "^(?:[A-Za-z0-9][A-Za-z0-9 ._-]{0,63})?$" } } } diff --git a/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json b/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json new file mode 100644 index 000000000..de6b2bc58 --- /dev/null +++ b/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json @@ -0,0 +1,17 @@ +{ + "project_name": "my_model", + "engine": "pandas", + "row_key": "customer_id", + "retraining_mode": "manual", + "model_change_mode": "incremental_append", + "model_selection_mode": "pinned_version", + "compute_mode": "policy_cluster", + "catalog": "REPLACE_DEV_CATALOG", + "schema": "REPLACE_DEV_SCHEMA", + "cluster_policy_name": "REPLACE_WITH_APPROVED_POLICY", + "spark_version": "17.3.x-cpu-ml-scala2.13", + "node_type_id": "REPLACE_WITH_NODE_TYPE", + "cost_tag_key": "PayingRegNo", + "cost_tag_value": "REPLACE_WITH_PAYING_REG_NO", + "risk_category": "Low" +} diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index b43b9e99e..645a71795 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -7,6 +7,11 @@ same Skyulf workflow code with different target bindings. ## What deployment creates +`src/workflow.py` is a thin widget/JSON entry point. Common behavior is provided +by the installed `skyulf.integrations.databricks.local_workflow` and +`prediction_output` modules. Customize your preprocessing/model pipeline in +`config/workflow.json`; common workflow changes belong in the Skyulf wheel. + `bundle deploy` uploads the wheel, notebook and configuration, and creates two jobs. It creates **no** Unity Catalog table or registered model. The initialization choice `retraining_mode=monthly_paused` adds a paused @@ -14,9 +19,28 @@ schedule to the existing `train` job; the default `manual` choice adds none. | Job | Run it when | UC effect | | --- | --- | --- | -| `train` | Labeled data is ready or the schedule runs | Registers a candidate; logs metrics | +| `train` | Labeled data is ready or the schedule runs | Registers and nominates a challenger; logs metrics and evaluation status | | `score` | A model is pinned and rows need scoring | Appends rows or builds a new generation | +In both selection modes, each registered contender becomes `@challenger` +before comparison. Model-version tags show `validation_status` (`pending`, +`passed`, `rejected`, or `error`), `validation_reason`, and `promotion_status`. +A tied or worse candidate remains challenger; a newer contender replaces the +pointer while earlier version evidence remains. Only the serialized train job +identity may write these aliases. Restrict other writers before running train; +table-free alias admission relies on that externally enforced ownership. + +Run and model-version tags use `train_data_version`, `test_data_version`, +`train_data_destination`, `test_data_destination`, `model_type`, and +`candidate_date_tag`. Both data versions refer to the pinned source snapshot; +`train_start`, `test_start`, and `data_end` describe its temporal split. +Optional `risk_category` is selected at initialization and stays editable in +config/workflow.json. Leaving it blank omits the tag; it never changes promotion gates. +For policy compute, select `PayingRegNo` as the cost tag key when required by +your company and provide the approved number as the cost tag value. +The complete dataset identity is in the run's training_data.json artifact. +Technical promotion event tags contain recovery receipts; do not edit them. + {{if eq .model_selection_mode "auto_champion"}} This project uses automatic champion selection. `train` compares a candidate against champion on a pinned temporal holdout. The first champion needs a @@ -28,16 +52,13 @@ unchanged. The train job calls the existing score job after it succeeds. Score resolves `@champion` once to a concrete version at run start. Alias promotion and Delta publication are separate transactions. If scoring fails after promotion, retry `score`; the previous successful prediction output -remains until a new score completes. Only the serialized train job identity -may write this model's aliases. Restrict other alias writers before enabling -automatic mode; table-free alias admission does not provide a lock. An +remains until a new score completes. An unknown alias-write outcome leaves a pending marker and blocks later automatic training and scoring until registry receipt reconciliation. An existing `@champion` set outside Skyulf's guarded promotion path has no committed receipt and must be reconciled before automatic mode can use it. {{else}} -Champion/challenger management is available through Skyulf Core but has no -job in this starting Bundle. Training a candidate does not activate it for +Training records challenger status but never promotes it or activates it for scoring. Set `model_version` to a concrete registered version and redeploy when you want scoring to use it. {{end}} @@ -56,7 +77,8 @@ later labels are excluded. The captured Delta version is pinned at run start; it is not a historical snapshot as of the cutoff. If the source has too few labeled rows in either partition, training fails without publishing a model. The run compares against the concrete version behind `@champion` if present; -a missing alias means first-model training. Registry access failures still +a missing alias means first-model training. An explicit `champion_version` +must match the current champion or training fails before fit. Registry access failures still fail the job. Retry runs can create additional candidate versions. {{if eq .model_selection_mode "pinned_version"}}None is promoted or used by `score` automatically.{{end}} diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index b505f22ff..6dd0d603a 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -10,6 +10,7 @@ "model_change_mode": "{{.model_change_mode}}", "model_selection_mode": "{{.model_selection_mode}}", "champion_version": null, + "risk_category": {{if .risk_category}}"{{.risk_category}}"{{else}}null{{end}}, "row_keys": ["{{.row_key}}"], "input_columns": ["feature_value"], "target_column": "target", diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py index 885cbcc6f..459cde28b 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -1,484 +1,12 @@ # Databricks notebook source -"""Run one bounded Skyulf local training or incremental scoring action.""" +"""Read job settings and call the installed Skyulf workflow services.""" import json -import re import tempfile -from dataclasses import asdict, dataclass -from datetime import UTC, datetime +from dataclasses import asdict from pathlib import Path -from typing import Any -import polars as pl - -from skyulf.integrations.databricks import ( - InputSource, - LocalTrainingSpec, - LocalWorkflowConfig, - ModelSelection, - OutputSink, - prepare_local_workflow, - read_training_snapshot, - run_incremental_local_batch, - split_labeled_snapshot, - train_local_candidate, -) -from skyulf.integrations.databricks.admission import SingleWriterAdmission -from skyulf.integrations.mlflow.promotion import ( - AliasChangeReceipt, - ExclusiveAliasWriterAdmission, - controlled_champion_version, - initialize_champion, - promote_candidate, - stage_challenger, -) -from skyulf.integrations.mlflow.registry import RegistryModelNotFoundError, resolve_model - -_TABLE_FIELDS = ( - "training_table", - "score_source_table", - "prediction_table", - "model_name", -) -_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") -_TABLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){2}\Z") -_OUTPUT_TYPES = { - "float64": ("double", "DOUBLE"), - "int64": ("long", "BIGINT"), - "string": ("string", "STRING"), - "bool": ("boolean", "BOOLEAN"), -} - - -@dataclass(frozen=True, slots=True) -class AutoTrainingOutcome: - """Expose both candidate evidence and the optional alias change in job output.""" - - candidate: Any - alias_change: AliasChangeReceipt | None - - -def _selection_mode(config: dict[str, Any]) -> str: - """Reject a selection policy that could silently load a wrong model.""" - mode = config.get("model_selection_mode", "pinned_version") - if mode not in ("pinned_version", "auto_champion"): - raise ValueError("model_selection_mode must be pinned_version or auto_champion.") - return mode - - -def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: - """Bind only UC object names to one validated Bundle target.""" - for name in ("catalog", "input_schema", "output_schema", "metadata_schema"): - if not _IDENTIFIER.fullmatch(bindings.get(name, "")): - raise ValueError(f"Invalid {name} for a Unity Catalog identifier.") - suffix = bindings.get("resource_suffix", "") - if suffix and (not suffix.startswith("_") or not _IDENTIFIER.fullmatch(suffix)): - raise ValueError("Invalid resource_suffix for a Unity Catalog identifier.") - resolved = config.copy() - for name in _TABLE_FIELDS: - value = config[name] - if type(value) is not str: - raise ValueError(f"{name} must be a string.") - for key, replacement in bindings.items(): - value = value.replace("{" + key + "}", replacement) - if not _TABLE_NAME.fullmatch(value): - raise ValueError(f"{name} must resolve to a three-part UC name.") - if name in {"prediction_table", "model_name"}: - schema = "output_schema" if name == "prediction_table" else "metadata_schema" - expected = f"{bindings['catalog']}.{bindings[schema]}." - if not value.startswith(expected): - raise ValueError(f"{name} must use the active target's {schema}.") - if suffix and not value.endswith(suffix): - raise ValueError(f"{name} must include the active target's resource_suffix.") - resolved[name] = value - return resolved - - -def _scoring_config(config: dict[str, Any]) -> LocalWorkflowConfig: - """Bind the pinned local model and source for incremental scoring.""" - return LocalWorkflowConfig( - runtime="databricks", - engine=config["engine"], - source=InputSource( - kind="uc_table", - table=config["score_source_table"], - read_mode="incremental", - max_rows=config["max_rows"], - max_bytes=config["max_bytes"], - ), - model=ModelSelection( - kind="local_pipeline", - name=config["model_name"], - version=config["model_version"], - tracking_uri=config.get("tracking_uri", "databricks"), - registry_uri=config.get("registry_uri", "databricks-uc"), - ), - sink=OutputSink(kind="uc_delta", table=config["prediction_table"]), - ) - - -def _scoring_target(config: dict[str, Any]) -> str: - """Choose a stable append target or a physical model-version generation.""" - mode = config.get("model_change_mode", "incremental_append") - if type(mode) is not str or mode not in {"incremental_append", "full_rebuild"}: - raise ValueError("model_change_mode must be incremental_append or full_rebuild.") - base = config["prediction_table"] - version = config["model_version"] - if not _TABLE_NAME.fullmatch(base): - raise ValueError("prediction_table must be a three-part UC name.") - if ( - type(version) is not str - or not version.isascii() - or not version.isdecimal() - or version[0] == "0" - ): - raise ValueError("model_version must be a concrete positive version.") - if mode == "full_rebuild": - return f"{base}_v{version}" - return base - - -def _managed_prediction_view_exists(spark: Any, logical: str) -> bool: - """Reject a table or unrelated view before creating prediction resources.""" - if not spark.catalog.tableExists(logical): - return False - if spark.catalog.getTable(logical).tableType.upper() != "VIEW": - raise ValueError("Full rebuild needs a view name, but a physical table already uses it.") - marker = spark.sql(f"SHOW TBLPROPERTIES {logical} ('skyulf.mode')").first() - if marker is None or marker["value"] != "full_rebuild": - raise ValueError("Existing prediction view is not managed by Skyulf full rebuild.") - return True - - -def _activate_prediction_view(spark: Any, logical: str, generation: str) -> None: - """Expose a complete generation without replacing prior prediction tables.""" - if ( - not _TABLE_NAME.fullmatch(logical) - or not _TABLE_NAME.fullmatch(generation) - or not re.fullmatch(re.escape(logical) + r"_v[1-9][0-9]*", generation) - ): - raise ValueError("Prediction view and generation names must match one UC target.") - physical = spark.table(generation) - if not physical.limit(1).count(): - raise ValueError("A full-rebuild generation must contain predictions before activation.") - if not _managed_prediction_view_exists(spark, logical): - spark.sql( - f"CREATE VIEW {logical} TBLPROPERTIES ('skyulf.mode' = 'full_rebuild') " - f"AS SELECT * FROM {generation}" - ).collect() - return - active_columns = tuple( - (field.name, field.dataType.typeName()) for field in spark.table(logical).schema.fields - ) - candidate_columns = tuple( - (field.name, field.dataType.typeName()) for field in physical.schema.fields - ) - if active_columns != candidate_columns: - raise ValueError("New prediction generation differs from the active view schema.") - definition = spark.sql(f"SHOW CREATE TABLE {logical}").first() - if definition is not None: - sql = definition["createtab_stmt"].casefold().replace("`", "") - if re.search(r"\bfrom\s+" + re.escape(generation.casefold()) + r"\b", sql): - return - spark.sql(f"ALTER VIEW {logical} AS SELECT * FROM {generation}").collect() - - -def _prediction_columns( - config: dict[str, Any], prepared: Any, source: Any -) -> tuple[tuple[str, str, str], ...]: - """Derive an exact Delta target schema from source keys and saved model outputs.""" - keys = tuple(config["row_keys"]) - inputs = tuple(prepared.artifact.manifest.input_columns) - if not keys or tuple(config["input_columns"]) != inputs: - raise ValueError("Configured keys or model inputs differ from the fitted model.") - names = (*keys, *inputs) - if any(not _IDENTIFIER.fullmatch(name) for name in names): - raise ValueError("Source keys and model inputs need simple column identifiers.") - if len({name.lower() for name in names}) != len(names): - raise ValueError("Source keys and model inputs must be distinct.") - if not set(names).issubset(source.columns): - raise ValueError("Scoring source lacks a row key or fitted model input column.") - columns = [] - for key in keys: - kind = source.schema[key].dataType.typeName() - if kind not in {"string", "long"}: - raise ValueError(f"Source row key {key!r} must be STRING or BIGINT.") - columns.append((key, kind, "STRING" if kind == "string" else "BIGINT")) - for output in prepared.preflight.output_schema: - if not _IDENTIFIER.fullmatch(output.name) or output.dtype not in _OUTPUT_TYPES: - raise ValueError("Saved model output has an unsupported name or type.") - kind, sql_type = _OUTPUT_TYPES[output.dtype] - columns.append((output.name, kind, sql_type)) - columns.extend((name, "string", "STRING") for name in ("run_id", "model_name", "model_version")) - if len({name.lower() for name, _, _ in columns}) != len(columns): - raise ValueError("Prediction columns collide with keys or metadata.") - return tuple(columns) - - -def _check_existing_table(spark: Any, name: str, columns: tuple[tuple[str, str, str], ...]) -> None: - """Reject an existing prediction target with a different schema.""" - actual = {field.name: field.dataType.typeName() for field in spark.table(name).schema.fields} - expected = {column: kind for column, kind, _ in columns} - if actual != expected: - raise ValueError(f"Existing prediction table {name} differs from the model output schema.") - - -def _generation_properties(config: dict[str, Any], prepared: Any) -> dict[str, str]: - """Bind a full-rebuild table to one concrete saved model artifact.""" - digest = prepared.preflight.model_digest - if type(digest) is not str or not re.fullmatch(r"[0-9a-f]{64}", digest): - raise ValueError("Pinned model has no valid artifact digest.") - return { - "skyulf.mode": "full_rebuild", - "skyulf.model_name": config["model_name"], - "skyulf.model_version": config["model_version"], - "skyulf.model_digest": digest, - } - - -def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any) -> bool: - """Preflight an existing source/model and create only a missing output table.""" - source_name = config["score_source_table"] - target_name = config["prediction_table"] - for name in (source_name, target_name, config["model_name"]): - if not _TABLE_NAME.fullmatch(name): - raise ValueError("Scoring needs valid three-part Unity Catalog names.") - if source_name == target_name: - raise ValueError("Prediction output must differ from the source table.") - if not spark.catalog.tableExists(source_name): - raise ValueError(f"Existing input source table is missing: {source_name}.") - if not prepared.preflight.ready: - raise ValueError("The pinned registered model failed Skyulf preflight.") - source = spark.table(source_name) - columns = _prediction_columns(config, prepared, source) - detail = spark.sql(f"DESCRIBE DETAIL {source_name}").first() - properties = detail["properties"] or {} - if not any( - key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" - for key, value in properties.items() - ): - raise ValueError("Scoring source must have Delta Change Data Feed enabled.") - target_exists = spark.catalog.tableExists(target_name) - generation = config.get("model_change_mode") == "full_rebuild" - generation_properties = _generation_properties(config, prepared) if generation else {} - if target_exists: - if generation: - actual_properties = ( - spark.sql(f"DESCRIBE DETAIL {target_name}").first()["properties"] or {} - ) - if any( - actual_properties.get(key) != value for key, value in generation_properties.items() - ): - raise ValueError( - "Existing prediction generation belongs to another model or workflow." - ) - _check_existing_table(spark, target_name, columns) - if not target_exists: - if ( - source.select(*config["row_keys"], *config["input_columns"]) - .limit(config["max_rows"] + 1) - .count() - > config["max_rows"] - ): - raise ValueError("Initial scoring source exceeds the configured max_rows budget.") - definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) - table_properties = "" - if generation: - properties = ", ".join( - f"'{key}' = '{value}'" for key, value in generation_properties.items() - ) - table_properties = f" TBLPROPERTIES ({properties})" - spark.sql( - f"CREATE TABLE {target_name} ({definition}) USING DELTA{table_properties}" - ).collect() - return not target_exists - - -def _training_spec(config: dict[str, Any]) -> LocalTrainingSpec: - """Keep the evaluation split and source snapshot identical across actions.""" - return LocalTrainingSpec( - table=config["training_table"], - version=config["training_version"], - start=datetime.fromisoformat(config["start"]), - holdout_start=datetime.fromisoformat(config["holdout_start"]), - cutoff=datetime.fromisoformat(config["cutoff"]), - event_column=config["event_column"], - label_time_column=config["label_time_column"], - row_keys=tuple(config["row_keys"]), - input_columns=tuple(config["input_columns"]), - target_column=config["target_column"], - max_rows=config["max_rows"], - max_bytes=config["max_bytes"], - ) - - -def _monthly_training_spec(spark: Any, config: dict[str, Any], now: datetime) -> LocalTrainingSpec: - """Pin one Delta version and a UTC calendar window for monthly training.""" - if now.tzinfo is None or now.utcoffset() is None: - raise ValueError("Monthly training needs a timezone-aware run instant.") - lookback = config.get("monthly_lookback_months") - if type(lookback) is not int or not 2 <= lookback <= 120: - raise ValueError("monthly_lookback_months must be an integer from 2 to 120.") - cutoff = now.astimezone(UTC).replace(day=1, hour=0, minute=0, second=0, microsecond=0) - - def months_before(count: int) -> datetime: - """Preserve the first-of-month boundary across year rollover.""" - index = cutoff.year * 12 + cutoff.month - 1 - count - return datetime(index // 12, index % 12 + 1, 1, tzinfo=UTC) - - table = config["training_table"] - if not _TABLE_NAME.fullmatch(table): - raise ValueError("training_table must be a three-part UC name.") - latest = ( - spark.sql(f"DESCRIBE HISTORY {table}") - .select("version") - .orderBy("version", ascending=False) - .first() - ) - if latest is None or type(latest["version"]) is not int: - raise ValueError("Training source has no concrete Delta version.") - return LocalTrainingSpec( - table=table, - version=latest["version"], - start=months_before(lookback), - holdout_start=months_before(1), - cutoff=cutoff, - event_column=config["event_column"], - label_time_column=config["label_time_column"], - row_keys=tuple(config["row_keys"]), - input_columns=tuple(config["input_columns"]), - target_column=config["target_column"], - max_rows=config["max_rows"], - max_bytes=config["max_bytes"], - ) - - -def _monthly_champion_version(config: dict[str, Any]) -> str | None: - """Resolve the current champion once while allowing first-model training.""" - try: - champion = resolve_model( - config["model_name"], - alias="champion", - tracking_uri=config.get("tracking_uri", "databricks"), - registry_uri=config.get("registry_uri", "databricks-uc"), - ) - except RegistryModelNotFoundError: - return None - return champion.version - - -def _automatic_promotion( - spark: Any, config: dict[str, Any], spec: LocalTrainingSpec, candidate: Any -) -> AliasChangeReceipt | None: - """Recheck the pinned holdout before one guarded champion transition.""" - report = candidate.comparison - if report.champion_version is not None and not report.eligible: - return None - frame = read_training_snapshot(spark, spec) - _, heldout, _ = split_labeled_snapshot(frame, spec) - native = pl.from_pandas(heldout) if config["engine"] == "polars" else heldout - options = { - "target_column": spec.target_column, - "admission": ExclusiveAliasWriterAdmission(), - "max_rows": spec.max_rows, - "max_bytes": spec.max_bytes, - "tracking_uri": config.get("tracking_uri", "databricks"), - "registry_uri": config.get("registry_uri", "databricks-uc"), - } - if report.champion_version is None: - return initialize_champion(report, native, **options) - stage_challenger( - report, - native, - expected_champion_version=report.champion_version, - **options, - ) - return promote_candidate( - report, - native, - expected_champion_version=report.champion_version, - **options, - ) - - -def run_action( - spark: Any, - config: dict[str, Any], - action: str, - *, - experiment_name: str | None = None, - artifact_path: str | Path | None = None, - now: datetime | None = None, -) -> Any: - """Delegate training or scoring to Skyulf's existing services.""" - tracking_uri = config.get("tracking_uri", "databricks") - registry_uri = config.get("registry_uri", "databricks-uc") - selection_mode = _selection_mode(config) - if action in {"train", "train_monthly"}: - if experiment_name is None or artifact_path is None: - raise ValueError("Training needs an experiment and temporary artifact path.") - monthly = action == "train_monthly" - if selection_mode == "auto_champion" and config.get("quality_threshold") is None: - raise ValueError("auto_champion requires an absolute quality_threshold.") - spec = ( - _monthly_training_spec(spark, config, now or datetime.now(UTC)) - if monthly - else _training_spec(config) - ) - if selection_mode == "auto_champion": - champion_version = controlled_champion_version( - config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri - ) - elif monthly: - champion_version = _monthly_champion_version(config) - else: - champion_version = config.get("champion_version") - candidate = train_local_candidate( - spark, - spec, - config["pipeline"], - model_name=config["model_name"], - tracking_uri=tracking_uri, - registry_uri=registry_uri, - experiment_name=experiment_name, - run_name="candidate_training", - artifact_path=artifact_path, - metric=config["metric"], - min_improvement=config["min_improvement"], - engine=config["engine"], - champion_version=champion_version, - quality_threshold=config.get("quality_threshold"), - ) - if selection_mode == "auto_champion": - return AutoTrainingOutcome( - candidate=candidate, - alias_change=_automatic_promotion(spark, config, spec, candidate), - ) - return candidate - if action == "score": - if selection_mode == "auto_champion": - champion_version = controlled_champion_version( - config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri - ) - if champion_version is None: - raise ValueError("auto_champion scoring requires a committed champion.") - config = {**config, "model_version": champion_version} - target = _scoring_target(config) - if config.get("model_change_mode", "incremental_append") == "full_rebuild": - _managed_prediction_view_exists(spark, config["prediction_table"]) - score_config = {**config, "prediction_table": target} - prepared = prepare_local_workflow(_scoring_config(score_config)) - provision_prediction_table(spark, score_config, prepared) - result = run_incremental_local_batch( - spark, - prepared, - row_keys=tuple(config["row_keys"]), - admission=SingleWriterAdmission(), - ) - if config.get("model_change_mode", "incremental_append") == "full_rebuild": - _activate_prediction_view(spark, config["prediction_table"], target) - return result - raise ValueError(f"Unknown workflow action: {action}.") +from skyulf.integrations.databricks.local_workflow import resolve_target_config, run_action def main() -> None: diff --git a/skyulf-core/tests/integrations/test_databricks_local_retraining.py b/skyulf-core/tests/integrations/test_databricks_local_retraining.py index a9dc3fa8e..ceeb12689 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_retraining.py +++ b/skyulf-core/tests/integrations/test_databricks_local_retraining.py @@ -144,6 +144,7 @@ def fake_run(*args, **kwargs): """Let publication fail after recording without contacting MLflow.""" yield SimpleNamespace( run_id="run", + client=SimpleNamespace(log_dict=lambda *args, **kwargs: None), log_config=lambda *args, **kwargs: None, log_params=lambda *args, **kwargs: None, set_tags=lambda *args, **kwargs: None, @@ -240,6 +241,25 @@ def test_candidate_workflow_logs_and_registers_without_alias(monkeypatch, tmp_pa assert run.data.metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) assert "candidate_comparison.json" in artifacts assert "model" in artifacts + assert run.data.tags["task"] == "training" + assert "dataset_id" not in run.data.tags and "phase" not in run.data.tags + assert run.data.tags["train_data_destination"] == _spec().table + assert run.data.tags["train_data_version"] == str(_spec().version) + assert run.data.tags["test_data_version"] == str(_spec().version) + assert "training_data.json" in artifacts + model_tags = client.get_model_version(f"candidate_{engine}", "1").tags + assert model_tags["engine"] == engine + assert model_tags["model_type"] == "linear_regression" + assert model_tags["train_data_destination"] == _spec().table + registrations = [] + original_compare = retraining.compare_registered_local_models + + def compare_after_registration(candidate, *args, **kwargs): + """Comparison must follow the orchestrator's explicit registration hook.""" + assert registrations == [candidate] + return original_compare(candidate, *args, **kwargs) + + monkeypatch.setattr(retraining, "compare_registered_local_models", compare_after_registration) next_result = retraining.train_local_candidate( None, _spec(max_rows=12, max_bytes=20000), @@ -254,6 +274,7 @@ def test_candidate_workflow_logs_and_registers_without_alias(monkeypatch, tmp_pa min_improvement=0, engine=engine, champion_version=result.model_version, + on_registered=registrations.append, ) assert next_result.model_version == "2" assert next_result.comparison.champion_version == "1" diff --git a/skyulf-core/tests/integrations/test_databricks_local_workflow.py b/skyulf-core/tests/integrations/test_databricks_local_workflow.py new file mode 100644 index 000000000..38f20d54d --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_local_workflow.py @@ -0,0 +1,813 @@ +"""Reusable Databricks workflow services preserve selection and publication behavior.""" + +from datetime import UTC, datetime, timedelta, timezone +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + + +def _workflow(): + """Use the public library that generated notebooks delegate to.""" + from skyulf.integrations.databricks import local_workflow + + return local_workflow + + +def _output(): + """Inspect output publication independently of notebook widgets.""" + from skyulf.integrations.databricks import prediction_output + + return prediction_output + + +def _config(): + """Keep a concrete, bounded source and model selection in each test.""" + return { + "engine": "polars", + "training_table": "workspace.test.training", + "training_version": 0, + "score_source_table": "workspace.test.source", + "prediction_table": "workspace.test.predictions", + "model_name": "workspace.test.model", + "model_version": "1", + "model_change_mode": "incremental_append", + "champion_version": "1", + "row_keys": ["entity_id"], + "input_columns": ["x"], + "target_column": "target", + "event_column": "event_time", + "label_time_column": "label_at", + "start": "2026-01-01T00:00:00+00:00", + "holdout_start": "2026-02-01T00:00:00+00:00", + "cutoff": "2026-03-01T00:00:00+00:00", + "max_rows": 100, + "max_bytes": 100_000, + "metric": "heldout_rmse", + "min_improvement": 0.0, + "quality_threshold": None, + "pipeline": {"preprocessing": [], "modeling": {"type": "linear_regression"}}, + } + + +def _one_column_schema(kind): + """Model the Spark field names/types used by view compatibility checks.""" + return SimpleNamespace( + fields=[SimpleNamespace(name="prediction", dataType=SimpleNamespace(typeName=lambda: kind))] + ) + + +def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, tmp_path): + """A training job must only produce a candidate with the chosen fit engine.""" + workflow = _workflow() + train = Mock(return_value=SimpleNamespace(model_version="2")) + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr(workflow, "_automatic_promotion", Mock(return_value=None)) + monkeypatch.setattr(workflow, "resolve_model", Mock(return_value=SimpleNamespace(version="1"))) + result = workflow.run_action( + object(), + _config(), + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.model_version == "2" + assert train.call_args.kwargs["engine"] == "polars" + assert train.call_args.args[1].version == 0 + assert callable(train.call_args.kwargs["on_registered"]) + + +def test_monthly_window_pins_current_delta_version_across_year_boundary(): + """A delayed or timezone-shifted run must pin one reproducible monthly window.""" + workflow = _workflow() + history = Mock() + history.select.return_value.orderBy.return_value.first.return_value = {"version": 7} + spark = Mock() + spark.sql.return_value = history + config = _config() + config["monthly_lookback_months"] = 4 + spec = workflow._monthly_training_spec( + spark, config, datetime(2027, 1, 3, 5, tzinfo=timezone(timedelta(hours=2))) + ) + assert (spec.version, spec.start, spec.holdout_start, spec.cutoff) == ( + 7, + datetime(2026, 9, 1, tzinfo=UTC), + datetime(2026, 12, 1, tzinfo=UTC), + datetime(2027, 1, 1, tzinfo=UTC), + ) + spark.sql.assert_called_once_with("DESCRIBE HISTORY workspace.test.training") + + +def test_monthly_training_rejects_missing_version_and_invalid_lookback(): + """A scheduled run must fail before fitting an unpinned or empty window.""" + workflow = _workflow() + spark = Mock() + spark.sql.return_value.select.return_value.orderBy.return_value.first.return_value = None + config = _config() + config["monthly_lookback_months"] = 1 + with pytest.raises(ValueError, match="monthly_lookback_months"): + workflow._monthly_training_spec(spark, config, datetime(2027, 1, 3, tzinfo=UTC)) + config["monthly_lookback_months"] = 3 + with pytest.raises(ValueError, match="version"): + workflow._monthly_training_spec(spark, config, datetime(2027, 1, 3, tzinfo=UTC)) + + +def test_monthly_train_compares_pinned_champion_without_activation(monkeypatch, tmp_path): + """Monthly nomination must not activate a model or change the scorer's pin.""" + workflow = _workflow() + spec = workflow._training_spec(_config()) + train = Mock(return_value=SimpleNamespace(model_version="3")) + champion = Mock(return_value=SimpleNamespace(version="2")) + monkeypatch.setattr(workflow, "_monthly_training_spec", lambda *args: spec) + monkeypatch.setattr(workflow, "resolve_model", champion) + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr(workflow, "_automatic_promotion", Mock(return_value=None)) + config = _config() + config["champion_version"] = None + original_version = config["model_version"] + workflow.run_action( + object(), + config, + "train_monthly", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + now=datetime(2027, 1, 3, tzinfo=UTC), + ) + assert train.call_args.kwargs["champion_version"] == "2" + assert config["model_version"] == original_version + champion.assert_called_once() + + +def test_monthly_train_allows_first_model_but_propagates_registry_errors(monkeypatch): + """Only a missing champion alias is a valid first-training condition.""" + workflow = _workflow() + from skyulf.integrations.mlflow.registry import RegistryModelNotFoundError + + def missing(*args, **kwargs): + """Represent a registry without a champion alias.""" + raise RegistryModelNotFoundError("alias missing") + + monkeypatch.setattr(workflow, "resolve_model", missing) + assert workflow._monthly_champion_version(_config()) is None + monkeypatch.setattr( + workflow, "resolve_model", Mock(side_effect=RuntimeError("permission denied")) + ) + with pytest.raises(RuntimeError, match="permission denied"): + workflow._monthly_champion_version(_config()) + + +def test_auto_champion_train_promotes_only_an_eligible_candidate(monkeypatch, tmp_path): + """A passing candidate must use the pinned holdout and controlled alias APIs.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", quality_threshold=1.0, engine="pandas") + report = SimpleNamespace(champion_version="1", candidate_version="2", eligible=True) + candidate = SimpleNamespace(comparison=report) + frame = object() + heldout = object() + monkeypatch.setattr(workflow, "train_local_candidate", Mock(return_value=candidate)) + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="1")) + monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=frame), raising=False) + monkeypatch.setattr( + workflow, + "split_labeled_snapshot", + Mock(return_value=(object(), heldout, 0)), + raising=False, + ) + stage = Mock(return_value=object()) + promote = Mock(return_value=SimpleNamespace(new_version="2")) + monkeypatch.setattr(workflow, "stage_challenger", stage, raising=False) + monkeypatch.setattr(workflow, "promote_candidate", promote, raising=False) + result = workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.alias_change.new_version == "2" + assert stage.call_args.args[1] is heldout + assert promote.call_args.kwargs["expected_champion_version"] == "1" + + +def test_auto_champion_train_retains_challenger_when_candidate_fails_gate(monkeypatch, tmp_path): + """An unsuccessful challenger stays visible without being promoted.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", quality_threshold=1.0, engine="pandas") + monkeypatch.setattr( + workflow, + "train_local_candidate", + Mock( + return_value=SimpleNamespace( + comparison=SimpleNamespace( + champion_version="1", candidate_version="2", eligible=False + ) + ) + ), + ) + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="1")) + stage = Mock() + monkeypatch.setattr(workflow, "stage_challenger", stage, raising=False) + monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=object())) + monkeypatch.setattr(workflow, "split_labeled_snapshot", Mock(return_value=(None, object(), 0))) + promote = Mock() + monkeypatch.setattr(workflow, "promote_candidate", promote) + result = workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.alias_change is None + stage.assert_called_once() + assert stage.call_args.kwargs["expected_challenger_version"] == "2" + promote.assert_not_called() + + +def test_auto_champion_bootstraps_first_model_or_rejects_missing_threshold(monkeypatch, tmp_path): + """First-model selection requires a real absolute gate before fitting.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", quality_threshold=None, engine="pandas") + train = Mock( + return_value=SimpleNamespace( + comparison=SimpleNamespace( + champion_version=None, + candidate_version="1", + candidate_metrics={"heldout_rmse": 0.1}, + metric="heldout_rmse", + metric_direction="minimize", + quality_threshold=1.0, + ) + ) + ) + monkeypatch.setattr(workflow, "train_local_candidate", train) + with pytest.raises(ValueError, match="quality_threshold"): + workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + train.assert_not_called() + config["quality_threshold"] = 1.0 + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value=None)) + monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=object())) + monkeypatch.setattr( + workflow, + "split_labeled_snapshot", + Mock(return_value=(object(), object(), 0)), + ) + initialize = Mock(return_value=SimpleNamespace(new_version="1")) + monkeypatch.setattr(workflow, "initialize_champion", initialize) + monkeypatch.setattr(workflow, "stage_challenger", Mock()) + result = workflow.run_action( + object(), + config, + "train", + experiment_name="/Users/test/experiment", + artifact_path=tmp_path / "artifact", + ) + assert result.alias_change.new_version == "1" + initialize.assert_called_once() + + +def test_bundle_records_comparison_error_without_promoting(monkeypatch, tmp_path): + """A registered contender must keep an inspectable error when evaluation fails.""" + workflow = _workflow() + monkeypatch.setattr(workflow, "resolve_model", Mock(return_value=SimpleNamespace(version="1"))) + lifecycle = Mock() + monkeypatch.setattr( + workflow, "ChallengerLifecycle", Mock(return_value=lifecycle), raising=False + ) + + def fail_after_registration(*args, **kwargs): + """Expose a version before reproducing the comparison failure.""" + kwargs["on_registered"](object()) + raise RuntimeError("comparison failed") + + monkeypatch.setattr(workflow, "train_local_candidate", fail_after_registration) + with pytest.raises(RuntimeError, match="comparison failed"): + workflow.run_action( + object(), + _config(), + "train", + experiment_name="test", + artifact_path=tmp_path / "artifact", + ) + lifecycle.registered.assert_called_once() + lifecycle.failed.assert_called_once() + + +def test_bundle_records_error_during_final_comparison(monkeypatch, tmp_path): + """The second holdout read and comparison must not leave a contender pending forever.""" + workflow = _workflow() + lifecycle = Mock() + monkeypatch.setattr(workflow, "ChallengerLifecycle", Mock(return_value=lifecycle)) + monkeypatch.setattr(workflow, "resolve_model", Mock(return_value=SimpleNamespace(version="1"))) + monkeypatch.setattr(workflow, "train_local_candidate", Mock(return_value=object())) + monkeypatch.setattr( + workflow, "_automatic_promotion", Mock(side_effect=RuntimeError("recheck failed")) + ) + with pytest.raises(RuntimeError, match="recheck failed"): + workflow.run_action( + object(), + _config(), + "train", + experiment_name="test", + artifact_path=tmp_path / "artifact", + ) + lifecycle.failed.assert_called_once() + + +def test_pinned_training_rejects_stale_comparison_version_before_fit(monkeypatch, tmp_path): + """A historical baseline must not produce a candidate before a known alias conflict.""" + workflow = _workflow() + monkeypatch.setattr(workflow, "resolve_model", Mock(return_value=SimpleNamespace(version="2"))) + train = Mock() + monkeypatch.setattr(workflow, "train_local_candidate", train) + with pytest.raises(ValueError, match="champion_version"): + workflow.run_action( + object(), + _config(), + "train", + experiment_name="test", + artifact_path=tmp_path / "artifact", + ) + train.assert_not_called() + + +def test_auto_champion_score_pins_resolved_version_before_target_selection(monkeypatch): + """A moving alias must become one concrete model and full-rebuild table per run.""" + workflow = _workflow() + config = _config() + config.update(model_selection_mode="auto_champion", model_change_mode="full_rebuild") + controlled = Mock(return_value="2") + prepare = Mock(return_value=object()) + provision = Mock() + monkeypatch.setattr(workflow, "controlled_champion_version", controlled) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "provision_prediction_table", provision) + monkeypatch.setattr(workflow, "run_incremental_local_batch", Mock(return_value=object())) + monkeypatch.setattr(workflow, "_activate_prediction_view", Mock()) + spark = Mock() + spark.catalog.tableExists.return_value = False + workflow.run_action(spark, config, "score") + assert controlled.call_args.args == (config["model_name"],) + assert prepare.call_args.args[0].model.version == "2" + assert provision.call_args.args[1]["prediction_table"] == "workspace.test.predictions_v2" + assert config["model_version"] == "1" + + +def test_score_uses_incremental_service_without_period_or_source_version(monkeypatch): + """Recurring scoring must derive new inserts from committed Delta receipts.""" + workflow = _workflow() + prepare = Mock(return_value=object()) + score = Mock(return_value=SimpleNamespace(noop=False, input_count=2)) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "run_incremental_local_batch", score) + monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) + result = workflow.run_action(object(), _config(), "score") + assert result.input_count == 2 + assert score.call_args.kwargs["row_keys"] == ("entity_id",) + assert "period_start" not in score.call_args.kwargs + assert "source_version" not in score.call_args.kwargs + assert prepare.call_args.args[0].engine == "polars" + assert isinstance(score.call_args.kwargs["admission"], workflow.SingleWriterAdmission) + + +def test_full_rebuild_scores_new_generation_before_view_activation(monkeypatch): + """A v2 rebuild must fill a new table before changing the logical output view.""" + workflow = _workflow() + config = _config() + config.update(model_version="2", model_change_mode="full_rebuild") + events = [] + prepared = Mock() + provision = Mock(side_effect=lambda *args: events.append("provision")) + monkeypatch.setattr( + workflow, + "prepare_local_workflow", + Mock(side_effect=lambda cfg: events.append("prepare") or prepared), + ) + monkeypatch.setattr( + workflow, + "provision_prediction_table", + provision, + ) + monkeypatch.setattr( + workflow, + "run_incremental_local_batch", + Mock(side_effect=lambda *args, **kwargs: events.append("score") or object()), + ) + activate = Mock(side_effect=lambda *args: events.append("activate")) + monkeypatch.setattr(workflow, "_activate_prediction_view", activate) + spark = Mock() + spark.catalog.tableExists.return_value = False + workflow.run_action(spark, config, "score") + assert events == ["prepare", "provision", "score", "activate"] + assert provision.call_args.args[1]["prediction_table"] == "workspace.test.predictions_v2" + assert activate.call_args.args[1:] == ( + "workspace.test.predictions", + "workspace.test.predictions_v2", + ) + + +def test_full_rebuild_does_not_activate_a_failed_generation(monkeypatch): + """A failed full score must leave the active prediction view untouched.""" + workflow = _workflow() + config = _config() + config["model_change_mode"] = "full_rebuild" + monkeypatch.setattr(workflow, "prepare_local_workflow", Mock(return_value=object())) + monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) + monkeypatch.setattr( + workflow, "run_incremental_local_batch", Mock(side_effect=RuntimeError("score failed")) + ) + activate = Mock() + monkeypatch.setattr(workflow, "_activate_prediction_view", activate) + spark = Mock() + spark.catalog.tableExists.return_value = False + with pytest.raises(RuntimeError, match="score failed"): + workflow.run_action(spark, config, "score") + activate.assert_not_called() + + +def test_full_rebuild_rejects_existing_table_before_creating_generation(monkeypatch): + """A mode switch must fail before creating an orphan physical generation.""" + workflow = _workflow() + config = _config() + config["model_change_mode"] = "full_rebuild" + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.catalog.getTable.return_value.tableType = "MANAGED" + prepare = Mock() + provision = Mock() + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "provision_prediction_table", provision) + with pytest.raises(ValueError, match="view name"): + workflow.run_action(spark, config, "score") + prepare.assert_not_called() + provision.assert_not_called() + + +@pytest.mark.parametrize( + "mode,version", [("unknown", "2"), ("full_rebuild", "@champion"), ("full_rebuild", "02")] +) +def test_scoring_rejects_unsafe_model_change_selection(mode, version): + """An invalid mode or moving version must fail before a score target is chosen.""" + workflow = _workflow() + config = _config() + config.update(model_change_mode=mode, model_version=version) + with pytest.raises(ValueError): + workflow._scoring_target(config) + + +def test_full_rebuild_refuses_existing_table_at_logical_view_name(): + """Switching modes must never replace an existing prediction Delta table.""" + workflow = _workflow() + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.catalog.getTable.return_value.tableType = "MANAGED" + spark.table.return_value.limit.return_value.count.return_value = 2 + with pytest.raises(ValueError, match="view name"): + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + spark.sql.assert_not_called() + + +def test_full_rebuild_refuses_foreign_view_and_incompatible_schema(): + """Activation must neither hijack a foreign view nor break its output schema.""" + workflow = _workflow() + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.catalog.getTable.return_value.tableType = "VIEW" + spark.table.return_value.limit.return_value.count.return_value = 2 + spark.sql.return_value.first.return_value = {"value": "other"} + with pytest.raises(ValueError, match="Skyulf"): + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + spark.sql.reset_mock() + spark.sql.return_value.first.return_value = {"value": "full_rebuild"} + spark.table.side_effect = [ + SimpleNamespace( + limit=Mock(return_value=SimpleNamespace(count=lambda: 2)), + schema=_one_column_schema("double"), + ), + SimpleNamespace(schema=_one_column_schema("string")), + ] + with pytest.raises(ValueError, match="schema"): + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + assert all(not call.args[0].startswith("ALTER VIEW") for call in spark.sql.call_args_list) + + +def test_full_rebuild_creates_owned_view_then_preserves_grants_on_switch(): + """A validated generation becomes active through create then ALTER VIEW.""" + workflow = _workflow() + spark = Mock() + spark.table.return_value.limit.return_value.count.return_value = 2 + spark.table.return_value.schema = _one_column_schema("double") + spark.catalog.tableExists.side_effect = [False, True] + spark.catalog.getTable.return_value.tableType = "VIEW" + spark.sql.return_value.first.side_effect = [ + {"value": "full_rebuild"}, + { + "createtab_stmt": "CREATE VIEW workspace.test.predictions AS SELECT * FROM workspace.test.predictions_v1" + }, + ] + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v1" + ) + workflow._activate_prediction_view( + spark, "workspace.test.predictions", "workspace.test.predictions_v2" + ) + statements = [call.args[0] for call in spark.sql.call_args_list] + assert any(statement.startswith("CREATE VIEW") for statement in statements) + assert any(statement.startswith("ALTER VIEW") for statement in statements) + + +def test_lifecycle_actions_are_not_bundle_entry_points(): + """The minimal Bundle must not accidentally mutate registry aliases.""" + workflow = _workflow() + for action in ("compare", "stage", "promote", "setup"): + with pytest.raises(ValueError, match="Unknown workflow action"): + workflow.run_action(object(), _config(), action) + + +def test_target_binding_separates_test_and_prod_outputs(): + """One generated workflow must never reuse a test prediction table in prod.""" + workflow = _workflow() + config = _config() + config.update( + training_table="{catalog}.{input_schema}.labeled_events", + score_source_table="shared.raw.events", + prediction_table="{catalog}.{output_schema}.predictions{resource_suffix}", + model_name="{catalog}.{metadata_schema}.model{resource_suffix}", + ) + shared = { + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + } + test_config = workflow.resolve_target_config( + config, {**shared, "catalog": "test_catalog", "resource_suffix": "_murat"} + ) + syst_config = workflow.resolve_target_config( + config, {**shared, "catalog": "syst_catalog", "resource_suffix": ""} + ) + prod_config = workflow.resolve_target_config( + config, {**shared, "catalog": "prod_catalog", "resource_suffix": ""} + ) + assert test_config["prediction_table"] == "test_catalog.mlresult.predictions_murat" + assert syst_config["prediction_table"] == "syst_catalog.mlresult.predictions" + assert prod_config["prediction_table"] == "prod_catalog.mlresult.predictions" + assert prod_config["score_source_table"] == "shared.raw.events" + assert test_config["model_name"] != prod_config["model_name"] + assert ( + len( + { + test_config["prediction_table"], + syst_config["prediction_table"], + prod_config["prediction_table"], + } + ) + == 3 + ) + assert config["prediction_table"] == "{catalog}.{output_schema}.predictions{resource_suffix}" + + +def test_target_binding_rejects_unsafe_catalog_before_any_job(): + """A malformed target parameter must fail before it reaches a UC operation.""" + workflow = _workflow() + with pytest.raises(ValueError, match="catalog"): + workflow.resolve_target_config( + _config(), + { + "catalog": "prod;DROP TABLE x", + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + "resource_suffix": "", + }, + ) + + +def test_target_binding_rejects_cross_environment_output(): + """A prod job cannot write a model or prediction into a test catalog.""" + workflow = _workflow() + config = _config() + config.update( + model_name="prod_catalog.metadata.model", + ) + config["prediction_table"] = "test_catalog.mlresult.predictions" + with pytest.raises(ValueError, match="prediction_table"): + workflow.resolve_target_config( + config, + { + "catalog": "prod_catalog", + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + "resource_suffix": "", + }, + ) + + +def test_target_binding_rejects_cross_environment_model(): + """A prod train job cannot register a model in a test catalog.""" + workflow = _workflow() + config = _config() + config.update( + prediction_table="prod_catalog.mlresult.predictions", + ) + config["model_name"] = "test_catalog.metadata.model" + with pytest.raises(ValueError, match="model_name"): + workflow.resolve_target_config( + config, + { + "catalog": "prod_catalog", + "input_schema": "refined", + "output_schema": "mlresult", + "metadata_schema": "metadata", + "resource_suffix": "", + }, + ) + + +def test_score_provision_rejects_missing_source_without_creating_tables(): + """A wrong source reference must not create partial prediction resources.""" + workflow = _output() + spark = Mock() + spark.catalog.tableExists.return_value = False + with pytest.raises(ValueError, match="source"): + workflow.provision_prediction_table(spark, _config(), object()) + spark.sql.assert_not_called() + + +def test_score_does_not_require_labeled_training_table(monkeypatch): + """A retired training snapshot must not prevent scoring a live source.""" + workflow = _output() + config = _config() + config["training_table"] = "workspace.test.retired_training" + spark = Mock() + spark.catalog.tableExists.side_effect = lambda name: name != config["training_table"] + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + monkeypatch.setattr(workflow, "_prediction_columns", Mock(return_value=())) + monkeypatch.setattr(workflow, "_check_existing_table", Mock()) + prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True)) + assert workflow.provision_prediction_table(spark, config, prepared) is False + + +def test_score_replay_validates_existing_output_without_recounting_source(monkeypatch): + """A later score must accept a growing source without recreating its output.""" + workflow = _output() + config = _config() + source = Mock() + source.columns = ["entity_id", "x"] + source.schema = { + "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) + } + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.table.return_value = source + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + check_target = Mock() + monkeypatch.setattr(workflow, "_check_existing_table", check_target) + prepared = SimpleNamespace( + artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), + preflight=SimpleNamespace( + ready=True, + output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), + ), + ) + result = workflow.provision_prediction_table(spark, config, prepared) + check_target.assert_called_once() + source.select.assert_not_called() + assert result is False + assert all(not call.args[0].startswith("CREATE TABLE") for call in spark.sql.call_args_list) + + +def test_first_score_provisions_prediction_before_incremental_write(monkeypatch): + """The scheduled score job must handle first-run setup without another job.""" + workflow = _workflow() + events = [] + prepared = object() + monkeypatch.setattr(workflow, "prepare_local_workflow", Mock(return_value=prepared)) + monkeypatch.setattr( + workflow, + "provision_prediction_table", + Mock(side_effect=lambda spark, config, model: events.append("provision")), + raising=False, + ) + monkeypatch.setattr( + workflow, + "run_incremental_local_batch", + Mock(side_effect=lambda *args, **kwargs: events.append("score")), + ) + workflow.run_action(object(), _config(), "score") + assert events == ["provision", "score"] + + +def test_prediction_provision_creates_no_control_table(monkeypatch): + """First scoring must create only the output table, with no lock table.""" + workflow = _output() + config = _config() + source = Mock() + source.columns = ["entity_id", "x"] + source.schema = { + "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) + } + source.select.return_value.limit.return_value.count.return_value = 2 + spark = Mock() + spark.catalog.tableExists.side_effect = lambda name: ( + name + in { + config["training_table"], + config["score_source_table"], + } + ) + spark.table.return_value = source + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + prepared = SimpleNamespace( + artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), + preflight=SimpleNamespace( + ready=True, + output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), + ), + ) + created = workflow.provision_prediction_table(spark, config, prepared) + statements = [call.args[0] for call in spark.sql.call_args_list] + assert created is True + assert len([statement for statement in statements if statement.startswith("CREATE TABLE")]) == 1 + assert all("admission" not in statement for statement in statements) + + +def test_full_rebuild_generation_records_model_identity(monkeypatch): + """A new generation must carry enough provenance to reject unrelated tables.""" + workflow = _output() + config = _config() + config.update( + model_change_mode="full_rebuild", prediction_table="workspace.test.predictions_v2" + ) + spark = Mock() + spark.catalog.tableExists.side_effect = lambda name: name == config["score_source_table"] + spark.sql.return_value.first.return_value = { + "properties": {"delta.enableChangeDataFeed": "true"} + } + spark.table.return_value.select.return_value.limit.return_value.count.return_value = 2 + monkeypatch.setattr( + workflow, "_prediction_columns", Mock(return_value=(("prediction", "double", "DOUBLE"),)) + ) + prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True, model_digest="a" * 64)) + assert workflow.provision_prediction_table(spark, config, prepared) is True + created = next( + call.args[0] for call in spark.sql.call_args_list if call.args[0].startswith("CREATE TABLE") + ) + assert "'skyulf.mode' = 'full_rebuild'" in created + assert "'skyulf.model_name' = 'workspace.test.model'" in created + assert "'skyulf.model_version' = '1'" in created + assert f"'skyulf.model_digest' = '{'a' * 64}'" in created + + +@pytest.mark.parametrize("changed", ["mode", "name", "digest"]) +def test_full_rebuild_rejects_unrelated_or_changed_generation(monkeypatch, changed): + """A same-named table must not be scored or activated under another model.""" + workflow = _output() + config = _config() + config.update( + model_change_mode="full_rebuild", prediction_table="workspace.test.predictions_v2" + ) + expected = { + "skyulf.mode": "full_rebuild", + "skyulf.model_name": config["model_name"], + "skyulf.model_version": config["model_version"], + "skyulf.model_digest": "a" * 64, + } + key = {"mode": "skyulf.mode", "name": "skyulf.model_name", "digest": "skyulf.model_digest"}[ + changed + ] + expected[key] = "other" + spark = Mock() + spark.catalog.tableExists.return_value = True + spark.sql.return_value.first.side_effect = [ + {"properties": {"delta.enableChangeDataFeed": "true"}}, + {"properties": expected}, + ] + monkeypatch.setattr(workflow, "_prediction_columns", Mock(return_value=())) + check_target = Mock() + monkeypatch.setattr(workflow, "_check_existing_table", check_target) + prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True, model_digest="a" * 64)) + with pytest.raises(ValueError, match="another model or workflow"): + workflow.provision_prediction_table(spark, config, prepared) + check_target.assert_not_called() diff --git a/skyulf-core/tests/integrations/test_mlflow_promotion.py b/skyulf-core/tests/integrations/test_mlflow_promotion.py index ea42adbd8..1b98becd3 100644 --- a/skyulf-core/tests/integrations/test_mlflow_promotion.py +++ b/skyulf-core/tests/integrations/test_mlflow_promotion.py @@ -119,7 +119,7 @@ def _stage(case, **changes): def test_stage_challenger_requires_validation_and_preserves_champion(case) -> None: - """Only a freshly eligible candidate becomes challenger without moving production.""" + """Staging verifies evidence while leaving the production version unchanged.""" client, _, name, _, report, _ = case staged = _stage(case) assert staged.kind == "challenger" @@ -137,6 +137,184 @@ def test_stage_challenger_requires_validation_and_preserves_champion(case) -> No _stage(case, report=replace(report, eligible=True, candidate_metrics={"heldout_mse": -1.0})) +def test_rejected_challenger_is_visible_but_cannot_promote(case) -> None: + """A contender's identity must not imply approval to replace champion.""" + client, uri, name, heldout, _, _ = case + report = compare_registered_local_models( + resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri), + resolve_model(name, version="1", tracking_uri=uri, registry_uri=uri), + heldout, + target_column="target", + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=1_000_000, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + _stage(case, report=report) + assert str(client.get_model_version_by_alias(name, "challenger").version) == "2" + assert client.get_model_version(name, "2").tags["validation_status"] == "rejected" + assert ( + client.get_model_version(name, "2").tags["validation_reason"] + == "Improvement below required minimum" + ) + with pytest.raises(ValueError, match="approve"): + _promote(case, report=report) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + +def test_nomination_precedes_evaluation_and_failure_keeps_challenger(case) -> None: + """An evaluation failure remains inspectable without moving production aliases.""" + from skyulf.integrations.mlflow.challenger import ChallengerLifecycle + + client, uri, name, _, _, admission = case + lifecycle = ChallengerLifecycle( + name, + expected_champion_version="1", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + lifecycle.registered(candidate) + first = client.get_registered_model(name).tags["challenger_current_event"] + lifecycle.registered(candidate) + assert client.get_registered_model(name).tags["challenger_current_event"] == first + assert client.get_model_version(name, "2").tags["validation_status"] == "pending" + lifecycle.failed() + assert client.get_model_version(name, "2").tags["validation_status"] == "error" + assert str(client.get_model_version_by_alias(name, "challenger").version) == "2" + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + +def test_tied_v3_remains_challenger_through_rollback_and_v4_replaces_it(case) -> None: + """Retaining an unsuccessful contender must not block safe rollback or later training.""" + from skyulf.integrations.mlflow.challenger import ChallengerLifecycle + + client, uri, name, heldout, _, admission = case + _stage(case) + promoted = _promote(case) + source = client.get_model_version(name, "2").source + register_model(source, name, tracking_uri=uri, registry_uri=uri) + candidate = resolve_model(name, version="3", tracking_uri=uri, registry_uri=uri) + lifecycle = ChallengerLifecycle( + name, + expected_champion_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + lifecycle.registered(candidate) + report = compare_registered_local_models( + candidate, + resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri), + heldout, + target_column="target", + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=0, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + _stage(case, report=report, expected_champion_version="2", expected_challenger_version="3") + assert not report.eligible + rollback_promotion( + promoted, + expected_current_version="2", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + assert str(client.get_model_version_by_alias(name, "challenger").version) == "3" + register_model(source, name, tracking_uri=uri, registry_uri=uri) + next_lifecycle = ChallengerLifecycle( + name, + expected_champion_version="1", + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + next_lifecycle.registered(resolve_model(name, version="4", tracking_uri=uri, registry_uri=uri)) + with pytest.raises(AliasConflictError, match="newer"): + next_lifecycle.registered(candidate) + assert str(client.get_model_version_by_alias(name, "challenger").version) == "4" + assert client.get_model_version(name, "3").tags["validation_status"] == "rejected" + + +def test_first_nominee_is_removed_from_challenger_when_initialized(case) -> None: + """The first champion must still pass quality and stop being its own challenger.""" + from skyulf.integrations.mlflow.challenger import ChallengerLifecycle + from skyulf.integrations.mlflow.promotion import initialize_champion + + client, uri, name, heldout, _, admission = case + client.delete_registered_model_alias(name, "champion") + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + lifecycle = ChallengerLifecycle( + name, + expected_champion_version=None, + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + lifecycle.registered(candidate) + report = compare_registered_local_models( + candidate, + None, + heldout, + target_column="target", + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=0, + quality_threshold=1.0, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + _stage(case, report=report, expected_champion_version=None, expected_challenger_version="2") + assert client.get_model_version(name, "2").tags["validation_status"] == "passed" + initialize_champion( + report, + heldout, + target_column="target", + admission=admission, + max_rows=10, + max_bytes=10_000, + tracking_uri=uri, + registry_uri=uri, + ) + with pytest.raises(mlflow.exceptions.MlflowException): + client.get_model_version_by_alias(name, "challenger") + assert client.get_model_version(name, "2").tags["promotion_status"] == "promoted" + + +def test_partial_challenger_status_write_keeps_pending_receipt(case, monkeypatch) -> None: + """Partial UI status must never be reported as a completed registry transition.""" + from skyulf.integrations.mlflow.promotion import controlled_champion_version + + client, uri, name, _, _, _ = case + original = client.set_model_version_tag + + def fail_reason(model_name, version, key, value): + """Simulate loss of the status write after the alias and first tag changed.""" + if key == "validation_reason": + raise RuntimeError("tag transport failed") + return original(model_name, version, key, value) + + monkeypatch.setattr(client, "set_model_version_tag", fail_reason) + monkeypatch.setattr("skyulf.integrations.mlflow.promotion._make_client", lambda *args: client) + with pytest.raises(AliasOutcomeUnknownError, match="Alias may have changed"): + _stage(case) + with pytest.raises(AliasConflictError, match="pending"): + controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + def test_promotion_requires_staged_challenger(case) -> None: """A direct or tampered challenger alias must not bypass the validated staging step.""" client, _, name, _, _, _ = case @@ -149,7 +327,8 @@ def test_promotion_requires_staged_challenger(case) -> None: assert str(client.get_model_version_by_alias(name, "champion").version) == "1" -def test_promote_and_rollback_persist_receipts(case) -> None: +@pytest.mark.parametrize("receipt_format", ["current", "readable_v1"]) +def test_promote_and_rollback_persist_receipts(case, receipt_format) -> None: """An accepted candidate moves the alias and leaves auditable forward and reverse receipts.""" client, uri, name, _, _, admission = case @@ -164,7 +343,16 @@ def test_promote_and_rollback_persist_receipts(case) -> None: assert "challenger_current_event" not in client.get_registered_model(name).tags tag = client.get_model_version(name, "2").tags[f"promotion_{receipt.event_id}"] assert len(tag.encode("utf-8")) <= 256 - assert json.loads(tag)["s"] == "committed" + assert json.loads(tag)["state"] == "committed" + assert json.loads(tag)["action"] == "promotion" + assert json.loads(tag)["from_version"] == "1" + assert "from" not in json.loads(tag) + if receipt_format == "readable_v1": + old_payload = json.loads(tag) + old_payload["from"] = old_payload.pop("from_version") + client.set_model_version_tag( + name, "2", f"promotion_{receipt.event_id}", json.dumps(old_payload) + ) assert json.loads(client.get_registered_model(name).tags["champion_current_event"]) == { "event_id": receipt.event_id, "version": "2", @@ -412,7 +600,7 @@ def test_controlled_champion_rejects_alias_without_receipt(case) -> None: client, uri, name, _, _, _ = case with pytest.raises(AliasConflictError, match="committed receipt"): controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) - client.set_registered_model_tag(name, "skyulf_pending_alias_event", "unresolved") + client.set_registered_model_tag(name, "pending_alias_event", "unresolved") with pytest.raises(AliasConflictError, match="pending"): controlled_champion_version(name, tracking_uri=uri, registry_uri=uri) @@ -478,7 +666,7 @@ def move_then_fail(model_name, alias, version): with pytest.raises(AliasOutcomeUnknownError, match="inspect prepared event"): _promote(case) assert str(client.get_model_version_by_alias(name, "champion").version) == "2" - assert client.get_registered_model(name).tags.get("skyulf_pending_alias_event") + assert client.get_registered_model(name).tags.get("pending_alias_event") from skyulf.integrations.mlflow.promotion import controlled_champion_version with pytest.raises(AliasConflictError, match="pending"): @@ -516,3 +704,11 @@ def test_global_uc_registry_rejects_local_admission(tmp_path, monkeypatch) -> No monkeypatch.setattr(mlflow, "get_registry_uri", lambda: "databricks-uc") with pytest.raises(ValueError, match="distributed"): _admission(LocalAliasAdmission(tmp_path / "locks"), None) + + +def test_receipt_rejects_conflicting_version_field_names() -> None: + """Legacy and current field names must never silently choose different prior versions.""" + from skyulf.integrations.mlflow.promotion import _read_event + + with pytest.raises(ValueError, match="[Dd]uplicate|[Aa]mbiguous"): + _read_event(json.dumps({"action": "promotion", "from": "1", "from_version": "2"})) diff --git a/tests/integration/test_bundle_challenger_lifecycle.py b/tests/integration/test_bundle_challenger_lifecycle.py new file mode 100644 index 000000000..3adc3cb10 --- /dev/null +++ b/tests/integration/test_bundle_challenger_lifecycle.py @@ -0,0 +1,104 @@ +"""Exercise generated lifecycle orchestration against a real local MLflow store.""" + +import importlib.util +from pathlib import Path + +import pandas as pd +import pytest + +from skyulf.integrations.databricks import local_retraining, local_workflow + +mlflow = pytest.importorskip("mlflow") + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_bundle_nomination_comparison_and_promotion_are_separate(tmp_path, monkeypatch, engine): + """Real artifacts must retain a tied contender and survive failed comparison on either engine.""" + path = Path(__file__).resolve().parents[2] / ( + "skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py" + ) + spec = importlib.util.spec_from_file_location("sm30_workflow", path) + assert spec is not None and spec.loader is not None + workflow = importlib.util.module_from_spec(spec) + spec.loader.exec_module(workflow) + frame = pd.DataFrame( + { + "id": range(12), + "x": [float(value) for value in range(12)], + "target": [10.0 + 2 * value for value in range(12)], + "event_time": pd.to_datetime(["2026-01-10"] * 8 + ["2026-02-10"] * 4, utc=True), + "label_at": pd.to_datetime(["2026-01-11"] * 8 + ["2026-02-11"] * 4, utc=True), + } + ) + monkeypatch.setattr(local_retraining, "read_training_snapshot", lambda *args: frame) + monkeypatch.setattr(local_workflow, "read_training_snapshot", lambda *args: frame) + store = f"sqlite:///{(tmp_path / 'registry.db').as_posix()}" + client = mlflow.MlflowClient(tracking_uri=store, registry_uri=store) + client.create_experiment("lifecycle", artifact_location=(tmp_path / "mlruns").as_uri()) + config = { + "engine": engine, + "training_table": "workspace.test.source", + "training_version": 0, + "model_name": "lifecycle_model", + "tracking_uri": store, + "registry_uri": store, + "model_selection_mode": "auto_champion", + "model_version": "1", + "row_keys": ["id"], + "input_columns": ["x"], + "target_column": "target", + "event_column": "event_time", + "label_time_column": "label_at", + "start": "2026-01-01T00:00:00+00:00", + "holdout_start": "2026-02-01T00:00:00+00:00", + "cutoff": "2026-03-01T00:00:00+00:00", + "max_rows": 20, + "max_bytes": 100_000, + "metric": "heldout_rmse", + "min_improvement": 0.1, + "quality_threshold": 100.0, + "pipeline": { + "preprocessing": [], + "modeling": { + "type": "linear_regression", + "params": {"fit_intercept": False}, + }, + }, + } + + def run(version): + """Use the exact template action with only its Spark input boundary replaced.""" + return workflow.run_action( + None, + config, + "train", + experiment_name="lifecycle", + artifact_path=tmp_path / f"model-{version}", + ) + + first = run(1) + assert first.alias_change.kind == "initial" + config["pipeline"]["modeling"]["params"]["fit_intercept"] = True + second = run(2) + assert second.alias_change.kind == "promotion" + third = run(3) + assert third.alias_change is None + assert str(client.get_model_version_by_alias("lifecycle_model", "champion").version) == "2" + assert str(client.get_model_version_by_alias("lifecycle_model", "challenger").version) == "3" + assert client.get_model_version("lifecycle_model", "3").tags["validation_status"] == "rejected" + config["model_selection_mode"] = "pinned_version" + fourth = run(4) + assert fourth.model_version == "4" and config["model_version"] == "1" + assert str(client.get_model_version_by_alias("lifecycle_model", "champion").version) == "2" + assert str(client.get_model_version_by_alias("lifecycle_model", "challenger").version) == "4" + + def comparison_fails(*args, **kwargs): + """Fail after nomination to preserve evidence for a registered contender.""" + raise RuntimeError("comparison unavailable") + + monkeypatch.setattr(local_retraining, "compare_registered_local_models", comparison_fails) + with pytest.raises(RuntimeError, match="comparison unavailable"): + run(5) + assert str(client.get_model_version_by_alias("lifecycle_model", "champion").version) == "2" + assert str(client.get_model_version_by_alias("lifecycle_model", "challenger").version) == "5" + assert client.get_model_version("lifecycle_model", "5").tags["validation_status"] == "error" diff --git a/tests/integration/test_sm20a_bundle_template.py b/tests/integration/test_sm20a_bundle_template.py index 0659f30d4..b152806c2 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/tests/integration/test_sm20a_bundle_template.py @@ -1,12 +1,9 @@ """The generated local Bundle delegates to Skyulf's verified services.""" -import importlib.util import json import re -from datetime import UTC, datetime, timedelta, timezone from pathlib import Path from types import SimpleNamespace -from unittest.mock import Mock import pytest @@ -17,44 +14,20 @@ def _workflow(): - """Load the source copied unchanged into every generated project.""" - spec = importlib.util.spec_from_file_location("sm20a_workflow", WORKFLOW) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module + """Use the public library that generated notebooks delegate to.""" + from skyulf.integrations.databricks import local_workflow + return local_workflow -def _config(): - """Keep a concrete, bounded source and model selection in each test.""" - return { - "engine": "polars", - "training_table": "workspace.test.training", - "training_version": 0, - "score_source_table": "workspace.test.source", - "prediction_table": "workspace.test.predictions", - "model_name": "workspace.test.model", - "model_version": "1", - "model_change_mode": "incremental_append", - "champion_version": "1", - "row_keys": ["entity_id"], - "input_columns": ["x"], - "target_column": "target", - "event_column": "event_time", - "label_time_column": "label_at", - "start": "2026-01-01T00:00:00+00:00", - "holdout_start": "2026-02-01T00:00:00+00:00", - "cutoff": "2026-03-01T00:00:00+00:00", - "max_rows": 100, - "max_bytes": 100_000, - "metric": "heldout_rmse", - "min_improvement": 0.0, - "quality_threshold": None, - "pipeline": {"preprocessing": [], "modeling": {"type": "linear_regression"}}, - } + +def _output(): + """Inspect output publication independently of notebook widgets.""" + from skyulf.integrations.databricks import prediction_output + + return prediction_output -def _render_default_config(row_key="entity_id"): +def _render_default_config(row_key="entity_id", risk_category=""): """Resolve the manual-mode template fields read by the generated-config tests.""" template = WORKFLOW.parents[1] / "config/workflow.json.tmpl" content = ( @@ -63,6 +36,10 @@ def _render_default_config(row_key="entity_id"): .replace("{{.engine}}", "pandas") .replace("{{.row_key}}", row_key) .replace("{{.min_improvement}}", "0.0") + .replace( + '{{if .risk_category}}"{{.risk_category}}"{{else}}null{{end}}', + json.dumps(risk_category or None), + ) .replace( '{{if eq .model_selection_mode "auto_champion"}}{{.quality_threshold}}{{else}}null{{end}}', "null", @@ -71,503 +48,30 @@ def _render_default_config(row_key="entity_id"): return json.loads(content) -def _one_column_schema(kind): - """Model the Spark field names/types used by view compatibility checks.""" - return SimpleNamespace( - fields=[SimpleNamespace(name="prediction", dataType=SimpleNamespace(typeName=lambda: kind))] - ) - - -def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, tmp_path): - """A training job must only produce a candidate with the chosen fit engine.""" - workflow = _workflow() - train = Mock(return_value=SimpleNamespace(model_version="2")) - monkeypatch.setattr(workflow, "train_local_candidate", train) - result = workflow.run_action( - object(), - _config(), - "train", - experiment_name="/Users/test/experiment", - artifact_path=tmp_path / "artifact", - ) - assert result.model_version == "2" - assert train.call_args.kwargs["engine"] == "polars" - assert train.call_args.args[1].version == 0 - - -def test_monthly_window_pins_current_delta_version_across_year_boundary(): - """A delayed or timezone-shifted run must pin one reproducible monthly window.""" - workflow = _workflow() - history = Mock() - history.select.return_value.orderBy.return_value.first.return_value = {"version": 7} - spark = Mock() - spark.sql.return_value = history - config = _config() - config["monthly_lookback_months"] = 4 - spec = workflow._monthly_training_spec( - spark, config, datetime(2027, 1, 3, 5, tzinfo=timezone(timedelta(hours=2))) - ) - assert (spec.version, spec.start, spec.holdout_start, spec.cutoff) == ( - 7, - datetime(2026, 9, 1, tzinfo=UTC), - datetime(2026, 12, 1, tzinfo=UTC), - datetime(2027, 1, 1, tzinfo=UTC), - ) - spark.sql.assert_called_once_with("DESCRIBE HISTORY workspace.test.training") - - -def test_monthly_training_rejects_missing_version_and_invalid_lookback(): - """A scheduled run must fail before fitting an unpinned or empty window.""" - workflow = _workflow() - spark = Mock() - spark.sql.return_value.select.return_value.orderBy.return_value.first.return_value = None - config = _config() - config["monthly_lookback_months"] = 1 - with pytest.raises(ValueError, match="monthly_lookback_months"): - workflow._monthly_training_spec(spark, config, datetime(2027, 1, 3, tzinfo=UTC)) - config["monthly_lookback_months"] = 3 - with pytest.raises(ValueError, match="version"): - workflow._monthly_training_spec(spark, config, datetime(2027, 1, 3, tzinfo=UTC)) - - -def test_monthly_train_compares_pinned_champion_without_activation(monkeypatch, tmp_path): - """A monthly candidate must not change aliases or the scorer's pinned model.""" - workflow = _workflow() - spec = workflow._training_spec(_config()) - train = Mock(return_value=SimpleNamespace(model_version="3")) - champion = Mock(return_value=SimpleNamespace(version="2")) - monkeypatch.setattr(workflow, "_monthly_training_spec", lambda *args: spec) - monkeypatch.setattr(workflow, "resolve_model", champion) - monkeypatch.setattr(workflow, "train_local_candidate", train) - config = _config() - original_version = config["model_version"] - workflow.run_action( - object(), - config, - "train_monthly", - experiment_name="/Users/test/experiment", - artifact_path=tmp_path / "artifact", - now=datetime(2027, 1, 3, tzinfo=UTC), - ) - assert train.call_args.kwargs["champion_version"] == "2" - assert config["model_version"] == original_version - champion.assert_called_once() - - -def test_monthly_train_allows_first_model_but_propagates_registry_errors(monkeypatch): - """Only a missing champion alias is a valid first-training condition.""" - workflow = _workflow() - from skyulf.integrations.mlflow.registry import RegistryModelNotFoundError - - def missing(*args, **kwargs): - """Represent a registry without a champion alias.""" - raise RegistryModelNotFoundError("alias missing") - - monkeypatch.setattr(workflow, "resolve_model", missing) - assert workflow._monthly_champion_version(_config()) is None - monkeypatch.setattr( - workflow, "resolve_model", Mock(side_effect=RuntimeError("permission denied")) - ) - with pytest.raises(RuntimeError, match="permission denied"): - workflow._monthly_champion_version(_config()) - - -def test_auto_champion_train_promotes_only_an_eligible_candidate(monkeypatch, tmp_path): - """A passing candidate must use the pinned holdout and controlled alias APIs.""" - workflow = _workflow() - config = _config() - config.update(model_selection_mode="auto_champion", quality_threshold=1.0, engine="pandas") - report = SimpleNamespace(champion_version="1", eligible=True) - candidate = SimpleNamespace(comparison=report) - frame = object() - heldout = object() - monkeypatch.setattr(workflow, "train_local_candidate", Mock(return_value=candidate)) - monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="1")) - monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=frame), raising=False) - monkeypatch.setattr( - workflow, - "split_labeled_snapshot", - Mock(return_value=(object(), heldout, 0)), - raising=False, - ) - stage = Mock(return_value=object()) - promote = Mock(return_value=SimpleNamespace(new_version="2")) - monkeypatch.setattr(workflow, "stage_challenger", stage, raising=False) - monkeypatch.setattr(workflow, "promote_candidate", promote, raising=False) - result = workflow.run_action( - object(), - config, - "train", - experiment_name="/Users/test/experiment", - artifact_path=tmp_path / "artifact", - ) - assert result.alias_change.new_version == "2" - assert stage.call_args.args[1] is heldout - assert promote.call_args.kwargs["expected_champion_version"] == "1" - - -def test_auto_champion_train_leaves_alias_when_candidate_fails_gate(monkeypatch, tmp_path): - """A failed comparison must never stage or promote its registered model.""" - workflow = _workflow() - config = _config() - config.update(model_selection_mode="auto_champion", quality_threshold=1.0, engine="pandas") - monkeypatch.setattr( - workflow, - "train_local_candidate", - Mock( - return_value=SimpleNamespace( - comparison=SimpleNamespace(champion_version="1", eligible=False) - ) - ), - ) - monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="1")) - stage = Mock() - monkeypatch.setattr(workflow, "stage_challenger", stage, raising=False) - result = workflow.run_action( - object(), - config, - "train", - experiment_name="/Users/test/experiment", - artifact_path=tmp_path / "artifact", - ) - assert result.alias_change is None - stage.assert_not_called() - - -def test_auto_champion_bootstraps_first_model_or_rejects_missing_threshold(monkeypatch, tmp_path): - """First-model selection requires a real absolute gate before fitting.""" - workflow = _workflow() - config = _config() - config.update(model_selection_mode="auto_champion", quality_threshold=None, engine="pandas") - train = Mock(return_value=SimpleNamespace(comparison=SimpleNamespace(champion_version=None))) - monkeypatch.setattr(workflow, "train_local_candidate", train) - with pytest.raises(ValueError, match="quality_threshold"): - workflow.run_action( - object(), - config, - "train", - experiment_name="/Users/test/experiment", - artifact_path=tmp_path / "artifact", - ) - train.assert_not_called() - config["quality_threshold"] = 1.0 - monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value=None)) - monkeypatch.setattr(workflow, "read_training_snapshot", Mock(return_value=object())) - monkeypatch.setattr( - workflow, - "split_labeled_snapshot", - Mock(return_value=(object(), object(), 0)), - ) - initialize = Mock(return_value=SimpleNamespace(new_version="1")) - monkeypatch.setattr(workflow, "initialize_champion", initialize) - result = workflow.run_action( - object(), - config, - "train", - experiment_name="/Users/test/experiment", - artifact_path=tmp_path / "artifact", - ) - assert result.alias_change.new_version == "1" - initialize.assert_called_once() - - -def test_auto_champion_score_pins_resolved_version_before_target_selection(monkeypatch): - """A moving alias must become one concrete model and full-rebuild table per run.""" - workflow = _workflow() - config = _config() - config.update(model_selection_mode="auto_champion", model_change_mode="full_rebuild") - controlled = Mock(return_value="2") - prepare = Mock(return_value=object()) - provision = Mock() - monkeypatch.setattr(workflow, "controlled_champion_version", controlled) - monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) - monkeypatch.setattr(workflow, "provision_prediction_table", provision) - monkeypatch.setattr(workflow, "run_incremental_local_batch", Mock(return_value=object())) - monkeypatch.setattr(workflow, "_activate_prediction_view", Mock()) - spark = Mock() - spark.catalog.tableExists.return_value = False - workflow.run_action(spark, config, "score") - assert controlled.call_args.args == (config["model_name"],) - assert prepare.call_args.args[0].model.version == "2" - assert provision.call_args.args[1]["prediction_table"] == "workspace.test.predictions_v2" - assert config["model_version"] == "1" - - -def test_score_uses_incremental_service_without_period_or_source_version(monkeypatch): - """Recurring scoring must derive new inserts from committed Delta receipts.""" - workflow = _workflow() - prepare = Mock(return_value=object()) - score = Mock(return_value=SimpleNamespace(noop=False, input_count=2)) - monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) - monkeypatch.setattr(workflow, "run_incremental_local_batch", score) - monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) - result = workflow.run_action(object(), _config(), "score") - assert result.input_count == 2 - assert score.call_args.kwargs["row_keys"] == ("entity_id",) - assert "period_start" not in score.call_args.kwargs - assert "source_version" not in score.call_args.kwargs - assert prepare.call_args.args[0].engine == "polars" - assert isinstance(score.call_args.kwargs["admission"], workflow.SingleWriterAdmission) - - -def test_full_rebuild_scores_new_generation_before_view_activation(monkeypatch): - """A v2 rebuild must fill a new table before changing the logical output view.""" - workflow = _workflow() - config = _config() - config.update(model_version="2", model_change_mode="full_rebuild") - events = [] - prepared = Mock() - provision = Mock(side_effect=lambda *args: events.append("provision")) - monkeypatch.setattr( - workflow, - "prepare_local_workflow", - Mock(side_effect=lambda cfg: events.append("prepare") or prepared), - ) - monkeypatch.setattr( - workflow, - "provision_prediction_table", - provision, - ) - monkeypatch.setattr( - workflow, - "run_incremental_local_batch", - Mock(side_effect=lambda *args, **kwargs: events.append("score") or object()), - ) - activate = Mock(side_effect=lambda *args: events.append("activate")) - monkeypatch.setattr(workflow, "_activate_prediction_view", activate) - spark = Mock() - spark.catalog.tableExists.return_value = False - workflow.run_action(spark, config, "score") - assert events == ["prepare", "provision", "score", "activate"] - assert provision.call_args.args[1]["prediction_table"] == "workspace.test.predictions_v2" - assert activate.call_args.args[1:] == ( - "workspace.test.predictions", - "workspace.test.predictions_v2", - ) - - -def test_full_rebuild_does_not_activate_a_failed_generation(monkeypatch): - """A failed full score must leave the active prediction view untouched.""" - workflow = _workflow() - config = _config() - config["model_change_mode"] = "full_rebuild" - monkeypatch.setattr(workflow, "prepare_local_workflow", Mock(return_value=object())) - monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) - monkeypatch.setattr( - workflow, "run_incremental_local_batch", Mock(side_effect=RuntimeError("score failed")) - ) - activate = Mock() - monkeypatch.setattr(workflow, "_activate_prediction_view", activate) - spark = Mock() - spark.catalog.tableExists.return_value = False - with pytest.raises(RuntimeError, match="score failed"): - workflow.run_action(spark, config, "score") - activate.assert_not_called() - - -def test_full_rebuild_rejects_existing_table_before_creating_generation(monkeypatch): - """A mode switch must fail before creating an orphan physical generation.""" - workflow = _workflow() - config = _config() - config["model_change_mode"] = "full_rebuild" - spark = Mock() - spark.catalog.tableExists.return_value = True - spark.catalog.getTable.return_value.tableType = "MANAGED" - prepare = Mock() - provision = Mock() - monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) - monkeypatch.setattr(workflow, "provision_prediction_table", provision) - with pytest.raises(ValueError, match="view name"): - workflow.run_action(spark, config, "score") - prepare.assert_not_called() - provision.assert_not_called() - - -@pytest.mark.parametrize( - "mode,version", [("unknown", "2"), ("full_rebuild", "@champion"), ("full_rebuild", "02")] -) -def test_scoring_rejects_unsafe_model_change_selection(mode, version): - """An invalid mode or moving version must fail before a score target is chosen.""" - workflow = _workflow() - config = _config() - config.update(model_change_mode=mode, model_version=version) - with pytest.raises(ValueError): - workflow._scoring_target(config) - - -def test_full_rebuild_refuses_existing_table_at_logical_view_name(): - """Switching modes must never replace an existing prediction Delta table.""" - workflow = _workflow() - spark = Mock() - spark.catalog.tableExists.return_value = True - spark.catalog.getTable.return_value.tableType = "MANAGED" - spark.table.return_value.limit.return_value.count.return_value = 2 - with pytest.raises(ValueError, match="view name"): - workflow._activate_prediction_view( - spark, "workspace.test.predictions", "workspace.test.predictions_v2" - ) - spark.sql.assert_not_called() - - -def test_full_rebuild_refuses_foreign_view_and_incompatible_schema(): - """Activation must neither hijack a foreign view nor break its output schema.""" - workflow = _workflow() - spark = Mock() - spark.catalog.tableExists.return_value = True - spark.catalog.getTable.return_value.tableType = "VIEW" - spark.table.return_value.limit.return_value.count.return_value = 2 - spark.sql.return_value.first.return_value = {"value": "other"} - with pytest.raises(ValueError, match="Skyulf"): - workflow._activate_prediction_view( - spark, "workspace.test.predictions", "workspace.test.predictions_v2" - ) - spark.sql.reset_mock() - spark.sql.return_value.first.return_value = {"value": "full_rebuild"} - spark.table.side_effect = [ - SimpleNamespace( - limit=Mock(return_value=SimpleNamespace(count=lambda: 2)), - schema=_one_column_schema("double"), - ), - SimpleNamespace(schema=_one_column_schema("string")), - ] - with pytest.raises(ValueError, match="schema"): - workflow._activate_prediction_view( - spark, "workspace.test.predictions", "workspace.test.predictions_v2" - ) - assert all(not call.args[0].startswith("ALTER VIEW") for call in spark.sql.call_args_list) - - -def test_full_rebuild_creates_owned_view_then_preserves_grants_on_switch(): - """A validated generation becomes active through create then ALTER VIEW.""" - workflow = _workflow() - spark = Mock() - spark.table.return_value.limit.return_value.count.return_value = 2 - spark.table.return_value.schema = _one_column_schema("double") - spark.catalog.tableExists.side_effect = [False, True] - spark.catalog.getTable.return_value.tableType = "VIEW" - spark.sql.return_value.first.side_effect = [ - {"value": "full_rebuild"}, - { - "createtab_stmt": "CREATE VIEW workspace.test.predictions AS SELECT * FROM workspace.test.predictions_v1" - }, - ] - workflow._activate_prediction_view( - spark, "workspace.test.predictions", "workspace.test.predictions_v1" - ) - workflow._activate_prediction_view( - spark, "workspace.test.predictions", "workspace.test.predictions_v2" - ) - statements = [call.args[0] for call in spark.sql.call_args_list] - assert any(statement.startswith("CREATE VIEW") for statement in statements) - assert any(statement.startswith("ALTER VIEW") for statement in statements) - - -def test_lifecycle_actions_are_not_bundle_entry_points(): - """The minimal Bundle must not accidentally mutate registry aliases.""" - workflow = _workflow() - for action in ("compare", "stage", "promote", "setup"): - with pytest.raises(ValueError, match="Unknown workflow action"): - workflow.run_action(object(), _config(), action) - - -def test_target_binding_separates_test_and_prod_outputs(): - """One generated workflow must never reuse a test prediction table in prod.""" - workflow = _workflow() - config = _config() - config.update( - training_table="{catalog}.{input_schema}.labeled_events", - score_source_table="shared.raw.events", - prediction_table="{catalog}.{output_schema}.predictions{resource_suffix}", - model_name="{catalog}.{metadata_schema}.model{resource_suffix}", - ) - shared = { - "input_schema": "refined", - "output_schema": "mlresult", - "metadata_schema": "metadata", - } - test_config = workflow.resolve_target_config( - config, {**shared, "catalog": "test_catalog", "resource_suffix": "_murat"} - ) - syst_config = workflow.resolve_target_config( - config, {**shared, "catalog": "syst_catalog", "resource_suffix": ""} - ) - prod_config = workflow.resolve_target_config( - config, {**shared, "catalog": "prod_catalog", "resource_suffix": ""} - ) - assert test_config["prediction_table"] == "test_catalog.mlresult.predictions_murat" - assert syst_config["prediction_table"] == "syst_catalog.mlresult.predictions" - assert prod_config["prediction_table"] == "prod_catalog.mlresult.predictions" - assert prod_config["score_source_table"] == "shared.raw.events" - assert test_config["model_name"] != prod_config["model_name"] - assert ( - len( - { - test_config["prediction_table"], - syst_config["prediction_table"], - prod_config["prediction_table"], - } - ) - == 3 - ) - assert config["prediction_table"] == "{catalog}.{output_schema}.predictions{resource_suffix}" - - -def test_target_binding_rejects_unsafe_catalog_before_any_job(): - """A malformed target parameter must fail before it reaches a UC operation.""" - workflow = _workflow() - with pytest.raises(ValueError, match="catalog"): - workflow.resolve_target_config( - _config(), - { - "catalog": "prod;DROP TABLE x", - "input_schema": "refined", - "output_schema": "mlresult", - "metadata_schema": "metadata", - "resource_suffix": "", - }, - ) - - -def test_target_binding_rejects_cross_environment_output(): - """A prod job cannot write a model or prediction into a test catalog.""" - workflow = _workflow() - config = _config() - config.update( - model_name="prod_catalog.metadata.model", +@pytest.mark.parametrize("risk_category", ["", "Low", "High"]) +def test_bundle_risk_category_is_optional_and_configurable(risk_category): + """Initialization must preserve the chosen business label without inventing a default risk.""" + root = WORKFLOW.parents[3] + schema = json.loads((root / "databricks_template_schema.json").read_text()) + choice = schema["properties"]["risk_category"] + assert choice["default"] == "" + assert re.fullmatch(choice["pattern"], risk_category) + assert not re.fullmatch(choice["pattern"], 'Low"invalid') + assert _render_default_config(risk_category=risk_category)["risk_category"] == ( + risk_category or None ) - config["prediction_table"] = "test_catalog.mlresult.predictions" - with pytest.raises(ValueError, match="prediction_table"): - workflow.resolve_target_config( - config, - { - "catalog": "prod_catalog", - "input_schema": "refined", - "output_schema": "mlresult", - "metadata_schema": "metadata", - "resource_suffix": "", - }, - ) -def test_target_binding_rejects_cross_environment_model(): - """A prod train job cannot register a model in a test catalog.""" - workflow = _workflow() - config = _config() - config.update( - prediction_table="prod_catalog.mlresult.predictions", - ) - config["model_name"] = "test_catalog.metadata.model" - with pytest.raises(ValueError, match="model_name"): - workflow.resolve_target_config( - config, - { - "catalog": "prod_catalog", - "input_schema": "refined", - "output_schema": "mlresult", - "metadata_schema": "metadata", - "resource_suffix": "", - }, - ) +def test_company_cost_tag_example_keeps_the_generic_cluster_choice(): + """A company setup must select PayingRegNo without changing the generic template default.""" + root = WORKFLOW.parents[3] + schema = json.loads((root / "databricks_template_schema.json").read_text()) + example = json.loads((root / "examples/paying-reg-no-init.example.json").read_text()) + assert schema["properties"]["cost_tag_key"]["default"] == "CostCenter" + assert "PayingRegNo" in schema["properties"]["cost_tag_key"]["description"] + assert example["cost_tag_key"] == "PayingRegNo" + assert example["compute_mode"] == "policy_cluster" + assert example["cost_tag_value"] == "REPLACE_WITH_PAYING_REG_NO" def test_generated_config_keeps_company_output_in_each_target(): @@ -617,180 +121,6 @@ def test_minimal_generated_config_uses_one_existing_source(): assert bound["training_table"] == bound["score_source_table"] -def test_score_provision_rejects_missing_source_without_creating_tables(): - """A wrong source reference must not create partial prediction resources.""" - workflow = _workflow() - spark = Mock() - spark.catalog.tableExists.return_value = False - with pytest.raises(ValueError, match="source"): - workflow.provision_prediction_table(spark, _config(), object()) - spark.sql.assert_not_called() - - -def test_score_does_not_require_labeled_training_table(monkeypatch): - """A retired training snapshot must not prevent scoring a live source.""" - workflow = _workflow() - config = _config() - config["training_table"] = "workspace.test.retired_training" - spark = Mock() - spark.catalog.tableExists.side_effect = lambda name: name != config["training_table"] - spark.sql.return_value.first.return_value = { - "properties": {"delta.enableChangeDataFeed": "true"} - } - monkeypatch.setattr(workflow, "_prediction_columns", Mock(return_value=())) - monkeypatch.setattr(workflow, "_check_existing_table", Mock()) - prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True)) - assert workflow.provision_prediction_table(spark, config, prepared) is False - - -def test_score_replay_validates_existing_output_without_recounting_source(monkeypatch): - """A later score must accept a growing source without recreating its output.""" - workflow = _workflow() - config = _config() - source = Mock() - source.columns = ["entity_id", "x"] - source.schema = { - "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) - } - spark = Mock() - spark.catalog.tableExists.return_value = True - spark.table.return_value = source - spark.sql.return_value.first.return_value = { - "properties": {"delta.enableChangeDataFeed": "true"} - } - check_target = Mock() - monkeypatch.setattr(workflow, "_check_existing_table", check_target) - prepared = SimpleNamespace( - artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), - preflight=SimpleNamespace( - ready=True, - output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), - ), - ) - result = workflow.provision_prediction_table(spark, config, prepared) - check_target.assert_called_once() - source.select.assert_not_called() - assert result is False - assert all(not call.args[0].startswith("CREATE TABLE") for call in spark.sql.call_args_list) - - -def test_first_score_provisions_prediction_before_incremental_write(monkeypatch): - """The scheduled score job must handle first-run setup without another job.""" - workflow = _workflow() - events = [] - prepared = object() - monkeypatch.setattr(workflow, "prepare_local_workflow", Mock(return_value=prepared)) - monkeypatch.setattr( - workflow, - "provision_prediction_table", - Mock(side_effect=lambda spark, config, model: events.append("provision")), - raising=False, - ) - monkeypatch.setattr( - workflow, - "run_incremental_local_batch", - Mock(side_effect=lambda *args, **kwargs: events.append("score")), - ) - workflow.run_action(object(), _config(), "score") - assert events == ["provision", "score"] - - -def test_prediction_provision_creates_no_control_table(monkeypatch): - """First scoring must create only the output table, with no lock table.""" - workflow = _workflow() - config = _config() - source = Mock() - source.columns = ["entity_id", "x"] - source.schema = { - "entity_id": SimpleNamespace(dataType=SimpleNamespace(typeName=lambda: "string")) - } - source.select.return_value.limit.return_value.count.return_value = 2 - spark = Mock() - spark.catalog.tableExists.side_effect = lambda name: ( - name - in { - config["training_table"], - config["score_source_table"], - } - ) - spark.table.return_value = source - spark.sql.return_value.first.return_value = { - "properties": {"delta.enableChangeDataFeed": "true"} - } - prepared = SimpleNamespace( - artifact=SimpleNamespace(manifest=SimpleNamespace(input_columns=("x",))), - preflight=SimpleNamespace( - ready=True, - output_schema=(SimpleNamespace(name="prediction", dtype="float64"),), - ), - ) - created = workflow.provision_prediction_table(spark, config, prepared) - statements = [call.args[0] for call in spark.sql.call_args_list] - assert created is True - assert len([statement for statement in statements if statement.startswith("CREATE TABLE")]) == 1 - assert all("admission" not in statement for statement in statements) - - -def test_full_rebuild_generation_records_model_identity(monkeypatch): - """A new generation must carry enough provenance to reject unrelated tables.""" - workflow = _workflow() - config = _config() - config.update( - model_change_mode="full_rebuild", prediction_table="workspace.test.predictions_v2" - ) - spark = Mock() - spark.catalog.tableExists.side_effect = lambda name: name == config["score_source_table"] - spark.sql.return_value.first.return_value = { - "properties": {"delta.enableChangeDataFeed": "true"} - } - spark.table.return_value.select.return_value.limit.return_value.count.return_value = 2 - monkeypatch.setattr( - workflow, "_prediction_columns", Mock(return_value=(("prediction", "double", "DOUBLE"),)) - ) - prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True, model_digest="a" * 64)) - assert workflow.provision_prediction_table(spark, config, prepared) is True - created = next( - call.args[0] for call in spark.sql.call_args_list if call.args[0].startswith("CREATE TABLE") - ) - assert "'skyulf.mode' = 'full_rebuild'" in created - assert "'skyulf.model_name' = 'workspace.test.model'" in created - assert "'skyulf.model_version' = '1'" in created - assert f"'skyulf.model_digest' = '{'a' * 64}'" in created - - -@pytest.mark.parametrize("changed", ["mode", "name", "digest"]) -def test_full_rebuild_rejects_unrelated_or_changed_generation(monkeypatch, changed): - """A same-named table must not be scored or activated under another model.""" - workflow = _workflow() - config = _config() - config.update( - model_change_mode="full_rebuild", prediction_table="workspace.test.predictions_v2" - ) - expected = { - "skyulf.mode": "full_rebuild", - "skyulf.model_name": config["model_name"], - "skyulf.model_version": config["model_version"], - "skyulf.model_digest": "a" * 64, - } - key = {"mode": "skyulf.mode", "name": "skyulf.model_name", "digest": "skyulf.model_digest"}[ - changed - ] - expected[key] = "other" - spark = Mock() - spark.catalog.tableExists.return_value = True - spark.sql.return_value.first.side_effect = [ - {"properties": {"delta.enableChangeDataFeed": "true"}}, - {"properties": expected}, - ] - monkeypatch.setattr(workflow, "_prediction_columns", Mock(return_value=())) - check_target = Mock() - monkeypatch.setattr(workflow, "_check_existing_table", check_target) - prepared = SimpleNamespace(preflight=SimpleNamespace(ready=True, model_digest="a" * 64)) - with pytest.raises(ValueError, match="another model or workflow"): - workflow.provision_prediction_table(spark, config, prepared) - check_target.assert_not_called() - - def test_generated_config_has_no_admission_or_alias_state(): """The starting Bundle must not ask users to provision coordination tables.""" config = _render_default_config() @@ -818,7 +148,7 @@ def test_init_row_key_becomes_prediction_table_key(): output_schema=(SimpleNamespace(name="prediction", dtype="float64"),) ), ) - columns = _workflow()._prediction_columns(config, prepared, source) + columns = _output()._prediction_columns(config, prepared, source) assert config["row_keys"] == ["customer_id"] assert columns[0] == ("customer_id", "string", "STRING") diff --git a/tests/integration/test_sm31_notebook_boundary.py b/tests/integration/test_sm31_notebook_boundary.py new file mode 100644 index 000000000..0268b4b84 --- /dev/null +++ b/tests/integration/test_sm31_notebook_boundary.py @@ -0,0 +1,87 @@ +"""A generated notebook must delegate behavior to the installed Core library.""" + +import importlib.util +import json +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize("action", ["train", "train_monthly", "score"]) +def test_notebook_delegates_bound_target_and_selected_action(tmp_path, monkeypatch, engine, action): + """All widget actions must use the public library while preserving engine and target binding.""" + from skyulf.integrations.databricks import local_workflow + + path = ( + Path(__file__).resolve().parents[2] + / "skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py" + ) + spec = importlib.util.spec_from_file_location("thin_notebook", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + assert module.run_action is local_workflow.run_action + assert module.resolve_target_config is local_workflow.resolve_target_config + config = { + "engine": engine, + **{ + key: "{catalog}.{input_schema}." + key + for key in ("training_table", "score_source_table", "prediction_table", "model_name") + }, + } + config_path = tmp_path / "workflow.json" + config_path.write_text(json.dumps(config)) + values = { + "config_path": str(config_path), + "action": action, + "experiment_name": "/test/experiment", + "catalog": "workspace", + "input_schema": "test", + "output_schema": "test", + "metadata_schema": "test", + "resource_suffix": "", + } + + @dataclass + class Result: + """Represent the real service's serializable result boundary.""" + + ok: bool = True + + run = Mock(return_value=Result()) + notebook = Mock() + spark = object() + monkeypatch.setattr(module, "run_action", run) + monkeypatch.setattr(module, "spark", spark, raising=False) + monkeypatch.setattr( + module, + "dbutils", + SimpleNamespace(widgets=SimpleNamespace(get=values.__getitem__), notebook=notebook), + raising=False, + ) + module.main() + assert run.call_args.args == ( + spark, + { + **config, + **{ + key: "workspace.test." + key + for key in ( + "training_table", + "score_source_table", + "prediction_table", + "model_name", + ) + }, + }, + action, + ) + assert run.call_args.kwargs["experiment_name"] == ( + "/test/experiment" if action.startswith("train") else None + ) + assert (run.call_args.kwargs["artifact_path"] is not None) == action.startswith("train") + assert json.loads(notebook.exit.call_args.args[0]) == {"ok": True} From 94b28320458f8130b7ce80c30712ee03b2464ea2 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Thu, 24 Sep 2026 23:16:06 +0300 Subject: [PATCH 57/85] feat: add evidence-based manual approval and relocate core tests Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 11 + docs/user_guide/databricks_bundle.md | 76 +++++++ .../43-sm32-policy-separation-progress.md | 57 +++++ .../44-core-test-relocation.md | 73 +++++++ .../45-sm32-manual-approval-progress.md | 63 ++++++ initiatives/spark_and_mlflow/HANDOFF.md | 21 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 11 +- .../integrations/databricks/local_approval.py | 195 ++++++++++++++++++ .../databricks/local_retraining.py | 6 + .../integrations/databricks/local_workflow.py | 76 ++++++- .../integration/test_preprocessing_chain.py | 0 .../test_databricks_bundle_lifecycle.py | 12 +- .../test_databricks_bundle_notebook.py | 2 +- .../test_databricks_bundle_template.py | 2 +- .../test_databricks_local_approval.py | 176 ++++++++++++++++ .../test_databricks_local_retraining.py | 1 + .../test_databricks_local_workflow.py | 163 +++++++++++++++ .../tests}/unit/test_advanced_cleaning.py | 0 .../tests}/unit/test_binning_comprehensive.py | 0 .../tests/unit/test_casting_nodes.py | 0 .../tests}/unit/test_cleaning.py | 0 .../tests}/unit/test_cleaning_nodes.py | 0 .../unit/test_cross_validation_all_methods.py | 103 ++++++--- .../tests}/unit/test_cv_basic_vs_advanced.py | 12 +- .../tests}/unit/test_cv_polars_final.py | 10 +- .../tests}/unit/test_drift.py | 0 .../tests}/unit/test_encoding.py | 0 .../tests}/unit/test_encoding_scenarios.py | 7 + .../tests}/unit/test_encoding_target_guard.py | 2 +- .../tests}/unit/test_feature_generation.py | 0 .../unit/test_feature_generation_speed.py | 0 .../tests}/unit/test_feature_selection.py | 0 .../test_feature_selection_comprehensive.py | 7 + .../unit/test_feature_selection_polars.py | 2 + .../tests}/unit/test_filtering.py | 0 .../tests}/unit/test_imputation.py | 0 .../tests}/unit/test_imputation_backend.py | 0 .../tests/unit/test_inspection_nodes.py | 10 +- .../tests}/unit/test_label_encoder_target.py | 5 +- .../tests}/unit/test_outliers.py | 0 .../test_preprocessing_comprehensive_suite.py | 0 .../unit/test_preprocessing_feature_nodes.py | 0 .../tests}/unit/test_profiling.py | 10 + .../tests/unit/test_registry_metadata.py | 17 ++ .../tests/unit/test_resampling_nodes.py | 0 .../tests/unit/test_scaling_nodes.py | 3 + .../tests/unit/test_split_nodes.py | 6 + .../tests}/unit/test_transformations.py | 0 .../unit/test_transformations_polars.py | 0 tests/unit/test_dynamic_registry_manual.py | 63 ------ 50 files changed, 1086 insertions(+), 116 deletions(-) create mode 100644 initiatives/spark_and_mlflow/43-sm32-policy-separation-progress.md create mode 100644 initiatives/spark_and_mlflow/44-core-test-relocation.md create mode 100644 initiatives/spark_and_mlflow/45-sm32-manual-approval-progress.md create mode 100644 skyulf-core/skyulf/integrations/databricks/local_approval.py rename tests/integration/test_pipeline_integration.py => skyulf-core/tests/integration/test_preprocessing_chain.py (100%) rename tests/integration/test_bundle_challenger_lifecycle.py => skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py (92%) rename tests/integration/test_sm31_notebook_boundary.py => skyulf-core/tests/integrations/test_databricks_bundle_notebook.py (97%) rename tests/integration/test_sm20a_bundle_template.py => skyulf-core/tests/integrations/test_databricks_bundle_template.py (99%) create mode 100644 skyulf-core/tests/integrations/test_databricks_local_approval.py rename {tests => skyulf-core/tests}/unit/test_advanced_cleaning.py (100%) rename {tests => skyulf-core/tests}/unit/test_binning_comprehensive.py (100%) rename tests/unit/test_casting.py => skyulf-core/tests/unit/test_casting_nodes.py (100%) rename {tests => skyulf-core/tests}/unit/test_cleaning.py (100%) rename {tests => skyulf-core/tests}/unit/test_cleaning_nodes.py (100%) rename {tests => skyulf-core/tests}/unit/test_cross_validation_all_methods.py (85%) rename {tests => skyulf-core/tests}/unit/test_cv_basic_vs_advanced.py (97%) rename {tests => skyulf-core/tests}/unit/test_cv_polars_final.py (71%) rename {tests => skyulf-core/tests}/unit/test_drift.py (100%) rename {tests => skyulf-core/tests}/unit/test_encoding.py (100%) rename {tests => skyulf-core/tests}/unit/test_encoding_scenarios.py (95%) rename {tests => skyulf-core/tests}/unit/test_encoding_target_guard.py (98%) rename {tests => skyulf-core/tests}/unit/test_feature_generation.py (100%) rename {tests => skyulf-core/tests}/unit/test_feature_generation_speed.py (100%) rename {tests => skyulf-core/tests}/unit/test_feature_selection.py (100%) rename {tests => skyulf-core/tests}/unit/test_feature_selection_comprehensive.py (95%) rename {tests => skyulf-core/tests}/unit/test_feature_selection_polars.py (96%) rename {tests => skyulf-core/tests}/unit/test_filtering.py (100%) rename {tests => skyulf-core/tests}/unit/test_imputation.py (100%) rename {tests => skyulf-core/tests}/unit/test_imputation_backend.py (100%) rename tests/unit/test_inspection.py => skyulf-core/tests/unit/test_inspection_nodes.py (75%) rename {tests => skyulf-core/tests}/unit/test_label_encoder_target.py (94%) rename {tests => skyulf-core/tests}/unit/test_outliers.py (100%) rename {tests => skyulf-core/tests}/unit/test_preprocessing_comprehensive_suite.py (100%) rename {tests => skyulf-core/tests}/unit/test_preprocessing_feature_nodes.py (100%) rename {tests => skyulf-core/tests}/unit/test_profiling.py (93%) create mode 100644 skyulf-core/tests/unit/test_registry_metadata.py rename tests/unit/test_resampling.py => skyulf-core/tests/unit/test_resampling_nodes.py (100%) rename tests/unit/test_scaling.py => skyulf-core/tests/unit/test_scaling_nodes.py (96%) rename tests/unit/test_split.py => skyulf-core/tests/unit/test_split_nodes.py (84%) rename {tests => skyulf-core/tests}/unit/test_transformations.py (100%) rename {tests => skyulf-core/tests}/unit/test_transformations_polars.py (100%) delete mode 100644 tests/unit/test_dynamic_registry_manual.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index 1499d9b04..b2c2ced08 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -10,6 +10,17 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed +- Core-owned tests now live under `skyulf-core/tests`, including the Bundle + template/notebook/lifecycle tests. Backend and frontend contract tests retain + their own scope; moved tests also participate in Core's type checks. +- Local workflow approval loads an existing candidate's saved comparison and + training snapshot, rechecks quality and returns a checked promotion receipt + without training or registering another model. Repeated current approvals + return the original receipt; Bundle operator wiring remains pending. +- Core's local workflow accepts independent scoring selection and promotion + policies. All four combinations preserve scoring pins and promotion gates; + partial/mixed configurations fail early. Legacy modes retain their behavior. + Bundle prompts and the remaining manual lifecycle actions are pending in SM-32. - Bundle initialization accepts an optional business risk label and documents the PayingRegNo cost-tag choice. New lifecycle receipts use from_version; older from and compact receipts remain readable. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index ad377afee..2bfa203a9 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -51,6 +51,82 @@ Edit the business pipeline in `config/workflow.json`. Model/preprocessing choices remain project configuration; common workflow fixes ship in the Skyulf wheel instead of requiring edits to every generated notebook. +### Independent library policies (SM-32 in progress) + +Direct `run_action` callers can now separate these two decisions: + +| `score_model_selection` | `promotion_policy` | Behavior | +| --- | --- | --- | +| `pinned_version` | `manual_approval` | Register/evaluate the contender; score keeps the configured version | +| `pinned_version` | `automatic` | Apply promotion gates; score still keeps the configured version | +| `champion` | `manual_approval` | Register/evaluate the contender; score follows the existing champion | +| `champion` | `automatic` | Apply promotion gates; the next score follows the resulting champion | + +For example, a library configuration containing `model_version: "2"`, +`score_model_selection: "pinned_version"` and `promotion_policy: "automatic"` +continues scoring with v2 after a successful promotion of v4. Selecting +`champion` instead resolves the controlled alias once per score run. A missing +champion fails before output preparation; there is no fallback to latest. + +Both new fields are required together. Remove `model_selection_mode` when +using them; mixed or partial configurations fail before training or scoring. +Legacy `auto_champion` retains champion/automatic behavior, and legacy +`pinned_version` retains pinned/manual behavior, with a deprecation warning. +Automatic promotion still requires `quality_threshold`, including when +scoring is pinned. Scoring never updates the caller's configured version. + +This first slice is available at the library boundary. The generated Bundle +still uses its existing `model_selection_mode` and job graph. Do not migrate +only its JSON: the lifecycle actions and matching job handoff must be delivered +together. `manual_approval` currently means no automatic promotion; approve, +reject and rollback are separate operator actions. The library now supports +`approve`; reject, rollback and `previous_challenger` remain the next SM-32 work. +No new cloud deployment is implied by these library changes. + +### Approve an existing candidate without training + +Use an explicit manual policy and the comparison returned by the earlier +training job. Review that saved result before passing its version and digest: + +```python +import hashlib +import json +from dataclasses import asdict + +from skyulf.integrations.databricks.local_workflow import run_action + +# candidate is the result of an earlier training job; no training runs here. +comparison = asdict(candidate.comparison) +comparison_sha256 = hashlib.sha256( + json.dumps(comparison, sort_keys=True, allow_nan=False).encode() +).hexdigest() +receipt = run_action( + spark, + config, # promotion_policy="manual_approval" and both independent fields + "approve", + candidate_version=candidate.model_version, + comparison_sha256=comparison_sha256, + expected_champion_version=candidate.comparison.champion_version, +) +``` + +Approval downloads `candidate_comparison.json` and `candidate_training_spec.json` +from the run associated with that registered version. It verifies the digest, +current metric policy, expected champion and controlled challenger receipt. +It then reads the original Delta version and evaluation window and rechecks +quality using the existing Core comparison/promotion services. The original +engine is preserved; current read budgets may tighten the saved limits. + +The action does not train, register or upload a model, rewrite `model_version`, +or publish predictions. A later score run follows the configured selector. +Retrying an unchanged successful approval returns its original committed +receipt; changed champion, pending writes or incompatible evidence fail. +Training runs created before the saved specification was introduced cannot +use this action without explicitly supplying that missing provenance through +a separately reviewed migration; there is no fallback to current training dates. +Use the same externally serialized lifecycle writer as training. Bundle widgets +and automatic score handoff for operator actions are still pending. + ## What is created `bundle deploy` creates only two jobs and uploads their code: diff --git a/initiatives/spark_and_mlflow/43-sm32-policy-separation-progress.md b/initiatives/spark_and_mlflow/43-sm32-policy-separation-progress.md new file mode 100644 index 000000000..706124c7c --- /dev/null +++ b/initiatives/spark_and_mlflow/43-sm32-policy-separation-progress.md @@ -0,0 +1,57 @@ +# SM-32: independent policies, first implementation slice + +Date: 2026-09-24. Status: ACTIVE, partially implemented locally. +Design: [independent selection and approval](38-model-selection-and-approval-design.md). +Baseline commit: `fcfcee31` (SM-30, SM-31 and company/readable tags). +The baseline passed 116 tests and the applicable commit hooks, including ty. + +## Implemented at the library boundary + +`skyulf.integrations.databricks.local_workflow.run_action` now validates +`score_model_selection` and `promotion_policy` independently. Automatic +promotion never overwrites a scoring pin. Champion selection resolves once +per score run, and missing champion fails before output preparation. +Both new fields are required; combining either with the old mode is rejected. +Legacy modes keep their established behavior and emit a migration warning. + +New configurations use controlled champion resolution for evaluation in both +promotion modes. An explicit stale champion expectation fails before fit. +Automatic training requires an absolute quality gate regardless of scoring +selection. Manual mode still registers, nominates and evaluates a contender. +Scoring does not train or register a model. + +The existing generated template keeps its legacy field and graph until the +complete lifecycle interface is ready. This avoids publishing a partially +migrated graph as a finished Bundle feature. + +## Verification + +- 17 new regression cases failed against the old coupled implementation. +- 78 focused tests passed, covering all four combinations on both engines, + malformed/partial/mixed migration, missing champion, stale expected champion, + automatic quality-gate requirements and legacy migration warnings. +- Real local MLflow stores exercised pandas and Polars with both scoring + selectors: bootstrap, improved candidate, tied contender, manual contender + and evaluation error. Existing notebook boundary and template tests passed. +- Log: `rehearsals/sm32-matrix.log` (local ignored test evidence). +- Scoped Ruff and ty passed. Independent read-only review found no blocking + correctness or regression issues in the library/test changes. +- This slice has not been deployed or tested live in Databricks. + +## Remaining SM-32 work, in order + +1. Existing-version approve is now implemented at the library boundary; see + [manual approval progress](45-sm32-manual-approval-progress.md). + Finish reject using the same stored evidence and serialized writer. +2. Add controlled rollback to the same lifecycle entry point and keep all + actions behind the same serialized writer. Preserve unknown-outcome rules. +3. Add previous_challenger on actual contender replacement, with controlled + history receipts, retry idempotency and promotion/rollback reconciliation. +4. Wire independent prompts, lifecycle action parameters and optional score + handoff to the two existing Bundle jobs. Match configuration and job graph; + extend migration validation with SM-33 instead of silently rewriting pins. +5. Verify manual approval of a passing existing version without training, + rejection/stale evidence, receipt retries and history transitions. Exercise + the generated Bundle and obtain live evidence for the completed interface. + +No Spark expansion or SM-33 work should start while this task is incomplete. diff --git a/initiatives/spark_and_mlflow/44-core-test-relocation.md b/initiatives/spark_and_mlflow/44-core-test-relocation.md new file mode 100644 index 000000000..7ecdbecd3 --- /dev/null +++ b/initiatives/spark_and_mlflow/44-core-test-relocation.md @@ -0,0 +1,73 @@ +# Core test relocation + +Date: 2026-09-24. Scope: collected pytest files that test Core without backend dependencies. + +36 files moved into Core. The three Databricks Bundle tests belong in +`skyulf-core/tests/integrations`, alongside the integration services. The +preprocessing chain belongs in `tests/integration`, and isolated node/model +checks belong in `tests/unit`. Existing same-named Core files were preserved; +conflicting names gained a descriptive `_nodes` suffix. + +Backend/Core integration tests remain in root `tests`. The EDA producer +contract also stays there because it compares Core output with a frontend +fixture. Manual diagnostic and benchmark scripts were not reclassified as +pytest tests by this relocation. + +## Verification and supporting corrections + +- Before relocation: 224 cases collected and passed. +- After relocation and path updates: the same 224 cases passed. +- All Core tests collected: 10,900 cases, no duplicate-module or import failures. +- Moving tests into Core brought 60 previously out-of-scope ty diagnostics into + scope. Explicit frame/tuple/None assertions and typed test parameters resolve + them; required checks were not suppressed globally. +- One precise waiver retains the native-Polars CV runtime regression because + its public annotation omits that accepted input. No input conversion was added. +- The former manual registry check changed from print-only diagnostics and + global stdout/sys.path mutations to real metadata assertions. +- Moved tests plus the workflow service suite: 281 passed. Full repository ty + and scoped Ruff passed. Independent review found no removed test functions, + reduced assertion counts or broken Bundle paths. +- Historical reports retain their original evidence paths; use this mapping + to locate the current test files. + +## File mapping + +| Previous path | Current path | +| --- | --- | +| `tests/integration/test_bundle_challenger_lifecycle.py` | `skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py` | +| `tests/integration/test_pipeline_integration.py` | `skyulf-core/tests/integration/test_preprocessing_chain.py` | +| `tests/integration/test_sm20a_bundle_template.py` | `skyulf-core/tests/integrations/test_databricks_bundle_template.py` | +| `tests/integration/test_sm31_notebook_boundary.py` | `skyulf-core/tests/integrations/test_databricks_bundle_notebook.py` | +| `tests/unit/test_advanced_cleaning.py` | `skyulf-core/tests/unit/test_advanced_cleaning.py` | +| `tests/unit/test_binning_comprehensive.py` | `skyulf-core/tests/unit/test_binning_comprehensive.py` | +| `tests/unit/test_casting.py` | `skyulf-core/tests/unit/test_casting_nodes.py` | +| `tests/unit/test_cleaning.py` | `skyulf-core/tests/unit/test_cleaning.py` | +| `tests/unit/test_cleaning_nodes.py` | `skyulf-core/tests/unit/test_cleaning_nodes.py` | +| `tests/unit/test_cross_validation_all_methods.py` | `skyulf-core/tests/unit/test_cross_validation_all_methods.py` | +| `tests/unit/test_cv_basic_vs_advanced.py` | `skyulf-core/tests/unit/test_cv_basic_vs_advanced.py` | +| `tests/unit/test_cv_polars_final.py` | `skyulf-core/tests/unit/test_cv_polars_final.py` | +| `tests/unit/test_drift.py` | `skyulf-core/tests/unit/test_drift.py` | +| `tests/unit/test_dynamic_registry_manual.py` | `skyulf-core/tests/unit/test_registry_metadata.py` | +| `tests/unit/test_encoding.py` | `skyulf-core/tests/unit/test_encoding.py` | +| `tests/unit/test_encoding_scenarios.py` | `skyulf-core/tests/unit/test_encoding_scenarios.py` | +| `tests/unit/test_encoding_target_guard.py` | `skyulf-core/tests/unit/test_encoding_target_guard.py` | +| `tests/unit/test_feature_generation.py` | `skyulf-core/tests/unit/test_feature_generation.py` | +| `tests/unit/test_feature_generation_speed.py` | `skyulf-core/tests/unit/test_feature_generation_speed.py` | +| `tests/unit/test_feature_selection.py` | `skyulf-core/tests/unit/test_feature_selection.py` | +| `tests/unit/test_feature_selection_comprehensive.py` | `skyulf-core/tests/unit/test_feature_selection_comprehensive.py` | +| `tests/unit/test_feature_selection_polars.py` | `skyulf-core/tests/unit/test_feature_selection_polars.py` | +| `tests/unit/test_filtering.py` | `skyulf-core/tests/unit/test_filtering.py` | +| `tests/unit/test_imputation.py` | `skyulf-core/tests/unit/test_imputation.py` | +| `tests/unit/test_imputation_backend.py` | `skyulf-core/tests/unit/test_imputation_backend.py` | +| `tests/unit/test_inspection.py` | `skyulf-core/tests/unit/test_inspection_nodes.py` | +| `tests/unit/test_label_encoder_target.py` | `skyulf-core/tests/unit/test_label_encoder_target.py` | +| `tests/unit/test_outliers.py` | `skyulf-core/tests/unit/test_outliers.py` | +| `tests/unit/test_preprocessing_comprehensive_suite.py` | `skyulf-core/tests/unit/test_preprocessing_comprehensive_suite.py` | +| `tests/unit/test_preprocessing_feature_nodes.py` | `skyulf-core/tests/unit/test_preprocessing_feature_nodes.py` | +| `tests/unit/test_profiling.py` | `skyulf-core/tests/unit/test_profiling.py` | +| `tests/unit/test_resampling.py` | `skyulf-core/tests/unit/test_resampling_nodes.py` | +| `tests/unit/test_scaling.py` | `skyulf-core/tests/unit/test_scaling_nodes.py` | +| `tests/unit/test_split.py` | `skyulf-core/tests/unit/test_split_nodes.py` | +| `tests/unit/test_transformations.py` | `skyulf-core/tests/unit/test_transformations.py` | +| `tests/unit/test_transformations_polars.py` | `skyulf-core/tests/unit/test_transformations_polars.py` | diff --git a/initiatives/spark_and_mlflow/45-sm32-manual-approval-progress.md b/initiatives/spark_and_mlflow/45-sm32-manual-approval-progress.md new file mode 100644 index 000000000..820b5235d --- /dev/null +++ b/initiatives/spark_and_mlflow/45-sm32-manual-approval-progress.md @@ -0,0 +1,63 @@ +# SM-32: manual approval from saved candidate evidence + +Date: 2026-09-24. Status: implemented locally; SM-32 remains ACTIVE. +Parent: [selection and approval design](38-model-selection-and-approval-design.md). + +## Delivered library behavior + +`run_action(..., "approve", candidate_version=..., comparison_sha256=..., +expected_champion_version=...)` is an explicit manual-policy operation. +The new `local_approval` service shares existing Core training snapshot, +comparison, initialization, promotion and receipt verification functions. +It neither fits nor registers a model and never changes the scoring pin. + +Training now saves `candidate_training_spec.json` beside its comparison. +Approval reads both artifacts from the requested model version's run. It +verifies the requested comparison digest, model identity, source contract, +engine, current metric policy and expected champion. The original source +version and split window are restored; today's training dates are not used. +Current budgets can tighten the saved read limits. Quality is re-evaluated +on the pinned holdout before a checked alias mutation. + +An unchanged repeated approval returns the same still-active committed +receipt. A newer champion, incompatible proof, pending mutation, failed +quality gate or changed policy is refused. The public approval service itself +also enforces manual policy, even when called without `run_action`. + +## Local verification + +- Initial approval tests failed because the action was not implemented. +- Real MLflow cases passed with both pandas and Polars: manual bootstrap, + improved candidate, same-receipt retry, pinned score version preservation, + exact version counts (no retraining/registration), rejected tied candidate, + wrong digest, changed metric policy/data contract, pending alias event, + changed holdout and stale expected champion. +- The public-service policy regression first failed and was then corrected. +- Full repository ty and scoped Ruff passed. +- Combined relocation, workflow, approval, retraining and promotion suite: + **321 passed**, 24 dependency/deprecation warnings, in 139.15 seconds. + Evidence: `rehearsals/sm32-moves-approval-final.log`. +- Tests now live in `skyulf-core/tests/integrations`; relocation details are + in [the inventory](44-core-test-relocation.md). + +## Remaining work and Databricks timing + +Reject, rollback, previous_challenger and the matching Bundle operator inputs/ +score handoff remain open. The existing generated Bundle still uses its +legacy interface; this library slice has not been uploaded or run remotely. + +Run the Databricks rehearsal after those lifecycle operations are wired and +local/generated-project checks pass. Inspect and reuse the existing personal +test workspace resources where appropriate instead of adding another schema +for each subtask. The reviewable live plan must cover: + +1. Train/register a passing manual contender and inspect its MLflow metrics. +2. Approve that exact existing version with no new training/model registration. +3. Score with champion selection and with a fixed version; inspect Delta output. +4. Repeat approval/score to verify receipt reuse and no duplicate predictions. +5. Replace a challenger, reject a contender, and perform controlled rollback. +6. Verify both local engines, stale evidence rejection and failed-score recovery. + +No new live run or cleanup was performed in this slice. Models trained before +the saved specification exists need explicit evidence migration; approval must +never silently reconstruct their original evaluation window from current config. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 8d7b7c034..8309967a8 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -4,7 +4,24 @@ The user approved the [local Bundle improvement program](37-local-bundle-improvement-program.md) and explicitly requested [independent scoring selection and promotion policy](38-model-selection-and-approval-design.md). -**SM-30, company tags and SM-31 are complete; SM-32 is next READY.** +**SM-30, company tags and SM-31 are committed as `fcfcee31`; SM-32 is ACTIVE.** +The requested commit passed 116 tests and all applicable hooks (including ty). +SM-32 now separates score_model_selection and promotion_policy at the library +run_action boundary. All four combinations passed on pandas and Polars; +78 relevant tests include real local MLflow lifecycle artifacts. These library +changes have not been deployed. See +[the progress and next implementation steps](43-sm32-policy-separation-progress.md). +Update: 36 Core-owned test files have moved from root tests into Core; see +[the relocation inventory](44-core-test-relocation.md). 224 cases passed before +and after relocation; Core collected 10,900 tests without collisions, and +the relocated cases plus workflow tests passed 281 tests after type narrowing. +Library approve now loads saved candidate evidence and rechecks it without fit +or registration; see [manual approval progress](45-sm32-manual-approval-progress.md). +Final combined regression suite passed 321 tests; full repository ty and +scoped Ruff passed. This commit includes the SM-32 policy/approval slice and +the Core test relocation; the complete SM-32 task remains open. +Next implement reject/rollback, previous_challenger and matching Bundle actions/ +handoff; do not mark SM-32 complete yet. No new Databricks run was made. Latest follow-up: Bundle initialization now asks for optional risk_category, PayingRegNo has an explicit policy-compute example, and new receipts use from_version while reading older formats. 44 relevant tests and real CLI @@ -15,7 +32,7 @@ The user requested readable/company-compatible tags and a clean live reset before SM-31. [The clean rehearsal](41-company-tags-and-clean-live-validation.md) passed all four tasks in run 607409241163605. [SM-31 evidence](42-sm31-refactor-plan-and-evidence.md) records 110 passing tests, Ruff, scoped ty, strict MkDocs, installed-wheel imports, -and a successful deployed score run 383572337148835. Changes remain uncommitted. +and a successful deployed score run 383572337148835. These changes are in `fcfcee31`. The old four test jobs and two schemas were deleted as requested. Retain the new workspace.skyulf_lifecycle_test schema and exactly two skyulf_lifecycle diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index e32971b10..0eb0d1906 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -39,7 +39,14 @@ scope and do not imply the improvements below already exist. Read [the improvement program](37-local-bundle-improvement-program.md) and [the independent selection/approval design](38-model-selection-and-approval-design.md). Each task includes implementation locations and concrete acceptance checks. -**SM-30, company-compatible tags and SM-31 are complete; SM-32 is READY.** See +**SM-30, company-compatible tags and SM-31 are committed; SM-32 is ACTIVE.** +Commit `fcfcee31` passed 116 tests and all applicable commit hooks. +The first SM-32 library policy slice passed 78 tests; see +[policy separation progress](43-sm32-policy-separation-progress.md). +The [manual approve library action](45-sm32-manual-approval-progress.md) now +rechecks saved candidate evidence without training; reject/rollback, contender +history and Bundle wiring remain open. [36 misplaced Core test files](44-core-test-relocation.md) +were relocated and verified before this continuation. See [the implementation evidence](40-sm30-challenger-validation-report.md): 104 tests passed, including real MLflow lifecycles with pandas and Polars. See [the clean live rehearsal](41-company-tags-and-clean-live-validation.md). @@ -53,7 +60,7 @@ on an existing candidate without retraining or reuploading the model. | --- | --- | --- | --- | --- | | SM-30 | Challenger nomination and visible evaluation status | Existing SM-22c/29 | DONE | 104 local tests and live run 607409241163605 passed; company tags, both engines, retained contender, replacement, error and rollback verified | | SM-31 | Thin template and reusable workflow/publication services | SM-30 | DONE | 44-line notebook, two Core services, 110 tests, wheel installation/import, strict generation validation and live score run 383572337148835 passed | -| SM-32 | Independent score selection and promotion policy | SM-31 | READY | Four pinned/champion and manual/automatic combinations; approve/reject/rollback existing versions via one writer; score handoff without fit; previous_challenger history on contender replacement | +| SM-32 | Independent score selection and promotion policy | SM-31 | ACTIVE | Library's four combinations and saved-evidence approve implemented; remaining: reject/rollback via one writer, score handoff without fit, previous_challenger history, matching Bundle choices and live proof | | SM-33 | Validated config, migration and runtime parameters | SM-32 | WAIT | Per-run version/action/evidence inputs; task/column/key setup; migrate old mode and reject config/job-graph disagreement | | SM-34 | Independent score/train schedules and training windows | SM-33 | WAIT | Editable paused score/train cron/timezone, explicit lookback/holdout/label windows; scoring needs no manual dates or retraining | | SM-35 | Multi-metric quality gates and clear thresholds | SM-33 | WAIT | One selection metric plus optional guardrails; task/domain validation, first-model gate, failed-gate explanations and no probability-threshold confusion | diff --git a/skyulf-core/skyulf/integrations/databricks/local_approval.py b/skyulf-core/skyulf/integrations/databricks/local_approval.py new file mode 100644 index 000000000..b2c190843 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/local_approval.py @@ -0,0 +1,195 @@ +"""Approve an existing local model using its saved, pinned evaluation evidence. + +The caller must serialize this operation with every other lifecycle writer. +Approval never fits, registers or uploads a model and never changes a scoring pin. +""" + +import hashlib +import json +import re +from dataclasses import asdict, replace +from datetime import datetime +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any + +import polars as pl + +from ..mlflow.promotion import ( + AliasChangeReceipt, + AliasConflictError, + ExclusiveAliasWriterAdmission, + _active_marker, + _event_tag, + _read_event, + _verify_original_receipt, + _verify_staged_challenger, + controlled_champion_version, + initialize_champion, + promote_candidate, +) +from ..mlflow.registry import _make_client, _require_mlflow, resolve_model +from ..mlflow.validation import ModelComparisonReport +from . import local_retraining +from .local_retraining import LocalTrainingSpec + + +def _load_evidence( + client: Any, name: str, version: str, digest: str +) -> tuple[ModelComparisonReport, LocalTrainingSpec, str]: + """Read only the named version's run artifacts and verify the operator's evidence pin.""" + model = client.get_model_version(name, version) + if not model.run_id: + raise ValueError("Candidate has no training run with approval evidence.") + with TemporaryDirectory(prefix="skyulf-approval-") as directory: + report_path = client.download_artifacts( + model.run_id, "candidate_comparison.json", directory + ) + spec_path = client.download_artifacts( + model.run_id, "candidate_training_spec.json", directory + ) + report = ModelComparisonReport(**json.loads(Path(report_path).read_text(encoding="utf-8"))) + saved_spec = json.loads(Path(spec_path).read_text(encoding="utf-8")) + actual = hashlib.sha256( + json.dumps(asdict(report), sort_keys=True, allow_nan=False).encode() + ).hexdigest() + if actual != digest: + raise ValueError("Saved comparison digest differs from requested approval evidence.") + if report.model_name != name or report.candidate_version != version: + raise ValueError("Saved comparison does not identify the requested candidate.") + engine = saved_spec.pop("engine") + if engine not in ("pandas", "polars"): + raise ValueError("Saved approval engine must be pandas or polars.") + for field in ("start", "holdout_start", "cutoff"): + saved_spec[field] = datetime.fromisoformat(saved_spec[field]) + for field in ("row_keys", "input_columns"): + saved_spec[field] = tuple(saved_spec[field]) + spec = LocalTrainingSpec(**saved_spec) + if spec.dataset_id != report.dataset_id: + raise ValueError("Saved training snapshot differs from comparison evidence.") + return report, spec, engine + + +def _completed_approval( + client: Any, report: ModelComparisonReport, digest: str +) -> AliasChangeReceipt: + """Replay only the same still-active committed transition, never a later rollback.""" + event_id = _active_marker(client, report.model_name, report.candidate_version) + if event_id is None: + raise AliasConflictError("Candidate lacks an active approval receipt.") + raw = client.get_model_version(report.model_name, report.candidate_version).tags.get( + _event_tag(event_id) + ) + event = _read_event(raw) + if not isinstance(event, dict) or ( + event.get("k") not in {"initial", "promotion"} + or event.get("h") != digest + or event.get("p") != report.champion_version + ): + raise AliasConflictError("Active champion receipt differs from requested approval.") + receipt = AliasChangeReceipt( + event_id=event_id, + kind=event["k"], + model_name=report.model_name, + alias="champion", + prior_version=event["p"], + new_version=report.candidate_version, + comparison_sha256=digest, + parent_event_id=event.get("e"), + previous_champion_version=event.get("o"), + ) + _verify_original_receipt(client, receipt) + return receipt + + +def approve_local_candidate( + spark: Any, + config: dict[str, Any], + *, + candidate_version: str | None, + comparison_sha256: str | None, + expected_champion_version: str | None, +) -> AliasChangeReceipt: + """Re-evaluate the saved holdout and approve without retraining or changing score selection. + + The current metric policy must match the saved comparison. Read limits may + be tightened; the source version and time window come from the candidate's + saved training specification. A repeated committed request returns its + original receipt only while that transition remains active. + """ + if config.get("promotion_policy") != "manual_approval": + raise ValueError("Approval requires explicit promotion_policy=manual_approval.") + if not isinstance(candidate_version, str) or not re.fullmatch( + r"[1-9][0-9]*", candidate_version + ): + raise ValueError("Approval requires a concrete candidate_version.") + if not isinstance(comparison_sha256, str) or not re.fullmatch( + r"[a-f0-9]{64}", comparison_sha256 + ): + raise ValueError("Approval requires a comparison_sha256 evidence digest.") + if expected_champion_version is not None and ( + not isinstance(expected_champion_version, str) + or not re.fullmatch(r"[1-9][0-9]*", expected_champion_version) + ): + raise ValueError("Expected champion must be a concrete version or None for bootstrap.") + for field in ("max_rows", "max_bytes"): + if type(config.get(field)) is not int or config[field] <= 0: + raise ValueError(f"Approval {field} must be a positive integer.") + tracking_uri = config.get("tracking_uri", "databricks") + registry_uri = config.get("registry_uri", "databricks-uc") + name = config["model_name"] + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + report, spec, engine = _load_evidence(client, name, candidate_version, comparison_sha256) + if report.champion_version != expected_champion_version: + raise ValueError("Expected champion differs from the saved comparison.") + if ( + any( + config.get(field) != getattr(report, field) + for field in ("metric", "min_improvement", "quality_threshold") + ) + or report.quality_threshold is None + ): + raise ValueError("Approval policy must match the saved, absolute-quality-gated comparison.") + if engine != config["engine"] or any( + ( + spec.table != config["training_table"], + spec.target_column != config["target_column"], + spec.input_columns != tuple(config["input_columns"]), + spec.row_keys != tuple(config["row_keys"]), + ) + ): + raise ValueError("Approval data contract differs from saved training evidence.") + candidate = resolve_model( + name, version=candidate_version, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + if candidate.digest != report.candidate_digest: + raise ValueError("Candidate model digest differs from saved comparison.") + current = controlled_champion_version( + name, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + if current == candidate_version: + return _completed_approval(client, report, comparison_sha256) + if current != expected_champion_version: + raise AliasConflictError("Champion changed since the requested comparison.") + _verify_staged_challenger(client, report, comparison_sha256) + bounded_spec = replace( + spec, + max_rows=min(spec.max_rows, config["max_rows"]), + max_bytes=min(spec.max_bytes, config["max_bytes"]), + ) + frame = local_retraining.read_training_snapshot(spark, bounded_spec) + _, heldout, _ = local_retraining.split_labeled_snapshot(frame, bounded_spec) + native = pl.from_pandas(heldout) if engine == "polars" else heldout + options = { + "target_column": spec.target_column, + "admission": ExclusiveAliasWriterAdmission(), + "max_rows": bounded_spec.max_rows, + "max_bytes": bounded_spec.max_bytes, + "tracking_uri": tracking_uri, + "registry_uri": registry_uri, + } + if expected_champion_version is None: + return initialize_champion(report, native, **options) + return promote_candidate( + report, native, expected_champion_version=expected_champion_version, **options + ) diff --git a/skyulf-core/skyulf/integrations/databricks/local_retraining.py b/skyulf-core/skyulf/integrations/databricks/local_retraining.py index 2317626cb..fb7b83a91 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_retraining.py +++ b/skyulf-core/skyulf/integrations/databricks/local_retraining.py @@ -310,6 +310,12 @@ def train_local_candidate( run.client.log_dict( run.run_id, {"dataset_id": spec.dataset_id, **tags}, "training_data.json" ) + saved_spec = asdict(spec) + for field in ("start", "holdout_start", "cutoff"): + saved_spec[field] = getattr(spec, field).isoformat() + run.client.log_dict( + run.run_id, {**saved_spec, "engine": engine}, "candidate_training_spec.json" + ) run.log_metrics(metrics) model_uri = _log_local_model(artifact_path, run_id=run.run_id, tracking_uri=tracking_uri) run_id = run.run_id diff --git a/skyulf-core/skyulf/integrations/databricks/local_workflow.py b/skyulf-core/skyulf/integrations/databricks/local_workflow.py index 83129c292..acd904dd7 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_workflow.py +++ b/skyulf-core/skyulf/integrations/databricks/local_workflow.py @@ -4,6 +4,7 @@ this module creates no Spark session, registry connection or cloud resource. """ +import warnings from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path @@ -22,6 +23,7 @@ ) from ..mlflow.registry import RegistryModelNotFoundError, resolve_model from .admission import SingleWriterAdmission +from .local_approval import approve_local_candidate from .local_incremental import run_incremental_local_batch from .local_retraining import ( LocalTrainingSpec, @@ -69,6 +71,44 @@ def _selection_mode(config: dict[str, Any]) -> str: return mode +def _workflow_policies(config: dict[str, Any]) -> tuple[str, str]: + """Validate independent policies while preserving legacy project behavior. + + Migrate both fields together and remove model_selection_mode. A mixed or + partial configuration is ambiguous and must fail before any external work. + """ + fields = {"score_model_selection", "promotion_policy"} + supplied = fields.intersection(config) + if supplied: + if supplied != fields or "model_selection_mode" in config: + raise ValueError( + "Set score_model_selection and promotion_policy together, " + "and remove legacy model_selection_mode." + ) + selection = config["score_model_selection"] + policy = config["promotion_policy"] + if selection not in ("pinned_version", "champion"): + raise ValueError("score_model_selection must be pinned_version or champion.") + if policy not in ("manual_approval", "automatic"): + raise ValueError("promotion_policy must be manual_approval or automatic.") + return selection, policy + mode = _selection_mode(config) + if "model_selection_mode" in config: + warnings.warn( + "model_selection_mode is deprecated. Replace auto_champion with " + "score_model_selection=champion and promotion_policy=automatic; " + "replace pinned_version with score_model_selection=pinned_version " + "and promotion_policy=manual_approval.", + DeprecationWarning, + stacklevel=3, + ) + return ( + ("champion", "automatic") + if mode == "auto_champion" + else ("pinned_version", "manual_approval") + ) + + def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> dict[str, Any]: """Bind only UC object names to one validated Bundle target.""" for name in ("catalog", "input_schema", "output_schema", "metadata_schema"): @@ -249,26 +289,46 @@ def run_action( experiment_name: str | None = None, artifact_path: str | Path | None = None, now: datetime | None = None, + candidate_version: str | None = None, + comparison_sha256: str | None = None, + expected_champion_version: str | None = None, ) -> Any: """Delegate training or scoring to Skyulf's existing services.""" tracking_uri = config.get("tracking_uri", "databricks") registry_uri = config.get("registry_uri", "databricks-uc") - selection_mode = _selection_mode(config) + selection, policy = _workflow_policies(config) + if action == "approve": + if policy != "manual_approval" or "promotion_policy" not in config: + raise ValueError("Approval requires explicit promotion_policy=manual_approval.") + return approve_local_candidate( + spark, + config, + candidate_version=candidate_version, + comparison_sha256=comparison_sha256, + expected_champion_version=expected_champion_version, + ) if action in {"train", "train_monthly"}: if experiment_name is None or artifact_path is None: raise ValueError("Training needs an experiment and temporary artifact path.") monthly = action == "train_monthly" - if selection_mode == "auto_champion" and config.get("quality_threshold") is None: - raise ValueError("auto_champion requires an absolute quality_threshold.") + if policy == "automatic" and config.get("quality_threshold") is None: + raise ValueError("Automatic promotion requires an absolute quality_threshold.") spec = ( _monthly_training_spec(spark, config, now or datetime.now(UTC)) if monthly else _training_spec(config) ) - if selection_mode == "auto_champion": + if policy == "automatic" or "score_model_selection" in config: champion_version = controlled_champion_version( config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri ) + expected = config.get("champion_version") + if ( + "score_model_selection" in config + and expected is not None + and str(expected) != champion_version + ): + raise ValueError("champion_version does not match the current champion.") else: champion_version = _monthly_champion_version(config) expected = config.get("champion_version") @@ -305,7 +365,7 @@ def run_action( config, spec, candidate, - promote=selection_mode == "auto_champion", + promote=policy == "automatic", ) except Exception as error: # noqa: BLE001 - preserve failure and lifecycle evidence try: @@ -313,19 +373,19 @@ def run_action( except Exception as status_error: # noqa: BLE001 - retain the original failure raise error from status_error raise - if selection_mode == "auto_champion": + if policy == "automatic": return AutoTrainingOutcome( candidate=candidate, alias_change=alias_change, ) return candidate if action == "score": - if selection_mode == "auto_champion": + if selection == "champion": champion_version = controlled_champion_version( config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri ) if champion_version is None: - raise ValueError("auto_champion scoring requires a committed champion.") + raise ValueError("Champion scoring requires a committed champion.") config = {**config, "model_version": champion_version} target = _scoring_target(config) if config.get("model_change_mode", "incremental_append") == "full_rebuild": diff --git a/tests/integration/test_pipeline_integration.py b/skyulf-core/tests/integration/test_preprocessing_chain.py similarity index 100% rename from tests/integration/test_pipeline_integration.py rename to skyulf-core/tests/integration/test_preprocessing_chain.py diff --git a/tests/integration/test_bundle_challenger_lifecycle.py b/skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py similarity index 92% rename from tests/integration/test_bundle_challenger_lifecycle.py rename to skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py index 3adc3cb10..6488e9aa8 100644 --- a/tests/integration/test_bundle_challenger_lifecycle.py +++ b/skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py @@ -12,10 +12,13 @@ @pytest.mark.parametrize("engine", ["pandas", "polars"]) -def test_bundle_nomination_comparison_and_promotion_are_separate(tmp_path, monkeypatch, engine): +@pytest.mark.parametrize("selection", ["pinned_version", "champion"]) +def test_bundle_nomination_comparison_and_promotion_are_separate( + tmp_path, monkeypatch, engine, selection +): """Real artifacts must retain a tied contender and survive failed comparison on either engine.""" path = Path(__file__).resolve().parents[2] / ( - "skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py" + "templates/databricks/template/{{.project_name}}/src/workflow.py" ) spec = importlib.util.spec_from_file_location("sm30_workflow", path) assert spec is not None and spec.loader is not None @@ -42,7 +45,8 @@ def test_bundle_nomination_comparison_and_promotion_are_separate(tmp_path, monke "model_name": "lifecycle_model", "tracking_uri": store, "registry_uri": store, - "model_selection_mode": "auto_champion", + "score_model_selection": selection, + "promotion_policy": "automatic", "model_version": "1", "row_keys": ["id"], "input_columns": ["x"], @@ -86,7 +90,7 @@ def run(version): assert str(client.get_model_version_by_alias("lifecycle_model", "champion").version) == "2" assert str(client.get_model_version_by_alias("lifecycle_model", "challenger").version) == "3" assert client.get_model_version("lifecycle_model", "3").tags["validation_status"] == "rejected" - config["model_selection_mode"] = "pinned_version" + config["promotion_policy"] = "manual_approval" fourth = run(4) assert fourth.model_version == "4" and config["model_version"] == "1" assert str(client.get_model_version_by_alias("lifecycle_model", "champion").version) == "2" diff --git a/tests/integration/test_sm31_notebook_boundary.py b/skyulf-core/tests/integrations/test_databricks_bundle_notebook.py similarity index 97% rename from tests/integration/test_sm31_notebook_boundary.py rename to skyulf-core/tests/integrations/test_databricks_bundle_notebook.py index 0268b4b84..5d25f95c4 100644 --- a/tests/integration/test_sm31_notebook_boundary.py +++ b/skyulf-core/tests/integrations/test_databricks_bundle_notebook.py @@ -18,7 +18,7 @@ def test_notebook_delegates_bound_target_and_selected_action(tmp_path, monkeypat path = ( Path(__file__).resolve().parents[2] - / "skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py" + / "templates/databricks/template/{{.project_name}}/src/workflow.py" ) spec = importlib.util.spec_from_file_location("thin_notebook", path) assert spec is not None and spec.loader is not None diff --git a/tests/integration/test_sm20a_bundle_template.py b/skyulf-core/tests/integrations/test_databricks_bundle_template.py similarity index 99% rename from tests/integration/test_sm20a_bundle_template.py rename to skyulf-core/tests/integrations/test_databricks_bundle_template.py index b152806c2..9cc214955 100644 --- a/tests/integration/test_sm20a_bundle_template.py +++ b/skyulf-core/tests/integrations/test_databricks_bundle_template.py @@ -9,7 +9,7 @@ WORKFLOW = ( Path(__file__).resolve().parents[2] - / "skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py" + / "templates/databricks/template/{{.project_name}}/src/workflow.py" ) diff --git a/skyulf-core/tests/integrations/test_databricks_local_approval.py b/skyulf-core/tests/integrations/test_databricks_local_approval.py new file mode 100644 index 000000000..3e0b93d0b --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_local_approval.py @@ -0,0 +1,176 @@ +"""Manual approval must use an existing model and its pinned training evidence.""" + +import hashlib +import json +from dataclasses import asdict +from typing import Any +from unittest.mock import Mock + +import pandas as pd +import pytest + +from skyulf.integrations.databricks import local_retraining, local_workflow +from skyulf.integrations.mlflow.promotion import AliasConflictError + +mlflow = pytest.importorskip("mlflow") + + +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +def test_manual_approval_reuses_registered_versions_and_replays_receipt( + tmp_path, monkeypatch, engine +): + """Approval, including bootstrap and retry, must never retrain or register a new model.""" + frame = pd.DataFrame( + { + "id": range(12), + "x": [float(i) for i in range(12)], + "target": [10.0 + 2 * i for i in range(12)], + "event_time": pd.to_datetime(["2026-01-10"] * 8 + ["2026-02-10"] * 4, utc=True), + "label_at": pd.to_datetime(["2026-01-11"] * 8 + ["2026-02-11"] * 4, utc=True), + } + ) + read_snapshot = Mock(return_value=frame) + monkeypatch.setattr(local_retraining, "read_training_snapshot", read_snapshot) + monkeypatch.setattr(local_workflow, "read_training_snapshot", Mock(return_value=frame)) + uri = f"sqlite:///{(tmp_path / 'registry.db').as_posix()}" + client = mlflow.MlflowClient(tracking_uri=uri, registry_uri=uri) + client.create_experiment("approval", artifact_location=(tmp_path / "runs").as_uri()) + config = { + "engine": engine, + "training_table": "workspace.test.source", + "training_version": 4, + "model_name": "approval_model", + "tracking_uri": uri, + "registry_uri": uri, + "score_model_selection": "pinned_version", + "promotion_policy": "manual_approval", + "model_version": "1", + "row_keys": ["id"], + "input_columns": ["x"], + "target_column": "target", + "event_column": "event_time", + "label_time_column": "label_at", + "start": "2026-01-01T00:00:00+00:00", + "holdout_start": "2026-02-01T00:00:00+00:00", + "cutoff": "2026-03-01T00:00:00+00:00", + "max_rows": 20, + "max_bytes": 100_000, + "metric": "heldout_rmse", + "min_improvement": 0.1, + "quality_threshold": 100.0, + "pipeline": { + "preprocessing": [], + "modeling": {"type": "linear_regression", "params": {"fit_intercept": False}}, + }, + } + + def train(): + """Create actual artifacts before the separate approval operation.""" + version = len(client.search_model_versions("name = 'approval_model'")) + 1 + return local_workflow.run_action( + None, + config, + "train", + experiment_name="approval", + artifact_path=tmp_path / f"model-{version}", + ) + + def approve(candidate, expected, **changes): + """Pin the exact saved comparison instead of accepting a latest-model fallback.""" + digest = hashlib.sha256( + json.dumps(asdict(candidate.comparison), sort_keys=True, allow_nan=False).encode() + ).hexdigest() + options: dict[str, Any] = { + "candidate_version": candidate.model_version, + "comparison_sha256": digest, + "expected_champion_version": expected, + } + options.update(changes) + return local_workflow.run_action(None, config, "approve", **options) + + first = train() + assert not client.get_registered_model(config["model_name"]).aliases.get("champion") + # Never derive approval data from today's training configuration. + config["training_version"] = 99 + with monkeypatch.context() as no_training: + no_training.setattr( + local_workflow, "train_local_candidate", Mock(side_effect=AssertionError("fit")) + ) + receipt = approve(first, None) + assert receipt.kind == "initial" and receipt.new_version == "1" + assert approve(first, None) == receipt + assert read_snapshot.call_count == 2 + assert read_snapshot.call_args.args[1].version == 4 + assert len(client.search_model_versions("name = 'approval_model'")) == 1 + + config["training_version"] = 4 + config["pipeline"]["modeling"]["params"]["fit_intercept"] = True + second = train() + assert str(client.get_registered_model(config["model_name"]).aliases["champion"]) == "1" + with pytest.raises(ValueError, match="digest"): + approve(second, "1", comparison_sha256="0" * 64) + with pytest.raises(ValueError, match="expected|Expected"): + approve(second, "9") + config["quality_threshold"] = 200.0 + with pytest.raises(ValueError, match="policy"): + approve(second, "1") + config["quality_threshold"] = 100.0 + config["input_columns"] = ["wrong_feature"] + with pytest.raises(ValueError, match="data contract"): + approve(second, "1") + config["input_columns"] = ["x"] + client.set_registered_model_tag(config["model_name"], "pending_alias_event", "uncertain-test") + with pytest.raises(AliasConflictError, match="pending"): + approve(second, "1") + client.delete_registered_model_tag(config["model_name"], "pending_alias_event") + changed_frame = frame.copy() + changed_frame.loc[8:, "target"] += 10.0 + read_snapshot.return_value = changed_frame + with pytest.raises(ValueError, match="comparison"): + approve(second, "1") + read_snapshot.return_value = frame + assert str(client.get_registered_model(config["model_name"]).aliases["champion"]) == "1" + with monkeypatch.context() as no_training: + no_training.setattr( + local_workflow, "train_local_candidate", Mock(side_effect=AssertionError("fit")) + ) + promoted = approve(second, "1") + assert promoted.kind == "promotion" and promoted.prior_version == "1" + assert approve(second, "1") == promoted + assert len(client.search_model_versions("name = 'approval_model'")) == 2 + assert config["model_version"] == "1" + assert str(client.get_registered_model(config["model_name"]).aliases["champion"]) == "2" + with pytest.raises(AliasConflictError): + approve(first, None) + + tied = train() + with pytest.raises(ValueError, match="approve|promotion"): + approve(tied, "2") + assert str(client.get_registered_model(config["model_name"]).aliases["champion"]) == "2" + + +@pytest.mark.parametrize("selection", ["pinned_version", "champion"]) +def test_approval_refuses_automatic_policy_before_registry_access(selection): + """Operator approval is an explicit manual-policy action, not a policy override.""" + with pytest.raises(ValueError, match="manual_approval"): + local_workflow.run_action( + None, + {"score_model_selection": selection, "promotion_policy": "automatic"}, + "approve", + candidate_version="2", + comparison_sha256="a" * 64, + ) + + +def test_direct_approval_service_requires_explicit_manual_policy(): + """Calling the public service directly must not bypass its operator-action policy.""" + from skyulf.integrations.databricks.local_approval import approve_local_candidate + + with pytest.raises(ValueError, match="manual_approval"): + approve_local_candidate( + None, + {"promotion_policy": "automatic"}, + candidate_version="2", + comparison_sha256="a" * 64, + expected_champion_version="1", + ) diff --git a/skyulf-core/tests/integrations/test_databricks_local_retraining.py b/skyulf-core/tests/integrations/test_databricks_local_retraining.py index ceeb12689..8bebd4fa2 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_retraining.py +++ b/skyulf-core/tests/integrations/test_databricks_local_retraining.py @@ -240,6 +240,7 @@ def test_candidate_workflow_logs_and_registers_without_alias(monkeypatch, tmp_pa assert result.comparison.reason == "no_champion" assert run.data.metrics["heldout_rmse"] == pytest.approx(0.0, abs=1e-8) assert "candidate_comparison.json" in artifacts + assert "candidate_training_spec.json" in artifacts assert "model" in artifacts assert run.data.tags["task"] == "training" assert "dataset_id" not in run.data.tags and "phase" not in run.data.tags diff --git a/skyulf-core/tests/integrations/test_databricks_local_workflow.py b/skyulf-core/tests/integrations/test_databricks_local_workflow.py index 38f20d54d..6f7da2fff 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_workflow.py +++ b/skyulf-core/tests/integrations/test_databricks_local_workflow.py @@ -57,6 +57,169 @@ def _one_column_schema(kind): ) +@pytest.mark.parametrize("engine", ["pandas", "polars"]) +@pytest.mark.parametrize("selection", ["pinned_version", "champion"]) +@pytest.mark.parametrize("policy", ["manual_approval", "automatic"]) +def test_training_policy_and_scoring_selection_are_independent( + monkeypatch, tmp_path, engine, selection, policy +): + """Changing registry policy must never silently change a scoring pin on either engine.""" + workflow = _workflow() + config = _config() + config.update( + engine=engine, + score_model_selection=selection, + promotion_policy=policy, + quality_threshold=1.0, + ) + candidate = SimpleNamespace(model_version="2") + train = Mock(return_value=candidate) + decision = Mock(return_value=SimpleNamespace(new_version="2")) + controlled = Mock(return_value="1") + prepare = Mock(return_value=object()) + score = Mock(return_value=SimpleNamespace(input_count=2)) + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr(workflow, "_automatic_promotion", decision) + monkeypatch.setattr(workflow, "controlled_champion_version", controlled) + monkeypatch.setattr(workflow, "resolve_model", Mock(side_effect=AssertionError("raw alias"))) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "provision_prediction_table", Mock()) + monkeypatch.setattr(workflow, "run_incremental_local_batch", score) + + result = workflow.run_action( + object(), config, "train", experiment_name="test", artifact_path=tmp_path / "model" + ) + assert decision.call_args.kwargs["promote"] is (policy == "automatic") + assert train.call_args.kwargs["engine"] == engine + assert train.call_args.kwargs["champion_version"] == "1" + assert (result.candidate if policy == "automatic" else result) is candidate + + controlled.reset_mock() + controlled.return_value = "2" if policy == "automatic" else "1" + workflow.run_action(object(), config, "score") + expected = "2" if selection == "champion" and policy == "automatic" else "1" + assert prepare.call_args.args[0].model.version == expected + assert prepare.call_args.args[0].engine == engine + assert controlled.call_count == (1 if selection == "champion" else 0) + assert config["model_version"] == "1" + assert train.call_count == 1 + score.assert_called_once() + + +@pytest.mark.parametrize( + "fields", + [ + {"score_model_selection": "champion"}, + {"promotion_policy": "automatic"}, + {"score_model_selection": "latest", "promotion_policy": "automatic"}, + {"score_model_selection": "champion", "promotion_policy": "force"}, + {"score_model_selection": None, "promotion_policy": "automatic"}, + { + "score_model_selection": "champion", + "promotion_policy": "automatic", + "model_selection_mode": "auto_champion", + }, + ], +) +def test_invalid_policy_migrations_fail_before_training_or_scoring(monkeypatch, fields): + """Partial or ambiguous migrations must not execute with implicit defaults.""" + workflow = _workflow() + train = Mock() + prepare = Mock() + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr( + workflow, "resolve_model", Mock(side_effect=AssertionError("registry read")) + ) + monkeypatch.setattr( + workflow, "controlled_champion_version", Mock(side_effect=AssertionError("registry read")) + ) + for action in ("train", "score"): + with pytest.raises(ValueError, match="selection|policy"): + workflow.run_action( + object(), + {**_config(), **fields}, + action, + experiment_name="test", + artifact_path="unused", + ) + train.assert_not_called() + prepare.assert_not_called() + + +@pytest.mark.parametrize("policy", ["manual_approval", "automatic"]) +def test_champion_selection_without_champion_cannot_publish(monkeypatch, policy): + """Following champion must not fall back to a configured pin when no champion exists.""" + workflow = _workflow() + config = {**_config(), "score_model_selection": "champion", "promotion_policy": policy} + prepare = Mock() + provision = Mock() + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value=None)) + monkeypatch.setattr(workflow, "prepare_local_workflow", prepare) + monkeypatch.setattr(workflow, "provision_prediction_table", provision) + monkeypatch.setattr( + workflow, "run_incremental_local_batch", Mock(side_effect=AssertionError("score write")) + ) + with pytest.raises(ValueError, match="committed champion"): + workflow.run_action(object(), config, "score") + prepare.assert_not_called() + provision.assert_not_called() + + +def test_pinned_scoring_does_not_allow_ungated_automatic_training(monkeypatch, tmp_path): + """An explicit scoring pin must not disable the automatic promotion quality gate.""" + workflow = _workflow() + config = { + **_config(), + "score_model_selection": "pinned_version", + "promotion_policy": "automatic", + } + train = Mock() + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr( + workflow, "resolve_model", Mock(side_effect=AssertionError("registry read")) + ) + with pytest.raises(ValueError, match="quality_threshold"): + workflow.run_action( + object(), config, "train", experiment_name="test", artifact_path=tmp_path / "model" + ) + train.assert_not_called() + + +@pytest.mark.parametrize("policy", ["manual_approval", "automatic"]) +def test_independent_training_checks_expected_champion_before_fit(monkeypatch, policy): + """A stale operator expectation must fail even when scoring keeps an explicit pin.""" + workflow = _workflow() + config = { + **_config(), + "score_model_selection": "pinned_version", + "promotion_policy": policy, + "quality_threshold": 1.0, + } + train = Mock() + monkeypatch.setattr(workflow, "train_local_candidate", train) + monkeypatch.setattr(workflow, "controlled_champion_version", Mock(return_value="2")) + with pytest.raises(ValueError, match="champion_version"): + workflow.run_action( + object(), config, "train", experiment_name="test", artifact_path="unused" + ) + train.assert_not_called() + + +@pytest.mark.parametrize( + "legacy,expected", + [ + ("auto_champion", ("champion", "automatic")), + ("pinned_version", ("pinned_version", "manual_approval")), + ], +) +def test_legacy_model_selection_has_an_explicit_compatible_migration(legacy, expected): + """Old projects must keep their behavior while receiving a concrete migration warning.""" + workflow = _workflow() + with pytest.warns(DeprecationWarning, match="model_selection_mode is deprecated"): + assert workflow._workflow_policies({"model_selection_mode": legacy}) == expected + + def test_train_preserves_selected_polars_engine_and_never_promotes(monkeypatch, tmp_path): """A training job must only produce a candidate with the chosen fit engine.""" workflow = _workflow() diff --git a/tests/unit/test_advanced_cleaning.py b/skyulf-core/tests/unit/test_advanced_cleaning.py similarity index 100% rename from tests/unit/test_advanced_cleaning.py rename to skyulf-core/tests/unit/test_advanced_cleaning.py diff --git a/tests/unit/test_binning_comprehensive.py b/skyulf-core/tests/unit/test_binning_comprehensive.py similarity index 100% rename from tests/unit/test_binning_comprehensive.py rename to skyulf-core/tests/unit/test_binning_comprehensive.py diff --git a/tests/unit/test_casting.py b/skyulf-core/tests/unit/test_casting_nodes.py similarity index 100% rename from tests/unit/test_casting.py rename to skyulf-core/tests/unit/test_casting_nodes.py diff --git a/tests/unit/test_cleaning.py b/skyulf-core/tests/unit/test_cleaning.py similarity index 100% rename from tests/unit/test_cleaning.py rename to skyulf-core/tests/unit/test_cleaning.py diff --git a/tests/unit/test_cleaning_nodes.py b/skyulf-core/tests/unit/test_cleaning_nodes.py similarity index 100% rename from tests/unit/test_cleaning_nodes.py rename to skyulf-core/tests/unit/test_cleaning_nodes.py diff --git a/tests/unit/test_cross_validation_all_methods.py b/skyulf-core/tests/unit/test_cross_validation_all_methods.py similarity index 85% rename from tests/unit/test_cross_validation_all_methods.py rename to skyulf-core/tests/unit/test_cross_validation_all_methods.py index 3be07b7ec..15437cbd2 100644 --- a/tests/unit/test_cross_validation_all_methods.py +++ b/skyulf-core/tests/unit/test_cross_validation_all_methods.py @@ -12,6 +12,8 @@ Advanced Tuning flow tests each CV method inside hyperparameter search. """ +from typing import Literal + import numpy as np import pandas as pd import pytest @@ -29,7 +31,7 @@ ) # --------------------------------------------------------------------------- -# Fixtures — larger datasets so multi-fold CV doesn't starve +# Fixtures — larger datasets so multi-fold CV doesn't starve # --------------------------------------------------------------------------- @@ -138,12 +140,12 @@ def _assert_cv_result(result: dict, n_folds: int, problem_type: str) -> None: # ========================================================================= -# SIMPLE FLOW — Basic Training cross_validate (all 5 CV methods) +# SIMPLE FLOW — Basic Training cross_validate (all 5 CV methods) # ========================================================================= class TestSimpleCVClassification: - """Basic Training CV — Classification with all 5 methods.""" + """Basic Training CV — Classification with all 5 methods.""" def test_k_fold(self, classification_dataset: SplitDataset) -> None: est = _make_classification_estimator() @@ -243,7 +245,7 @@ def test_nested_cv(self, classification_dataset: SplitDataset) -> None: class TestSimpleCVRegression: - """Basic Training CV — Regression with all 5 methods.""" + """Basic Training CV — Regression with all 5 methods.""" def test_k_fold(self, regression_dataset: SplitDataset) -> None: est = _make_regression_estimator() @@ -314,7 +316,7 @@ def test_time_series_split_explicit_column( assert any("sorted by 'date'" in log for log in logs) def test_time_series_split_no_datetime_column(self, regression_dataset: SplitDataset) -> None: - """Time Series Split without any datetime column — should warn and use row order.""" + """Time Series Split without any datetime column — should warn and use row order.""" est = _make_regression_estimator() logs: list[str] = [] result = est.cross_validate( @@ -346,7 +348,7 @@ def test_nested_cv(self, regression_dataset: SplitDataset) -> None: # ========================================================================= -# ADVANCED FLOW — Tuning with each CV method × each search strategy +# ADVANCED FLOW — Tuning with each CV method × each search strategy # ========================================================================= # All 5 tuning strategies @@ -359,12 +361,14 @@ def test_nested_cv(self, regression_dataset: SplitDataset) -> None: def _run_tuning_test( dataset: SplitDataset, problem_type: str, - cv_type: str, - strategy: str, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], + strategy: Literal["grid", "random", "optuna", "halving_grid", "halving_random"], ) -> None: """Run a tuning session with the given strategy and cv_type. - Halving strategies may fail on small data — we accept that as expected. + Halving strategies may fail on small data — we accept that as expected. """ if problem_type == "classification": calculator = LogisticRegressionCalculator() @@ -387,6 +391,7 @@ def _run_tuning_test( search_space=search_space, ) + assert isinstance(dataset.train, pd.DataFrame) X = dataset.train.drop(columns=["target"]) y = dataset.train["target"] @@ -410,67 +415,111 @@ def _run_tuning_test( class TestAdvancedTuningCV: - """Grid Search — verify each CV method works.""" + """Grid Search — verify each CV method works.""" @pytest.mark.parametrize("cv_type", CV_METHODS) - def test_grid_classification(self, classification_dataset: SplitDataset, cv_type: str) -> None: + def test_grid_classification( + self, + classification_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], + ) -> None: _run_tuning_test(classification_dataset, "classification", cv_type, "grid") @pytest.mark.parametrize("cv_type", CV_METHODS) - def test_grid_regression(self, regression_dataset: SplitDataset, cv_type: str) -> None: + def test_grid_regression( + self, + regression_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], + ) -> None: _run_tuning_test(regression_dataset, "regression", cv_type, "grid") class TestRandomSearchCV: - """Random Search — verify each CV method works.""" + """Random Search — verify each CV method works.""" @pytest.mark.parametrize("cv_type", CV_METHODS) def test_random_classification( - self, classification_dataset: SplitDataset, cv_type: str + self, + classification_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], ) -> None: _run_tuning_test(classification_dataset, "classification", cv_type, "random") @pytest.mark.parametrize("cv_type", CV_METHODS) - def test_random_regression(self, regression_dataset: SplitDataset, cv_type: str) -> None: + def test_random_regression( + self, + regression_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], + ) -> None: _run_tuning_test(regression_dataset, "regression", cv_type, "random") class TestHalvingGridCV: - """Halving Grid Search — verify each CV method works.""" + """Halving Grid Search — verify each CV method works.""" @pytest.mark.parametrize("cv_type", CV_METHODS) def test_halving_grid_classification( - self, classification_dataset: SplitDataset, cv_type: str + self, + classification_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], ) -> None: _run_tuning_test(classification_dataset, "classification", cv_type, "halving_grid") @pytest.mark.parametrize("cv_type", CV_METHODS) - def test_halving_grid_regression(self, regression_dataset: SplitDataset, cv_type: str) -> None: + def test_halving_grid_regression( + self, + regression_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], + ) -> None: _run_tuning_test(regression_dataset, "regression", cv_type, "halving_grid") class TestHalvingRandomCV: - """Halving Random Search — verify each CV method works.""" + """Halving Random Search — verify each CV method works.""" @pytest.mark.parametrize("cv_type", CV_METHODS) def test_halving_random_classification( - self, classification_dataset: SplitDataset, cv_type: str + self, + classification_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], ) -> None: _run_tuning_test(classification_dataset, "classification", cv_type, "halving_random") @pytest.mark.parametrize("cv_type", CV_METHODS) def test_halving_random_regression( - self, regression_dataset: SplitDataset, cv_type: str + self, + regression_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], ) -> None: _run_tuning_test(regression_dataset, "regression", cv_type, "halving_random") class TestOptunaCV: - """Optuna Search — verify each CV method works.""" + """Optuna Search — verify each CV method works.""" @pytest.mark.parametrize("cv_type", CV_METHODS) def test_optuna_classification( - self, classification_dataset: SplitDataset, cv_type: str + self, + classification_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], ) -> None: try: _run_tuning_test(classification_dataset, "classification", cv_type, "optuna") @@ -478,7 +527,13 @@ def test_optuna_classification( pytest.skip("Optuna not installed") @pytest.mark.parametrize("cv_type", CV_METHODS) - def test_optuna_regression(self, regression_dataset: SplitDataset, cv_type: str) -> None: + def test_optuna_regression( + self, + regression_dataset: SplitDataset, + cv_type: Literal[ + "k_fold", "stratified_k_fold", "time_series_split", "shuffle_split", "nested_cv" + ], + ) -> None: try: _run_tuning_test(regression_dataset, "regression", cv_type, "optuna") except ImportError: diff --git a/tests/unit/test_cv_basic_vs_advanced.py b/skyulf-core/tests/unit/test_cv_basic_vs_advanced.py similarity index 97% rename from tests/unit/test_cv_basic_vs_advanced.py rename to skyulf-core/tests/unit/test_cv_basic_vs_advanced.py index ad2443c9b..6825f8a33 100644 --- a/tests/unit/test_cv_basic_vs_advanced.py +++ b/skyulf-core/tests/unit/test_cv_basic_vs_advanced.py @@ -177,7 +177,8 @@ def test_advanced_tuning_nested_cv_uses_standard_fold( tuning_config.__dict__, ) - _, tuning_result = tuning_est.model # type: ignore[misc] + assert isinstance(tuning_est.model, tuple) + _, tuning_result = tuning_est.model best_params = tuning_result.best_params # Simulate engine.py fix: override nested_cv -> stratified_k_fold @@ -242,7 +243,8 @@ def test_basic_vs_advanced_metric_keys_match( "target", tuning_config.__dict__, ) - _, tuning_result = tuning_est.model # type: ignore[misc] + assert isinstance(tuning_est.model, tuple) + _, tuning_result = tuning_est.model best_params = tuning_result.best_params adv_est = StatefulEstimator(calc, applier, "cv_node") @@ -293,7 +295,8 @@ def test_regression_nested_cv_uses_k_fold( tuning_config.__dict__, ) - _, tuning_result = tuning_est.model # type: ignore[misc] + assert isinstance(tuning_est.model, tuple) + _, tuning_result = tuning_est.model best_params = tuning_result.best_params # Engine.py logic: regression -> k_fold @@ -347,7 +350,8 @@ def test_classification_nested_cv_uses_stratified( tuning_config.__dict__, ) - _, tuning_result = tuning_est.model # type: ignore[misc] + assert isinstance(tuning_est.model, tuple) + _, tuning_result = tuning_est.model best_params = tuning_result.best_params # Engine.py logic: classification -> stratified_k_fold diff --git a/tests/unit/test_cv_polars_final.py b/skyulf-core/tests/unit/test_cv_polars_final.py similarity index 71% rename from tests/unit/test_cv_polars_final.py rename to skyulf-core/tests/unit/test_cv_polars_final.py index 7d416127a..3e9dc3b63 100644 --- a/tests/unit/test_cv_polars_final.py +++ b/skyulf-core/tests/unit/test_cv_polars_final.py @@ -20,9 +20,15 @@ def test_cross_validation_polars(): calculator = LogisticRegressionCalculator() applier = LogisticRegressionApplier() - # Run CV + # Pin native Polars support; the public annotation currently omits this accepted input. results = perform_cross_validation( - calculator=calculator, applier=applier, X=X, y=y, config={}, n_folds=2, cv_type="k_fold" + calculator=calculator, + applier=applier, + X=X, # ty: ignore[invalid-argument-type] - exercise the native Polars runtime contract + y=y, + config={}, + n_folds=2, + cv_type="k_fold", ) assert "aggregated_metrics" in results diff --git a/tests/unit/test_drift.py b/skyulf-core/tests/unit/test_drift.py similarity index 100% rename from tests/unit/test_drift.py rename to skyulf-core/tests/unit/test_drift.py diff --git a/tests/unit/test_encoding.py b/skyulf-core/tests/unit/test_encoding.py similarity index 100% rename from tests/unit/test_encoding.py rename to skyulf-core/tests/unit/test_encoding.py diff --git a/tests/unit/test_encoding_scenarios.py b/skyulf-core/tests/unit/test_encoding_scenarios.py similarity index 95% rename from tests/unit/test_encoding_scenarios.py rename to skyulf-core/tests/unit/test_encoding_scenarios.py index 61258a671..86a7e613a 100644 --- a/tests/unit/test_encoding_scenarios.py +++ b/skyulf-core/tests/unit/test_encoding_scenarios.py @@ -32,8 +32,12 @@ def test_scenario_1_xy_then_split_then_encode(): split_data = tt_splitter.apply(xy_data, {"test_size": 0.2, "random_state": 42}) assert isinstance(split_data, SplitDataset) + assert isinstance(split_data.train, tuple) + assert isinstance(split_data.test, tuple) X_train, y_train = split_data.train X_test, y_test = split_data.test + assert isinstance(X_train, pd.DataFrame) + assert isinstance(X_test, pd.DataFrame) print(f"Step 2 (Train/Test Split): Train size={len(X_train)}, Test size={len(X_test)}") # 3. Encoding @@ -75,6 +79,7 @@ def test_scenario_2_split_then_xy_then_encode(): # split_df.train is now a plain DataFrame (no target_column was set, so no # X/y split was performed at this stage). train_df = split_df.train + assert isinstance(train_df, pd.DataFrame) print(f"Step 1 (Train/Test Split): Train shape={train_df.shape}") # 2. Feature Target Split (on SplitDataset) @@ -82,7 +87,9 @@ def test_scenario_2_split_then_xy_then_encode(): split_xy = ft_splitter.apply(split_df, {"target_column": "species"}) assert isinstance(split_xy, SplitDataset) + assert isinstance(split_xy.train, tuple) X_train, y_train = split_xy.train + assert isinstance(X_train, pd.DataFrame) print(f"Step 2 (XY Split): X_train shape={X_train.shape}, y_train shape={y_train.shape}") # 3. Encoding diff --git a/tests/unit/test_encoding_target_guard.py b/skyulf-core/tests/unit/test_encoding_target_guard.py similarity index 98% rename from tests/unit/test_encoding_target_guard.py rename to skyulf-core/tests/unit/test_encoding_target_guard.py index fa23da6c6..d756b10fb 100644 --- a/tests/unit/test_encoding_target_guard.py +++ b/skyulf-core/tests/unit/test_encoding_target_guard.py @@ -173,7 +173,7 @@ def test_encodes_target_column(self, iris_Xy): calc = LabelEncoderCalculator() params = calc.fit(X_with_target, {"columns": ["Species"]}) assert params.get("type") == "label_encoder" - assert "Species" in params.get("columns", []) or "Species" in params.get("mappings", {}) + assert "Species" in (params.get("columns") or []) or "Species" in params.get("mappings", {}) class TestOrdinalEncoderKeepsTarget: diff --git a/tests/unit/test_feature_generation.py b/skyulf-core/tests/unit/test_feature_generation.py similarity index 100% rename from tests/unit/test_feature_generation.py rename to skyulf-core/tests/unit/test_feature_generation.py diff --git a/tests/unit/test_feature_generation_speed.py b/skyulf-core/tests/unit/test_feature_generation_speed.py similarity index 100% rename from tests/unit/test_feature_generation_speed.py rename to skyulf-core/tests/unit/test_feature_generation_speed.py diff --git a/tests/unit/test_feature_selection.py b/skyulf-core/tests/unit/test_feature_selection.py similarity index 100% rename from tests/unit/test_feature_selection.py rename to skyulf-core/tests/unit/test_feature_selection.py diff --git a/tests/unit/test_feature_selection_comprehensive.py b/skyulf-core/tests/unit/test_feature_selection_comprehensive.py similarity index 95% rename from tests/unit/test_feature_selection_comprehensive.py rename to skyulf-core/tests/unit/test_feature_selection_comprehensive.py index fc3f9fb42..7be32f4fc 100644 --- a/tests/unit/test_feature_selection_comprehensive.py +++ b/skyulf-core/tests/unit/test_feature_selection_comprehensive.py @@ -60,6 +60,7 @@ def test_variance_threshold(regression_data): # Threshold 0 drops constant config = {"method": "variance_threshold", "threshold": 0.0} params = calc.fit(df, config) + assert isinstance(params, dict) res = applier.apply(df, params) assert "constant" not in res.columns @@ -80,6 +81,7 @@ def test_univariate_k_best_regression(regression_data): "problem_type": "regression", } params = calc.fit(regression_data, config) + assert isinstance(params, dict) res = applier.apply(regression_data, params) assert "A" in res.columns @@ -102,6 +104,7 @@ def test_univariate_percentile_classification(classification_data): "problem_type": "classification", } params = calc.fit(classification_data, config) + assert isinstance(params, dict) res = applier.apply(classification_data, params) assert "A" in res.columns @@ -119,6 +122,7 @@ def test_univariate_fpr(regression_data): "target_column": "target", } params = calc.fit(regression_data, config) + assert isinstance(params, dict) res = applier.apply(regression_data, params) # A and B should be significant @@ -140,6 +144,7 @@ def test_generic_univariate(regression_data): "target_column": "target", } params = calc.fit(regression_data, config) + assert isinstance(params, dict) res = applier.apply(regression_data, params) # Should pick A (highest correlation) @@ -159,6 +164,7 @@ def test_select_from_model_rf(regression_data): "problem_type": "regression", } params = calc.fit(regression_data, config) + assert isinstance(params, dict) res = applier.apply(regression_data, params) # RF should find A and B important @@ -180,6 +186,7 @@ def test_rfe_linear(regression_data): "problem_type": "regression", } params = calc.fit(regression_data, config) + assert isinstance(params, dict) res = applier.apply(regression_data, params) assert "A" in res.columns diff --git a/tests/unit/test_feature_selection_polars.py b/skyulf-core/tests/unit/test_feature_selection_polars.py similarity index 96% rename from tests/unit/test_feature_selection_polars.py rename to skyulf-core/tests/unit/test_feature_selection_polars.py index afcb0d6dc..dcfce593e 100644 --- a/tests/unit/test_feature_selection_polars.py +++ b/skyulf-core/tests/unit/test_feature_selection_polars.py @@ -27,6 +27,7 @@ def test_variance_threshold_polars(): # Threshold 0 drops constant config = {"method": "variance_threshold", "threshold": 0.0} params = calc.fit(df, config) + assert isinstance(params, dict) res = applier.apply(df, params) assert "B" not in res.columns @@ -60,6 +61,7 @@ def test_univariate_k_best_regression_polars(): "problem_type": "regression", } params = calc.fit(df, config) + assert isinstance(params, dict) res = applier.apply(df, params) assert "A" in res.columns diff --git a/tests/unit/test_filtering.py b/skyulf-core/tests/unit/test_filtering.py similarity index 100% rename from tests/unit/test_filtering.py rename to skyulf-core/tests/unit/test_filtering.py diff --git a/tests/unit/test_imputation.py b/skyulf-core/tests/unit/test_imputation.py similarity index 100% rename from tests/unit/test_imputation.py rename to skyulf-core/tests/unit/test_imputation.py diff --git a/tests/unit/test_imputation_backend.py b/skyulf-core/tests/unit/test_imputation_backend.py similarity index 100% rename from tests/unit/test_imputation_backend.py rename to skyulf-core/tests/unit/test_imputation_backend.py diff --git a/tests/unit/test_inspection.py b/skyulf-core/tests/unit/test_inspection_nodes.py similarity index 75% rename from tests/unit/test_inspection.py rename to skyulf-core/tests/unit/test_inspection_nodes.py index f52a8fd2d..9e7605cdf 100644 --- a/tests/unit/test_inspection.py +++ b/skyulf-core/tests/unit/test_inspection_nodes.py @@ -15,7 +15,8 @@ def test_dataset_profile(): applier = DatasetProfileApplier() artifacts = calc.fit(df, {}) - result = applier.apply(df, artifacts) + assert isinstance(artifacts, dict) + result = applier.apply(df, dict(artifacts)) assert result.equals(df) # Should be identity assert "profile" in artifacts @@ -30,8 +31,11 @@ def test_data_snapshot(): config = {"n_rows": 2} artifacts = calc.fit(df, config) - result = applier.apply(df, artifacts) + assert isinstance(artifacts, dict) + result = applier.apply(df, dict(artifacts)) assert result.equals(df) assert len(artifacts["snapshot"]) == 2 - assert artifacts["snapshot"][0]["a"] == 0 + snapshot = artifacts["snapshot"] + assert isinstance(snapshot, list) + assert snapshot[0]["a"] == 0 diff --git a/tests/unit/test_label_encoder_target.py b/skyulf-core/tests/unit/test_label_encoder_target.py similarity index 94% rename from tests/unit/test_label_encoder_target.py rename to skyulf-core/tests/unit/test_label_encoder_target.py index 74722c570..229a9158c 100644 --- a/tests/unit/test_label_encoder_target.py +++ b/skyulf-core/tests/unit/test_label_encoder_target.py @@ -27,7 +27,8 @@ def test_label_encoder_on_target_after_split(): # fit returns empty config split_params = split_calc.fit(dataset_tuple, split_config) # apply returns SplitDataset - split_dataset = split_applier.apply(dataset_tuple, split_params) + assert isinstance(split_params, dict) + split_dataset = split_applier.apply(dataset_tuple, dict(split_params)) assert isinstance(split_dataset, SplitDataset) assert isinstance(split_dataset.train, tuple) @@ -86,7 +87,9 @@ def test_label_encoder_on_target_after_split(): assert set(y_test_new.unique()).issubset({0, 1}) # Check consistency on Test + assert isinstance(split_dataset.test, tuple) original_y_test = split_dataset.test[1] + assert isinstance(original_y_test, pd.Series) # If Test has 'A', it must be encoded to same value as in Train if "A" in original_y_test.values: diff --git a/tests/unit/test_outliers.py b/skyulf-core/tests/unit/test_outliers.py similarity index 100% rename from tests/unit/test_outliers.py rename to skyulf-core/tests/unit/test_outliers.py diff --git a/tests/unit/test_preprocessing_comprehensive_suite.py b/skyulf-core/tests/unit/test_preprocessing_comprehensive_suite.py similarity index 100% rename from tests/unit/test_preprocessing_comprehensive_suite.py rename to skyulf-core/tests/unit/test_preprocessing_comprehensive_suite.py diff --git a/tests/unit/test_preprocessing_feature_nodes.py b/skyulf-core/tests/unit/test_preprocessing_feature_nodes.py similarity index 100% rename from tests/unit/test_preprocessing_feature_nodes.py rename to skyulf-core/tests/unit/test_preprocessing_feature_nodes.py diff --git a/tests/unit/test_profiling.py b/skyulf-core/tests/unit/test_profiling.py similarity index 93% rename from tests/unit/test_profiling.py rename to skyulf-core/tests/unit/test_profiling.py index 407b4dfbd..7dddaa813 100644 --- a/tests/unit/test_profiling.py +++ b/skyulf-core/tests/unit/test_profiling.py @@ -58,6 +58,7 @@ def test_classification_target(sample_df): # Check Rule Discovery (Decision Tree) assert profile.rule_tree is not None assert len(profile.rule_tree.nodes) > 0 + assert profile.rule_tree.rules is not None assert len(profile.rule_tree.rules) > 0 # Check if rules look like classification rules @@ -75,6 +76,7 @@ def test_regression_target(sample_df): # Check Rule Discovery (Decision Tree Regressor) assert profile.rule_tree is not None assert len(profile.rule_tree.nodes) > 0 + assert profile.rule_tree.rules is not None assert len(profile.rule_tree.rules) > 0 # Check if rules look like regression rules @@ -83,10 +85,12 @@ def test_regression_target(sample_df): # Check Feature Importance # Age should be important because we engineered it + assert profile.rule_tree.feature_importances is not None importances = { item["feature"]: item["importance"] for item in profile.rule_tree.feature_importances } assert "age" in importances + assert isinstance(importances["age"], float) assert importances["age"] > 0.1 # Should be significant @@ -176,6 +180,8 @@ def test_high_cardinality_classification(): assert profile.rule_tree is not None + assert profile.rule_tree is not None + assert profile.rule_tree.rules is not None rules_text = "\n".join(profile.rule_tree.rules) assert "Other" in rules_text or "Class_0" in rules_text @@ -189,6 +195,8 @@ def test_force_regression_on_id(): profile = analyzer.analyze(target_col="id") # Check if it ran as regression (rules should have "Value =") + assert profile.rule_tree is not None + assert profile.rule_tree.rules is not None rules_text = "\n".join(profile.rule_tree.rules) assert "Value =" in rules_text @@ -203,6 +211,8 @@ def test_force_classification_on_id(): # Check if it ran as classification (rules should have "Class =" or just the class name) # And since it has 100 unique values, it should have grouped them. + assert profile.rule_tree is not None + assert profile.rule_tree.rules is not None rules_text = "\n".join(profile.rule_tree.rules) # Visualizer format is "THEN {class_name}" assert "THEN Other" in rules_text or "THEN" in rules_text diff --git a/skyulf-core/tests/unit/test_registry_metadata.py b/skyulf-core/tests/unit/test_registry_metadata.py new file mode 100644 index 000000000..4c4f2e1ff --- /dev/null +++ b/skyulf-core/tests/unit/test_registry_metadata.py @@ -0,0 +1,17 @@ +"""Core model metadata must be discoverable without backend setup.""" + +from skyulf.modeling.classification import ( + LogisticRegressionCalculator, + RandomForestClassifierCalculator, +) +from skyulf.registry import NodeRegistry + + +def test_registry(): + """Missing dynamic models or parameters must fail instead of only printing a warning.""" + assert hasattr(LogisticRegressionCalculator, "__node_meta__") + assert hasattr(RandomForestClassifierCalculator, "__node_meta__") + metadata = NodeRegistry.get_all_metadata() + assert "logistic_regression" in metadata + assert "random_forest_classifier" in metadata + assert "max_iter" in (metadata["logistic_regression"].get("params") or {}) diff --git a/tests/unit/test_resampling.py b/skyulf-core/tests/unit/test_resampling_nodes.py similarity index 100% rename from tests/unit/test_resampling.py rename to skyulf-core/tests/unit/test_resampling_nodes.py diff --git a/tests/unit/test_scaling.py b/skyulf-core/tests/unit/test_scaling_nodes.py similarity index 96% rename from tests/unit/test_scaling.py rename to skyulf-core/tests/unit/test_scaling_nodes.py index cbe8a2b3e..fdbc0fcb3 100644 --- a/tests/unit/test_scaling.py +++ b/skyulf-core/tests/unit/test_scaling_nodes.py @@ -33,6 +33,7 @@ def test_standard_scaler(sample_df): assert params["type"] == "standard_scaler" assert params["columns"] == ["A", "B"] + assert params["mean"] is not None assert np.isclose(params["mean"][0], 3.0) # Mean of 1..5 is 3 assert np.isclose(params["mean"][1], 30.0) # Mean of 10..50 is 30 @@ -86,6 +87,7 @@ def test_robust_scaler(sample_df): # Median of 1,2,3,4,5,1000 is (3+4)/2 = 3.5 # Center should be median + assert params["center"] is not None assert np.isclose(params["center"][0], 3.5) # Transformed values should be centered around 0 (roughly) @@ -104,6 +106,7 @@ def test_maxabs_scaler(sample_df): params = calc.fit(df, config) assert params["type"] == "maxabs_scaler" + assert params["max_abs"] is not None assert np.isclose(params["max_abs"][0], 10.0) # 2. Apply diff --git a/tests/unit/test_split.py b/skyulf-core/tests/unit/test_split_nodes.py similarity index 84% rename from tests/unit/test_split.py rename to skyulf-core/tests/unit/test_split_nodes.py index 50abed9dd..832ca1672 100644 --- a/tests/unit/test_split.py +++ b/skyulf-core/tests/unit/test_split_nodes.py @@ -21,7 +21,9 @@ def test_data_splitter_basic(sample_df): # split() now returns plain DataFrames in train/test (no placeholder y). train_df = ds.train + assert isinstance(train_df, pd.DataFrame) test_df = ds.test + assert isinstance(test_df, pd.DataFrame) assert len(train_df) == 80 assert len(test_df) == 20 assert ds.validation is None @@ -33,8 +35,11 @@ def test_data_splitter_validation(sample_df): # Total 100. Test=20. Val=10. Train=70. test_df = ds.test + assert isinstance(test_df, pd.DataFrame) val_df = ds.validation + assert isinstance(val_df, pd.DataFrame) train_df = ds.train + assert isinstance(train_df, pd.DataFrame) assert len(test_df) == 20 assert len(val_df) == 10 assert len(train_df) == 70 @@ -47,5 +52,6 @@ def test_data_splitter_stratify(sample_df): # Check stratification in test set (should be 50/50 split of A/B roughly) # 20 samples total -> 10 A, 10 B test_df = ds.test + assert isinstance(test_df, pd.DataFrame) assert test_df["target"].value_counts()["A"] == 10 assert test_df["target"].value_counts()["B"] == 10 diff --git a/tests/unit/test_transformations.py b/skyulf-core/tests/unit/test_transformations.py similarity index 100% rename from tests/unit/test_transformations.py rename to skyulf-core/tests/unit/test_transformations.py diff --git a/tests/unit/test_transformations_polars.py b/skyulf-core/tests/unit/test_transformations_polars.py similarity index 100% rename from tests/unit/test_transformations_polars.py rename to skyulf-core/tests/unit/test_transformations_polars.py diff --git a/tests/unit/test_dynamic_registry_manual.py b/tests/unit/test_dynamic_registry_manual.py deleted file mode 100644 index 2b6cc03db..000000000 --- a/tests/unit/test_dynamic_registry_manual.py +++ /dev/null @@ -1,63 +0,0 @@ -import io -import os -import sys - -# Force UTF-8 output to handle emoji on Windows -if sys.stdout.encoding != "utf-8": - sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") - sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace") - -# Add workspace root to sys.path to ensure we can import backend and skyulf-core -sys.path.append(os.getcwd()) -# Also add skyulf-core specifically if it's not installed in the env -sys.path.append(os.path.join(os.getcwd(), "skyulf-core")) - -from skyulf.modeling.classification import ( - LogisticRegressionCalculator, - RandomForestClassifierCalculator, -) -from skyulf.registry import NodeRegistry as SkyulfRegistry - - -def test_registry(): - print("Testing Dynamic Node Registry...") - - # Check if Skyulf classes have __node_meta__ - if hasattr(LogisticRegressionCalculator, "__node_meta__"): - print( - f"✅ LogisticRegressionCalculator has metadata: {LogisticRegressionCalculator.__node_meta__}" - ) - else: - print("❌ LogisticRegressionCalculator MISSING metadata") - - if hasattr(RandomForestClassifierCalculator, "__node_meta__"): - print( - f"✅ RandomForestClassifierCalculator has metadata: {RandomForestClassifierCalculator.__node_meta__}" - ) - else: - print("❌ RandomForestClassifierCalculator MISSING metadata") - - # Get all nodes directly from the core registry - all_metadata = SkyulfRegistry.get_all_metadata() - - # Check if our dynamic nodes are in the list - dynamic_ids = ["logistic_regression", "random_forest_classifier"] - found_map = dict.fromkeys(dynamic_ids, False) - - for node_id, meta in all_metadata.items(): - if node_id in found_map: - found_map[node_id] = True - print(f"✅ Found dynamic node in registry: {node_id} ({meta.get('name')})") - if node_id == "logistic_regression": - if "max_iter" in (meta.get("params") or {}): - print(f" -> Params correctly populated: {meta.get('params')}") - else: - print(f" -> ❌ Params missing: {meta.get('params')}") - - for id, found in found_map.items(): - if not found: - print(f"❌ Failed to find node {id} in SkyulfRegistry") - - -if __name__ == "__main__": - test_registry() From 6a7f9e95da27d93a2c1a1778e453f6fc3d1cc4ef Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Fri, 25 Sep 2026 10:09:59 +0300 Subject: [PATCH 58/85] feat: add explicit candidate rejection and repeatable rollback Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 6 +- docs/user_guide/databricks_bundle.md | 51 +++++- docs/user_guide/mlflow_registry.md | 17 ++ .../46-sm32-reject-rollback-progress.md | 62 +++++++ initiatives/spark_and_mlflow/HANDOFF.md | 13 +- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 8 +- .../integrations/databricks/local_approval.py | 78 ++++++-- .../integrations/databricks/local_workflow.py | 31 +++- .../skyulf/integrations/mlflow/challenger.py | 3 +- .../skyulf/integrations/mlflow/promotion.py | 45 ++++- .../skyulf/integrations/mlflow/rejection.py | 110 ++++++++++++ .../test_databricks_local_approval.py | 71 ++++++++ .../integrations/test_mlflow_promotion.py | 168 +++++++++++++++++- 13 files changed, 633 insertions(+), 30 deletions(-) create mode 100644 initiatives/spark_and_mlflow/46-sm32-reject-rollback-progress.md create mode 100644 skyulf-core/skyulf/integrations/mlflow/rejection.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index b2c2ced08..de8b6ecc9 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -10,6 +10,10 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed +- Local workflow adds explicit reject and rollback actions without retraining. + Rejection preserves evaluation results and blocks implicit reconsideration; + unchanged retries reuse checked rejection/rollback receipts. Scoring pins + remain unchanged; Bundle operator wiring and live validation are pending. - Core-owned tests now live under `skyulf-core/tests`, including the Bundle template/notebook/lifecycle tests. Backend and frontend contract tests retain their own scope; moved tests also participate in Core's type checks. @@ -20,7 +24,7 @@ execution, MLflow registry and Databricks delivery remain under development. - Core's local workflow accepts independent scoring selection and promotion policies. All four combinations preserve scoring pins and promotion gates; partial/mixed configurations fail early. Legacy modes retain their behavior. - Bundle prompts and the remaining manual lifecycle actions are pending in SM-32. + Bundle prompts and operator-action handoff are pending in SM-32. - Bundle initialization accepts an optional business risk label and documents the PayingRegNo cost-tag choice. New lifecycle receipts use from_version; older from and compact receipts remain readable. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index 2bfa203a9..a4489d549 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -80,7 +80,8 @@ still uses its existing `model_selection_mode` and job graph. Do not migrate only its JSON: the lifecycle actions and matching job handoff must be delivered together. `manual_approval` currently means no automatic promotion; approve, reject and rollback are separate operator actions. The library now supports -`approve`; reject, rollback and `previous_challenger` remain the next SM-32 work. +`approve`, `reject` and `rollback`. `previous_challenger` and the matching Bundle +choices/action handoff remain open in SM-32. No new cloud deployment is implied by these library changes. ### Approve an existing candidate without training @@ -127,6 +128,54 @@ a separately reviewed migration; there is no fallback to current training dates. Use the same externally serialized lifecycle writer as training. Bundle widgets and automatic score handoff for operator actions are still pending. +### Reject a candidate or roll back a promotion + +To decline the candidate above, use the same version and evidence digest with +an explicit manual policy. This is an alternative to approving that candidate: + +```python +decision = run_action( + spark, + config, + "reject", + candidate_version=candidate.model_version, + comparison_sha256=comparison_sha256, + expected_champion_version=candidate.comparison.champion_version, + rejection_reason="Business review requires another candidate", +) +``` + +Rejection retains both aliases and the evaluation metrics/status. It records +`approval_status=rejected` and the human-readable `approval_reason` separately. +The reason must be nonempty and at most 256 UTF-8 bytes. A rejected version +cannot be implicitly approved, restaged, renominated or made the first champion. +There is no reopen action in this slice; a later training run creates a new candidate. +Neither rejection nor rollback reads training rows, fits or registers a model. + +To undo an earlier completed promotion, pass that promotion's receipt: + +```python +reversal = run_action( + spark, + config, + "rollback", + promotion_receipt=receipt, # kind="promotion", not first-champion initialization + expected_champion_version=receipt.new_version, +) +``` + +Rollback is available under either promotion policy. It restores the previous +champion only when the saved transition still matches controlled registry state. +A separately verified challenger is retained. Repeating an unchanged rejection +or rollback returns the same committed receipt; incompatible evidence, +conflicting alias state and unresolved writes stop the action. + +All lifecycle actions must use the same externally serialized writer as training. +No additional control table is created. These actions do not launch score or +rewrite its version pin. A later `champion` score follows the restored alias; +a `pinned_version` score continues using its configured version. Rollback does +not undo predictions already written; scoring's model-change policy still applies. + ## What is created `bundle deploy` creates only two jobs and uploads their code: diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index ca3b983f8..3c1572d43 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -287,12 +287,29 @@ before retrying. `@previous_champion` identifies only the latest rollback pointer, not the full history. Concrete versions and promotion/rollback event tags retain that history; predictions should record the resolved model version. Rollback refuses a later promotion, even if it selects the same version. +An unchanged repeat of a completed rollback returns its original reversal +receipt without another alias mutation. The active receipt, previous-champion +pointer and any retained challenger must still be consistent. AliasOutcomeUnknownError includes the event ID for inspection. A prepared tag is not proof that promotion completed. Registry tags are audit records for controlled writers, not tamper-proof authorization tokens. The event tag key uses underscores, and its compact value stays within Unity Catalog's 256-byte tag-value limit. +`skyulf.integrations.mlflow.rejection.reject_candidate(report, reason=..., +expected_champion_version=..., admission=..., tracking_uri=..., registry_uri=...)` +records an explicit operator decision against the exact staged comparison. +It leaves aliases and evaluation metrics/status unchanged, adding +`approval_status=rejected` and `approval_reason` to the candidate version. +It requires no training rows and accepts a failed quality comparison too. +The same unchanged request reuses its committed receipt; a changed reason, +proof, champion, challenger or pending event is refused. Promotion, initialization, +staging and nomination do not implicitly override rejection. A partial metadata +write reports an unknown outcome and keeps the pending event for inspection. +The local workflow wrapper additionally verifies controlled champion state and +requires an explicit manual policy; the low-level registry API retains its +existing legacy-champion compatibility. + The lock protects only participating jobs. A principal with direct registry write permission can bypass it. A crashed Delta admission owner does not expire; clear it only after proving the original job cannot publish. diff --git a/initiatives/spark_and_mlflow/46-sm32-reject-rollback-progress.md b/initiatives/spark_and_mlflow/46-sm32-reject-rollback-progress.md new file mode 100644 index 000000000..bee7b1041 --- /dev/null +++ b/initiatives/spark_and_mlflow/46-sm32-reject-rollback-progress.md @@ -0,0 +1,62 @@ +# SM-32: explicit rejection and repeatable rollback + +Date: 2026-09-25. Status: local library implementation; SM-32 remains ACTIVE. +Baseline: `94b28320` on branch `090`. This change delivers the rejection/rollback slice. +Parent: [selection and approval design](38-model-selection-and-approval-design.md). + +## Delivered behavior + +- `run_action(..., "reject")` takes a concrete candidate version, comparison + digest, expected champion and human-readable reason. Explicit manual policy + is required. It loads the candidate's saved evidence and verifies controlled + champion/challenger state before recording the decision. +- Rejection preserves aliases and evaluation results. Model-version tags + `approval_status=rejected` and `approval_reason` describe the operator's + decision separately from `validation_status` and quality metrics. +- Initialization, promotion, restaging and renomination cannot implicitly + override rejection. A later training run may nominate a new version; this + slice provides no reopen/force-approval action. +- `run_action(..., "rollback")` requires the configured model's completed + promotion receipt and its expected champion. It works under manual or + automatic promotion policy and preserves a separate controlled challenger. +- Unchanged rejection/rollback retries return the original committed receipt. + Changed evidence, inconsistent control state and unresolved writes fail. + Partial decision-tag writes retain a pending event for reconciliation. +- Neither operation fits, registers or uploads a model, reads training rows, + changes a scoring pin, launches score or rewrites earlier predictions. + Existing Core registry/admission/receipt services are reused. + +## Verification + +The combined promotion, manual approval, local workflow/retraining, Bundle +lifecycle/template/notebook and comparison suites passed **145 tests**, with +five expected legacy-selection deprecation warnings, in 120.38 seconds. +Evidence: `rehearsals/sm32-reject-verified.log`. Scoped Ruff lint/format, +full repository ty, strict MkDocs and `git diff --check` also passed. +MkDocs evidence: `rehearsals/sm32-reject-mkdocs-final.log` (exit 0). + +The cases cover both pandas and Polars with actual local MLflow artifacts, +manual rejection of failed-quality candidates, valid first-model rejection, +no implicit reconsideration, controlled-marker disagreement, unchanged +registry version counts, automatic-policy rollback and safe retries. +Failure injection covers partially written decisions and conflicting rollback +control state. The reviewer identified the local rejection wrapper's missing +controlled-champion check; that check and its regression are now included. + +## Boundaries and next work + +The generated Bundle still has the legacy selector and job graph. Do not +migrate only its JSON or treat these library calls as deployed operator tasks. +All lifecycle mutations require the same externally serialized writer as +training; no new job or admission table is created by this slice. The low-level +registry API preserves its existing legacy-champion compatibility; the local +workflow wrapper requires controlled state. + +Next: implement `previous_challenger` replacement history, then expose the +independent Bundle choices and operator inputs through its serialized lifecycle +job, with optional score handoff using the existing score job. Complete local +generation/validation checks before the combined Databricks rehearsal. No +Databricks resources were changed or live jobs run in this continuation. + +Examples: [Bundle user guide](../../docs/user_guide/databricks_bundle.md) and +[registry user guide](../../docs/user_guide/mlflow_registry.md). diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 8309967a8..371533920 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,4 +1,4 @@ -# Session handoff - 2026-09-24 +# Session handoff - 2026-09-25 ## Current priority: SM-30 through SM-43 @@ -18,10 +18,15 @@ the relocated cases plus workflow tests passed 281 tests after type narrowing. Library approve now loads saved candidate evidence and rechecks it without fit or registration; see [manual approval progress](45-sm32-manual-approval-progress.md). Final combined regression suite passed 321 tests; full repository ty and -scoped Ruff passed. This commit includes the SM-32 policy/approval slice and +scoped Ruff passed. Commit `94b28320` includes the SM-32 policy/approval slice and the Core test relocation; the complete SM-32 task remains open. -Next implement reject/rollback, previous_challenger and matching Bundle actions/ -handoff; do not mark SM-32 complete yet. No new Databricks run was made. +The continuation implements library reject/rollback and safe retries; +see [its evidence and limits](46-sm32-reject-rollback-progress.md). +The combined affected suites passed 145 tests, scoped Ruff lint/format and full +repository ty passed, and strict MkDocs built successfully. The progress +report is included alongside this implementation. +Next implement previous_challenger and matching Bundle actions/handoff; +do not mark SM-32 complete yet. No new Databricks run was made. Latest follow-up: Bundle initialization now asks for optional risk_category, PayingRegNo has an explicit policy-compute example, and new receipts use from_version while reading older formats. 44 relevant tests and real CLI diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 0eb0d1906..51b1d0093 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -44,8 +44,10 @@ Commit `fcfcee31` passed 116 tests and all applicable commit hooks. The first SM-32 library policy slice passed 78 tests; see [policy separation progress](43-sm32-policy-separation-progress.md). The [manual approve library action](45-sm32-manual-approval-progress.md) now -rechecks saved candidate evidence without training; reject/rollback, contender -history and Bundle wiring remain open. [36 misplaced Core test files](44-core-test-relocation.md) +rechecks saved candidate evidence without training. Library reject/rollback +and checked retries are implemented in the [current slice](46-sm32-reject-rollback-progress.md); +145 affected tests passed locally; contender history and Bundle wiring remain open. +[36 misplaced Core test files](44-core-test-relocation.md) were relocated and verified before this continuation. See [the implementation evidence](40-sm30-challenger-validation-report.md): 104 tests passed, including real MLflow lifecycles with pandas and Polars. @@ -60,7 +62,7 @@ on an existing candidate without retraining or reuploading the model. | --- | --- | --- | --- | --- | | SM-30 | Challenger nomination and visible evaluation status | Existing SM-22c/29 | DONE | 104 local tests and live run 607409241163605 passed; company tags, both engines, retained contender, replacement, error and rollback verified | | SM-31 | Thin template and reusable workflow/publication services | SM-30 | DONE | 44-line notebook, two Core services, 110 tests, wheel installation/import, strict generation validation and live score run 383572337148835 passed | -| SM-32 | Independent score selection and promotion policy | SM-31 | ACTIVE | Library's four combinations and saved-evidence approve implemented; remaining: reject/rollback via one writer, score handoff without fit, previous_challenger history, matching Bundle choices and live proof | +| SM-32 | Independent score selection and promotion policy | SM-31 | ACTIVE | Library's four combinations and approve/reject/rollback implemented; remaining: previous_challenger history, serialized Bundle operator actions and score handoff without fit, matching choices and live proof | | SM-33 | Validated config, migration and runtime parameters | SM-32 | WAIT | Per-run version/action/evidence inputs; task/column/key setup; migrate old mode and reject config/job-graph disagreement | | SM-34 | Independent score/train schedules and training windows | SM-33 | WAIT | Editable paused score/train cron/timezone, explicit lookback/holdout/label windows; scoring needs no manual dates or retraining | | SM-35 | Multi-metric quality gates and clear thresholds | SM-33 | WAIT | One selection metric plus optional guardrails; task/domain validation, first-model gate, failed-gate explanations and no probability-threshold confusion | diff --git a/skyulf-core/skyulf/integrations/databricks/local_approval.py b/skyulf-core/skyulf/integrations/databricks/local_approval.py index b2c190843..06a5198fd 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_approval.py +++ b/skyulf-core/skyulf/integrations/databricks/local_approval.py @@ -1,4 +1,4 @@ -"""Approve an existing local model using its saved, pinned evaluation evidence. +"""Approve or reject an existing local model using its pinned evaluation evidence. The caller must serialize this operation with every other lifecycle writer. Approval never fits, registers or uploads a model and never changes a scoring pin. @@ -29,6 +29,7 @@ promote_candidate, ) from ..mlflow.registry import _make_client, _require_mlflow, resolve_model +from ..mlflow.rejection import reject_candidate from ..mlflow.validation import ModelComparisonReport from . import local_retraining from .local_retraining import LocalTrainingSpec @@ -102,6 +103,65 @@ def _completed_approval( return receipt +def _validate_candidate_request( + candidate_version: str | None, + comparison_sha256: str | None, + expected_champion_version: str | None, +) -> tuple[str, str]: + """Reject ambiguous candidate and evidence pins before accessing the registry.""" + if not isinstance(candidate_version, str) or not re.fullmatch( + r"[1-9][0-9]*", candidate_version + ): + raise ValueError("Approval requires a concrete candidate_version.") + if not isinstance(comparison_sha256, str) or not re.fullmatch( + r"[a-f0-9]{64}", comparison_sha256 + ): + raise ValueError("Approval requires a comparison_sha256 evidence digest.") + if expected_champion_version is not None and ( + not isinstance(expected_champion_version, str) + or not re.fullmatch(r"[1-9][0-9]*", expected_champion_version) + ): + raise ValueError("Expected champion must be a concrete version or None for bootstrap.") + return candidate_version, comparison_sha256 + + +def reject_local_candidate( + config: dict[str, Any], + *, + candidate_version: str | None, + comparison_sha256: str | None, + expected_champion_version: str | None, + rejection_reason: str, +) -> AliasChangeReceipt: + """Reject saved candidate evidence without fitting, reading rows or changing a scoring pin.""" + if config.get("promotion_policy") != "manual_approval": + raise ValueError("Rejection requires explicit promotion_policy=manual_approval.") + candidate_version, comparison_sha256 = _validate_candidate_request( + candidate_version, comparison_sha256, expected_champion_version + ) + tracking_uri = config.get("tracking_uri", "databricks") + registry_uri = config.get("registry_uri", "databricks-uc") + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + report, _, _ = _load_evidence( + client, config["model_name"], candidate_version, comparison_sha256 + ) + if ( + controlled_champion_version( + config["model_name"], tracking_uri=tracking_uri, registry_uri=registry_uri + ) + != expected_champion_version + ): + raise AliasConflictError("Champion changed before rejection.") + return reject_candidate( + report, + reason=rejection_reason, + expected_champion_version=expected_champion_version, + admission=ExclusiveAliasWriterAdmission(), + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + + def approve_local_candidate( spark: Any, config: dict[str, Any], @@ -119,19 +179,9 @@ def approve_local_candidate( """ if config.get("promotion_policy") != "manual_approval": raise ValueError("Approval requires explicit promotion_policy=manual_approval.") - if not isinstance(candidate_version, str) or not re.fullmatch( - r"[1-9][0-9]*", candidate_version - ): - raise ValueError("Approval requires a concrete candidate_version.") - if not isinstance(comparison_sha256, str) or not re.fullmatch( - r"[a-f0-9]{64}", comparison_sha256 - ): - raise ValueError("Approval requires a comparison_sha256 evidence digest.") - if expected_champion_version is not None and ( - not isinstance(expected_champion_version, str) - or not re.fullmatch(r"[1-9][0-9]*", expected_champion_version) - ): - raise ValueError("Expected champion must be a concrete version or None for bootstrap.") + candidate_version, comparison_sha256 = _validate_candidate_request( + candidate_version, comparison_sha256, expected_champion_version + ) for field in ("max_rows", "max_bytes"): if type(config.get(field)) is not int or config[field] <= 0: raise ValueError(f"Approval {field} must be a positive integer.") diff --git a/skyulf-core/skyulf/integrations/databricks/local_workflow.py b/skyulf-core/skyulf/integrations/databricks/local_workflow.py index acd904dd7..deaed9372 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_workflow.py +++ b/skyulf-core/skyulf/integrations/databricks/local_workflow.py @@ -19,11 +19,12 @@ controlled_champion_version, initialize_champion, promote_candidate, + rollback_promotion, stage_challenger, ) from ..mlflow.registry import RegistryModelNotFoundError, resolve_model from .admission import SingleWriterAdmission -from .local_approval import approve_local_candidate +from .local_approval import approve_local_candidate, reject_local_candidate from .local_incremental import run_incremental_local_batch from .local_retraining import ( LocalTrainingSpec, @@ -292,11 +293,37 @@ def run_action( candidate_version: str | None = None, comparison_sha256: str | None = None, expected_champion_version: str | None = None, + rejection_reason: str = "", + promotion_receipt: AliasChangeReceipt | None = None, ) -> Any: - """Delegate training or scoring to Skyulf's existing services.""" + """Delegate training, scoring and explicit lifecycle actions to existing Core services.""" tracking_uri = config.get("tracking_uri", "databricks") registry_uri = config.get("registry_uri", "databricks-uc") selection, policy = _workflow_policies(config) + if action == "rollback": + if ( + not isinstance(promotion_receipt, AliasChangeReceipt) + or promotion_receipt.model_name != config["model_name"] + or not isinstance(expected_champion_version, str) + ): + raise ValueError( + "Rollback needs a receipt for the configured model and expected champion." + ) + return rollback_promotion( + promotion_receipt, + expected_current_version=expected_champion_version, + admission=ExclusiveAliasWriterAdmission(), + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + if action == "reject": + return reject_local_candidate( + config, + candidate_version=candidate_version, + comparison_sha256=comparison_sha256, + expected_champion_version=expected_champion_version, + rejection_reason=rejection_reason, + ) if action == "approve": if policy != "manual_approval" or "promotion_policy" not in config: raise ValueError("Approval requires explicit promotion_policy=manual_approval.") diff --git a/skyulf-core/skyulf/integrations/mlflow/challenger.py b/skyulf-core/skyulf/integrations/mlflow/challenger.py index 54e349f06..ace43f148 100644 --- a/skyulf-core/skyulf/integrations/mlflow/challenger.py +++ b/skyulf-core/skyulf/integrations/mlflow/challenger.py @@ -9,6 +9,7 @@ _active_marker, _admission, _assert_no_pending, + _assert_not_rejected, _checked_challenger_event, _commit_change, _read_optional_alias, @@ -57,7 +58,7 @@ def registered(self, candidate: ResolvedModel) -> None: raise ValueError("Candidate artifact digest changed before nomination.") client = _make_client(_require_mlflow(), self.tracking_uri, self.registry_uri) with self.admission.hold(alias_resource_id(candidate.name)): - _assert_no_pending(client, candidate.name) + _assert_not_rejected(client, candidate.name, candidate.version) champion = _read_optional_alias(client, candidate.name, "champion") if champion != self.expected_champion_version: raise AliasConflictError("Champion changed before challenger nomination.") diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py index 3035c65fc..d047036a7 100644 --- a/skyulf-core/skyulf/integrations/mlflow/promotion.py +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -183,6 +183,13 @@ def _assert_no_pending(client: Any, name: str) -> None: raise AliasConflictError("A pending alias event requires reconciliation.") +def _assert_not_rejected(client: Any, name: str, version: str) -> None: + """Refuse an implicit override of an operator's persisted rejection.""" + _assert_no_pending(client, name) + if (client.get_model_version(name, version).tags or {}).get("approval_status") == "rejected": + raise AliasConflictError("Candidate was manually rejected; implicit override is forbidden.") + + def controlled_champion_version( model_name: str, *, @@ -503,6 +510,7 @@ def initialize_champion( digest = hashlib.sha256(json.dumps(asdict(fresh), sort_keys=True).encode()).hexdigest() client = _make_client(_require_mlflow(), tracking_uri, registry_uri) with admission.hold(alias_resource_id(report.model_name)): + _assert_not_rejected(client, report.model_name, report.candidate_version) if _read_optional_alias(client, report.model_name, _ALIAS) is not None: raise AliasConflictError("Champion alias already exists.") if (client.get_registered_model(report.model_name).tags or {}).get(_ACTIVE_TAG): @@ -558,6 +566,7 @@ def stage_challenger( ) client = _make_client(_require_mlflow(), tracking_uri, registry_uri) with admission.hold(alias_resource_id(report.model_name)): + _assert_not_rejected(client, report.model_name, report.candidate_version) if _read_optional_alias(client, report.model_name, _ALIAS) != expected_champion_version: raise AliasConflictError("Champion alias differs from expected version.") existing = _read_optional_alias(client, report.model_name, _CHALLENGER) @@ -628,7 +637,7 @@ def _checked_challenger_event(client: Any, name: str, version: str) -> dict[str, or not isinstance(event, dict) or ( event.get("s") != "committed" - or event.get("k") not in {"nomination", "challenger", "evaluation_error"} + or event.get("k") not in {"nomination", "challenger", "evaluation_error", "rejection"} ) ): raise AliasConflictError("Challenger lacks a committed lifecycle receipt.") @@ -639,6 +648,7 @@ def _verify_staged_challenger( client: Any, report: ModelComparisonReport, comparison_sha256: str ) -> str: """Require a committed staging event for this exact comparison.""" + _assert_not_rejected(client, report.model_name, report.candidate_version) if _read_optional_alias(client, report.model_name, _CHALLENGER) != report.candidate_version: raise AliasConflictError("Challenger alias differs from candidate version.") event_id = _active_marker(client, report.model_name, report.candidate_version, _CHALLENGER) @@ -724,7 +734,7 @@ def rollback_promotion( tracking_uri: str | None = None, registry_uri: str | None = None, ) -> AliasChangeReceipt: - """Restore the prior version only while the matching promotion remains active.""" + """Restore the matching promotion, or return its verified still-current rollback receipt.""" if not isinstance(receipt, AliasChangeReceipt) or receipt.kind != "promotion": raise ValueError("Rollback requires a completed promotion receipt.") if receipt.prior_version is None: @@ -735,12 +745,41 @@ def rollback_promotion( mlflow = _require_mlflow() client = _make_client(mlflow, tracking_uri, registry_uri) with admission.hold(alias_resource_id(receipt.model_name)): + _assert_no_pending(client, receipt.model_name) + legacy = _verify_original_receipt(client, receipt) current = _read_alias(client, receipt.model_name) + if current == receipt.prior_version: + event_id = _active_marker(client, receipt.model_name, current) + if event_id is None: + raise AliasConflictError("Rollback replay lacks a controlled receipt.") + reversal = AliasChangeReceipt( + event_id=event_id, + kind="rollback", + model_name=receipt.model_name, + alias=_ALIAS, + prior_version=receipt.new_version, + new_version=receipt.prior_version, + comparison_sha256=receipt.comparison_sha256, + parent_event_id=receipt.event_id, + previous_champion_version=receipt.previous_champion_version, + ) + _verify_original_receipt(client, reversal) + if ( + not legacy + and _read_optional_alias(client, receipt.model_name, _PREVIOUS) + != receipt.previous_champion_version + ): + raise AliasConflictError("Previous champion changed after rollback.") + challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) + if challenger is not None: + _checked_challenger_event(client, receipt.model_name, challenger) + if challenger == current: + raise AliasConflictError("Challenger conflicts with the restored champion.") + return reversal if current != expected_current_version: raise AliasConflictError("Champion alias differs from expected current version.") if _active_marker(client, receipt.model_name, current) != receipt.event_id: raise AliasConflictError("A newer promotion superseded this rollback receipt.") - legacy = _verify_original_receipt(client, receipt) challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) if challenger is not None: _checked_challenger_event(client, receipt.model_name, challenger) diff --git a/skyulf-core/skyulf/integrations/mlflow/rejection.py b/skyulf-core/skyulf/integrations/mlflow/rejection.py new file mode 100644 index 000000000..f3f4183b7 --- /dev/null +++ b/skyulf-core/skyulf/integrations/mlflow/rejection.py @@ -0,0 +1,110 @@ +"""Explicit operator rejection of an evaluated, registered challenger.""" + +import hashlib +import json +from dataclasses import asdict +from uuid import uuid4 + +from .promotion import ( + AliasAdmission, + AliasChangeReceipt, + AliasConflictError, + _active_marker, + _admission, + _assert_no_pending, + _checked_challenger_event, + _commit_change, + _read_optional_alias, + _verify_original_receipt, + _verify_staged_challenger, + alias_resource_id, +) +from .registry import _make_client, _require_mlflow +from .validation import ModelComparisonReport + + +def reject_candidate( + report: ModelComparisonReport, + *, + reason: str, + expected_champion_version: str | None, + admission: AliasAdmission, + tracking_uri: str | None = None, + registry_uri: str | None = None, +) -> AliasChangeReceipt: + """Record a manual decision without replacing aliases or altering evaluation metrics. + + Rejection requires the exact controlled staging evidence. It does not + reread data or require a passing quality gate. A repeated request reuses + its receipt only while champion, challenger, reason and proof still match. + """ + if not isinstance(reason, str) or not reason.strip() or len(reason.encode("utf-8")) > 256: + raise ValueError("Rejection reason must be nonempty text of at most 256 UTF-8 bytes.") + if not isinstance(report, ModelComparisonReport): + raise TypeError("Rejection requires a ModelComparisonReport.") + if expected_champion_version != report.champion_version: + raise ValueError("Expected champion must match the rejected comparison.") + _admission(admission, registry_uri) + digest = hashlib.sha256( + json.dumps(asdict(report), sort_keys=True, allow_nan=False).encode() + ).hexdigest() + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + name = report.model_name + version = report.candidate_version + with admission.hold(alias_resource_id(name)): + _assert_no_pending(client, name) + if _read_optional_alias(client, name, "champion") != expected_champion_version: + raise AliasConflictError("Champion changed before rejection.") + if ( + _read_optional_alias(client, name, "challenger") != version + or version == expected_champion_version + ): + raise AliasConflictError("Challenger changed before rejection.") + event = _checked_challenger_event(client, name, version) + if event["k"] == "rejection": + tags = client.get_model_version(name, version).tags or {} + if ( + event.get("h") != digest + or tags.get("approval_status") != "rejected" + or tags.get("approval_reason") != reason + ): + raise AliasConflictError( + "Rejection proof, status or reason differs from the recorded decision." + ) + event_id = _active_marker(client, name, version, "challenger") + if event_id is None: + raise AliasConflictError("Rejected challenger lacks an active decision receipt.") + receipt = AliasChangeReceipt( + event_id=event_id, + kind="rejection", + model_name=name, + alias="challenger", + prior_version=version, + new_version=version, + comparison_sha256=digest, + parent_event_id=event.get("e"), + ) + _verify_original_receipt(client, receipt) + return receipt + stage_event = _verify_staged_challenger(client, report, digest) + receipt = AliasChangeReceipt( + event_id=uuid4().hex, + kind="rejection", + model_name=name, + alias="challenger", + prior_version=version, + new_version=version, + comparison_sha256=digest, + parent_event_id=stage_event, + ) + _commit_change( + client, + receipt, + [], + version_tags={ + "approval_status": "rejected", + "approval_reason": reason, + "promotion_status": "not_promoted", + }, + ) + return receipt diff --git a/skyulf-core/tests/integrations/test_databricks_local_approval.py b/skyulf-core/tests/integrations/test_databricks_local_approval.py index 3e0b93d0b..44203351f 100644 --- a/skyulf-core/tests/integrations/test_databricks_local_approval.py +++ b/skyulf-core/tests/integrations/test_databricks_local_approval.py @@ -148,6 +148,77 @@ def approve(candidate, expected, **changes): approve(tied, "2") assert str(client.get_registered_model(config["model_name"]).aliases["champion"]) == "2" + tied_digest = hashlib.sha256( + json.dumps(asdict(tied.comparison), sort_keys=True, allow_nan=False).encode() + ).hexdigest() + with monkeypatch.context() as no_training: + no_training.setattr( + local_workflow, "train_local_candidate", Mock(side_effect=AssertionError("fit")) + ) + no_training.setattr( + local_retraining, + "read_training_snapshot", + Mock(side_effect=AssertionError("data read")), + ) + marker = client.get_registered_model(config["model_name"]).tags["champion_current_event"] + client.set_registered_model_tag( + config["model_name"], + "champion_current_event", + json.dumps({"event_id": promoted.event_id, "version": "1"}), + ) + with pytest.raises(AliasConflictError, match="receipt disagrees"): + local_workflow.run_action( + None, + config, + "reject", + candidate_version=tied.model_version, + comparison_sha256=tied_digest, + expected_champion_version="2", + rejection_reason="Retain the current production model", + ) + assert ( + "approval_status" + not in client.get_model_version(config["model_name"], tied.model_version).tags + ) + client.set_registered_model_tag(config["model_name"], "champion_current_event", marker) + rejected = local_workflow.run_action( + None, + config, + "reject", + candidate_version=tied.model_version, + comparison_sha256=tied_digest, + expected_champion_version="2", + rejection_reason="Retain the current production model", + ) + assert ( + local_workflow.run_action( + None, + config, + "reject", + candidate_version=tied.model_version, + comparison_sha256=tied_digest, + expected_champion_version="2", + rejection_reason="Retain the current production model", + ) + == rejected + ) + with pytest.raises(AliasConflictError, match="rejected"): + approve(tied, "2") + config["promotion_policy"] = "automatic" + rollback = local_workflow.run_action( + None, config, "rollback", promotion_receipt=promoted, expected_champion_version="2" + ) + assert rollback.kind == "rollback" and rollback.new_version == "1" + assert ( + local_workflow.run_action( + None, config, "rollback", promotion_receipt=promoted, expected_champion_version="2" + ) + == rollback + ) + assert len(client.search_model_versions("name = 'approval_model'")) == 3 + assert str(client.get_model_version_by_alias(config["model_name"], "challenger").version) == "3" + assert config["model_version"] == "1" + @pytest.mark.parametrize("selection", ["pinned_version", "champion"]) def test_approval_refuses_automatic_policy_before_registry_access(selection): diff --git a/skyulf-core/tests/integrations/test_mlflow_promotion.py b/skyulf-core/tests/integrations/test_mlflow_promotion.py index 1b98becd3..8ecf66bb8 100644 --- a/skyulf-core/tests/integrations/test_mlflow_promotion.py +++ b/skyulf-core/tests/integrations/test_mlflow_promotion.py @@ -118,6 +118,172 @@ def _stage(case, **changes): return stage_challenger(selected, heldout, **options) +def _reject(case, reason="Business review declined deployment", **changes): + """Reject the staged comparison through the same explicit alias admission.""" + from skyulf.integrations.mlflow.rejection import reject_candidate + + _, uri, _, _, report, admission = case + options = { + "expected_champion_version": report.champion_version, + "admission": admission, + "tracking_uri": uri, + "registry_uri": uri, + } + options.update(changes) + return reject_candidate(report, reason=reason, **options) + + +def test_manual_rejection_retains_aliases_and_cannot_be_erased_by_recheck(case): + """An operator rejection must survive quality rechecks without changing objective metrics.""" + client, _, name, _, _, _ = case + _stage(case) + before = client.get_registered_model(name).aliases + receipt = _reject(case) + assert receipt.kind == "rejection" + assert client.get_registered_model(name).aliases == before + tags = client.get_model_version(name, "2").tags + assert tags["validation_status"] == "passed" + assert tags["approval_status"] == "rejected" + assert tags["approval_reason"] == "Business review declined deployment" + assert _reject(case) == receipt + with pytest.raises(AliasConflictError, match="reason|decision"): + _reject(case, reason="Different decision") + with pytest.raises(AliasConflictError, match="rejected"): + _promote(case) + with pytest.raises(AliasConflictError, match="rejected"): + _stage(case, expected_challenger_version="2") + assert client.get_registered_model(name).aliases == before + + +def test_rejected_first_candidate_cannot_initialize_or_renominate(case): + """Bootstrap and nomination must not bypass a recorded operator rejection.""" + from skyulf.integrations.mlflow.challenger import ChallengerLifecycle + from skyulf.integrations.mlflow.promotion import initialize_champion + from skyulf.integrations.mlflow.rejection import reject_candidate + + client, uri, name, heldout, _, admission = case + client.delete_registered_model_alias(name, "champion") + candidate = resolve_model(name, version="2", tracking_uri=uri, registry_uri=uri) + evaluation: dict[str, Any] = { + "target_column": "target", + "max_rows": 10, + "max_bytes": 10_000, + "tracking_uri": uri, + "registry_uri": uri, + } + report = compare_registered_local_models( + candidate, + None, + heldout, + dataset_id="labels@5/heldout", + metric="heldout_mse", + min_improvement=1.0, + quality_threshold=1.0, + **evaluation, + ) + _stage(case, report=report, expected_champion_version=None) + reject_candidate( + report, + reason="Review declined first deployment", + expected_champion_version=None, + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + with pytest.raises(AliasConflictError, match="rejected"): + initialize_champion(report, heldout, admission=admission, **evaluation) + lifecycle = ChallengerLifecycle( + name, + expected_champion_version=None, + admission=admission, + tracking_uri=uri, + registry_uri=uri, + ) + with pytest.raises(AliasConflictError, match="rejected"): + lifecycle.registered(candidate) + aliases = client.get_registered_model(name).aliases + assert set(aliases) == {"challenger"} + assert str(aliases["challenger"]) == "2" + + +@pytest.mark.parametrize("reason", ["", " ", "a" * 257, "\u00fc" * 129]) +def test_invalid_rejection_reason_cannot_write_a_decision(case, reason): + """Empty and oversized UTF-8 reasons must fail before changing model metadata.""" + client, _, name, _, _, _ = case + _stage(case) + tags = client.get_model_version(name, "2").tags + with pytest.raises(ValueError, match="reason"): + _reject(case, reason=reason) + assert client.get_model_version(name, "2").tags == tags + + +def test_partial_rejection_retains_pending_event_and_blocks_retry(case, monkeypatch): + """A lost decision-tag write cannot be treated as a completed or safe-to-repeat rejection.""" + client, _, name, _, _, _ = case + _stage(case) + original = mlflow.MlflowClient.set_model_version_tag + + def fail_reason(self, model_name, version, key, value): + """Fail after status was written but before its human-readable reason.""" + if key == "approval_reason": + raise RuntimeError("lost decision response") + return original(self, model_name, version, key, value) + + monkeypatch.setattr(mlflow.MlflowClient, "set_model_version_tag", fail_reason) + with pytest.raises(AliasOutcomeUnknownError): + _reject(case) + with pytest.raises(AliasConflictError, match="pending"): + _reject(case) + assert client.get_registered_model(name).tags["pending_alias_event"] + + +def test_rollback_retry_returns_original_receipt_without_alias_writes(case, monkeypatch): + """A repeated logical rollback must be idempotent even though its expected source moved.""" + client, uri, name, _, _, admission = case + _stage(case) + receipt = _promote(case) + options: dict[str, Any] = { + "expected_current_version": "2", + "admission": admission, + "tracking_uri": uri, + "registry_uri": uri, + } + reversal = rollback_promotion(receipt, **options) + before = client.get_registered_model(name).tags + + def unexpected_write(*args, **kwargs): + """Replaying a committed rollback may read state but must not mutate it.""" + raise AssertionError("rollback replay attempted a write") + + monkeypatch.setattr(mlflow.MlflowClient, "set_registered_model_alias", unexpected_write) + assert rollback_promotion(receipt, **options) == reversal + assert client.get_registered_model(name).tags == before + + +@pytest.mark.parametrize("changed", ["pending", "previous", "receipt"]) +def test_rollback_retry_refuses_changed_control_state(case, changed): + """A completed rollback is not permission to ignore later corruption or pending writes.""" + client, uri, name, _, _, admission = case + _stage(case) + receipt = _promote(case) + options: dict[str, Any] = { + "expected_current_version": "2", + "admission": admission, + "tracking_uri": uri, + "registry_uri": uri, + } + reversal = rollback_promotion(receipt, **options) + if changed == "pending": + client.set_registered_model_tag(name, "pending_alias_event", "uncertain") + elif changed == "previous": + client.set_registered_model_alias(name, "previous_champion", "2") + else: + client.set_model_version_tag(name, "1", f"promotion_{reversal.event_id}", "{}") + with pytest.raises((AliasConflictError, ValueError)): + rollback_promotion(receipt, **options) + assert str(client.get_model_version_by_alias(name, "champion").version) == "1" + + def test_stage_challenger_requires_validation_and_preserves_champion(case) -> None: """Staging verifies evidence while leaving the production version unchanged.""" client, _, name, _, report, _ = case @@ -621,7 +787,7 @@ def test_rollback_rejects_newer_alias_state(case) -> None: _stage(case) receipt = _promote(case) client.set_registered_model_alias(name, "champion", "1") - with pytest.raises(AliasConflictError, match="expected"): + with pytest.raises(AliasConflictError, match="receipt disagrees"): rollback_promotion( receipt, expected_current_version="2", From 5ba388ec13ce31b9db10979543d49dae6676446b Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Fri, 25 Sep 2026 12:32:25 +0300 Subject: [PATCH 59/85] feat: complete bundle lifecycle controls and readable operator reports Signed-off-by: flyingriverhorse --- changelog/0.9.x.md | 23 +- docs/user_guide/databricks_bundle.md | 149 +++++-- .../databricks_bundle_walkthrough.md | 408 ++++++++++++++++++ docs/user_guide/mlflow_registry.md | 27 +- .../38-model-selection-and-approval-design.md | 8 +- .../47-sm32-challenger-history-progress.md | 54 +++ .../48-sm32-bundle-actions-plan.md | 58 +++ .../49-sm32-bundle-actions-validation.md | 86 ++++ .../50-sm32-live-rehearsal-plan.md | 31 ++ .../51-sm32-live-validation-report.md | 161 +++++++ .../52-sm32-operator-output-and-evidence.md | 111 +++++ initiatives/spark_and_mlflow/HANDOFF.md | 65 ++- initiatives/spark_and_mlflow/OPEN_QUEUE.md | 23 +- mkdocs.yml | 7 + .../integrations/databricks/job_output.py | 147 +++++++ .../integrations/databricks/job_runtime.py | 246 +++++++++++ .../integrations/databricks/local_approval.py | 45 ++ .../skyulf/integrations/mlflow/promotion.py | 108 +++++ .../databricks_template_schema.json | 36 +- .../examples/paying-reg-no-init.example.json | 4 +- .../examples/policy-init.example.json | 4 +- .../examples/serverless-init.example.json | 4 +- .../template/{{.project_name}}/README.md.tmpl | 109 +++-- .../config/workflow.json.tmpl | 6 +- .../{{.project_name}}/databricks.yml.tmpl | 1 + .../resources/workflow.jobs.yml.tmpl | 32 +- .../template/{{.project_name}}/src/score.py | 18 + .../{{.project_name}}/src/workflow.py | 48 +-- .../test_databricks_bundle_generation.py | 115 +++++ .../test_databricks_bundle_lifecycle.py | 20 +- .../test_databricks_bundle_notebook.py | 116 ++++- .../test_databricks_bundle_template.py | 16 +- .../test_databricks_job_output.py | 147 +++++++ .../test_databricks_job_runtime.py | 238 ++++++++++ .../test_databricks_local_approval.py | 66 ++- .../integrations/test_mlflow_promotion.py | 189 ++++++++ 36 files changed, 2708 insertions(+), 218 deletions(-) create mode 100644 docs/user_guide/databricks_bundle_walkthrough.md create mode 100644 initiatives/spark_and_mlflow/47-sm32-challenger-history-progress.md create mode 100644 initiatives/spark_and_mlflow/48-sm32-bundle-actions-plan.md create mode 100644 initiatives/spark_and_mlflow/49-sm32-bundle-actions-validation.md create mode 100644 initiatives/spark_and_mlflow/50-sm32-live-rehearsal-plan.md create mode 100644 initiatives/spark_and_mlflow/51-sm32-live-validation-report.md create mode 100644 initiatives/spark_and_mlflow/52-sm32-operator-output-and-evidence.md create mode 100644 skyulf-core/skyulf/integrations/databricks/job_output.py create mode 100644 skyulf-core/skyulf/integrations/databricks/job_runtime.py create mode 100644 skyulf-core/templates/databricks/template/{{.project_name}}/src/score.py create mode 100644 skyulf-core/tests/integrations/test_databricks_bundle_generation.py create mode 100644 skyulf-core/tests/integrations/test_databricks_job_output.py create mode 100644 skyulf-core/tests/integrations/test_databricks_job_runtime.py diff --git a/changelog/0.9.x.md b/changelog/0.9.x.md index de8b6ecc9..9ae6d6f14 100644 --- a/changelog/0.9.x.md +++ b/changelog/0.9.x.md @@ -10,21 +10,38 @@ execution, MLflow registry and Databricks delivery remain under development. ### Changed +- Bundle notebooks show shared readable result summaries, metric comparisons + and next-action tables while preserving their JSON API result. Approval and + rejection resolve full comparison proofs from committed registry receipts, + removing manual hash copying without weakening Core evidence checks. +- Generated Bundles expose independent score selection, promotion policy and + optional score handoff. The existing serialized lifecycle job accepts + approve/reject/rollback with explicit evidence, returns copyable next-action + inputs and conditionally calls the score job. Two fixed-role entrypoints + delegate to a shared Core adapter; no third job or control table is added. +- Score notebook entrypoints ignore lifecycle evidence automatically forwarded + by Databricks Run Job tasks. Fixed score dispatch and explicit role/action + override guards remain enforced. An operator walkthrough documents policies, + approval, rejection, rollback and prediction behavior with Mermaid diagrams. +- Model lifecycle retains displaced contenders as `previous_challenger`, + without rotating history on repeated nomination. Promotion preserves it; + rollback or renomination clears a history pointer that becomes a current + role. Checked event records and pending-write protection cover history too. - Local workflow adds explicit reject and rollback actions without retraining. Rejection preserves evaluation results and blocks implicit reconsideration; unchanged retries reuse checked rejection/rollback receipts. Scoring pins - remain unchanged; Bundle operator wiring and live validation are pending. + remain unchanged; personal serverless Bundle verification passed. - Core-owned tests now live under `skyulf-core/tests`, including the Bundle template/notebook/lifecycle tests. Backend and frontend contract tests retain their own scope; moved tests also participate in Core's type checks. - Local workflow approval loads an existing candidate's saved comparison and training snapshot, rechecks quality and returns a checked promotion receipt without training or registering another model. Repeated current approvals - return the original receipt; Bundle operator wiring remains pending. + return the original receipt; live Bundle approval/rejection/rollback passed. - Core's local workflow accepts independent scoring selection and promotion policies. All four combinations preserve scoring pins and promotion gates; partial/mixed configurations fail early. Legacy modes retain their behavior. - Bundle prompts and operator-action handoff are pending in SM-32. + Bundle prompts and operator-action handoff use these independent policies. - Bundle initialization accepts an optional business risk label and documents the PayingRegNo cost-tag choice. New lifecycle receipts use from_version; older from and compact receipts remain readable. diff --git a/docs/user_guide/databricks_bundle.md b/docs/user_guide/databricks_bundle.md index a4489d549..1acb5a512 100644 --- a/docs/user_guide/databricks_bundle.md +++ b/docs/user_guide/databricks_bundle.md @@ -1,5 +1,8 @@ # Local-engine Databricks Bundle +For job-screen instructions and lifecycle diagrams, use the +[operator walkthrough](databricks_bundle_walkthrough.md). + The custom Skyulf template generates one editable Bundle with `dev`, `test`, `syst` and `prod` targets. It fits and predicts with pandas or Polars. Spark reads bounded Unity Catalog Delta rows and publishes predictions; local @@ -12,7 +15,8 @@ databricks bundle init skyulf-core/templates/databricks --output-dir ./generated ``` The short path asks for project name, engine, one existing source row-key -column, model-change and model-selection modes, optional retraining mode and cron, serverless +column, model-change mode, independent scoring and promotion policies, optional +score handoff, retraining mode and cron, serverless or policy-backed job compute and the existing `dev` catalog/schema. Serverless is the default. Reviewable noninteractive examples are in `skyulf-core/templates/databricks/examples/`. The generated @@ -39,21 +43,21 @@ versions; it does not change promotion gates or relabel existing versions. ## Where the workflow lives -The generated `src/workflow.py` reads job widgets and JSON, calls the installed -library, and serializes its result. Reusable behavior lives in -`skyulf.integrations.databricks.local_workflow`: `resolve_target_config` binds -target names and `run_action` executes train, train_monthly or score. -`prediction_output` validates and creates output tables and safely switches -full-rebuild views. Both reuse the existing training, inference and registry -services. Importing them does not create a Spark session or cloud resource. +The generated `src/workflow.py` and `src/score.py` are small entrypoints with +fixed lifecycle and score roles. The installed `job_runtime` adapter reads +widgets/configuration, validates operator inputs and publishes task values. +It delegates target resolution and execution to `local_workflow`; training, +evaluation, registry changes and prediction use existing Core services. +`prediction_output` creates output tables and safely switches full-rebuild +views. Imports do not create a Spark session or cloud resource. Edit the business pipeline in `config/workflow.json`. Model/preprocessing choices remain project configuration; common workflow fixes ship in the Skyulf wheel instead of requiring edits to every generated notebook. -### Independent library policies (SM-32 in progress) +### Independent scoring and promotion policies -Direct `run_action` callers can now separate these two decisions: +Generated Bundles and direct `run_action` callers separate these decisions: | `score_model_selection` | `promotion_policy` | Behavior | | --- | --- | --- | @@ -75,14 +79,51 @@ Legacy `auto_champion` retains champion/automatic behavior, and legacy Automatic promotion still requires `quality_threshold`, including when scoring is pinned. Scoring never updates the caller's configured version. -This first slice is available at the library boundary. The generated Bundle -still uses its existing `model_selection_mode` and job graph. Do not migrate -only its JSON: the lifecycle actions and matching job handoff must be delivered -together. `manual_approval` currently means no automatic promotion; approve, -reject and rollback are separate operator actions. The library now supports -`approve`, `reject` and `rollback`. `previous_challenger` and the matching Bundle -choices/action handoff remain open in SM-32. -No new cloud deployment is implied by these library changes. +New Bundles require both policy fields and `score_handoff`. Migrate an older +project's configuration, both notebook entrypoints and job graph together; +changing only JSON is insufficient. Core direct callers retain the legacy +compatibility path described above. Generated projects use the new policies. + +### Operator actions through Run now + +The existing `train` job is the serialized lifecycle writer. In **Run now with +different parameters**, choose `lifecycle_action`: + +| Action | Required job parameters | +| --- | --- | +| `train` / `train_monthly` | No operator evidence; leave other parameters empty | +| `approve` | `candidate_version`, `comparison_sha256`, `expected_champion_version` | +| `reject` | Same as approve, plus `rejection_reason` | +| `rollback` | `promotion_receipt_json`, `expected_champion_version` | + +Manual training returns copyable `next_actions.approve` and `next_actions.reject` +fields. Review the comparison and copy its exact values; add a reason for +rejection. `expected_champion_version=none` explicitly selects first-champion +initialization; an empty value fails. Configure the metric and absolute quality +threshold **before training** so saved evidence matches the approval policy. +A completed promotion returns `next_actions.rollback`, including its complete +receipt JSON. Copy that receipt rather than reconstructing it from alias names. +These operator actions reuse the existing candidate; they do not fit a model. + +`score_handoff=after_alias_change` requests the existing score job after a +successful initialization, promotion or rollback. `disabled` leaves scoring to +an explicit score run or its schedule. Rejection and training without a champion +transition never trigger score. Handoff preserves the score selector: a pinned +scorer still uses its configured version even after champion changes. + +There are still two jobs. The lifecycle job contains three tasks: execute the +action, check `score_requested`, and conditionally call the score job. Both jobs +queue runs with `max_concurrent_runs: 1`. Score's fixed notebook role ignores inherited +lifecycle parameters and cannot dispatch alias actions; this is input isolation, not a replacement for exclusive +registry write permissions. A failed/uncertain alias action never publishes a +successful score request. If the alias change succeeded but score failed, retry +score directly; no retraining is needed. + +Local tests and strict generated-project validation cover this wiring. The +personal serverless SM-32 rehearsal verified manual approval, rejection, +rollback/retry, automatic promotion, score handoff and pinned selection. +The score entrypoint filters inherited parent-job evidence before dispatching +score. Company targets and production identities remain separate acceptance work. ### Approve an existing candidate without training @@ -125,8 +166,8 @@ receipt; changed champion, pending writes or incompatible evidence fail. Training runs created before the saved specification was introduced cannot use this action without explicitly supplying that missing provenance through a separately reviewed migration; there is no fallback to current training dates. -Use the same externally serialized lifecycle writer as training. Bundle widgets -and automatic score handoff for operator actions are still pending. +Use the same externally serialized lifecycle writer as training. The Bundle +operator parameters above provide that path with optional score handoff. ### Reject a candidate or roll back a promotion @@ -171,18 +212,42 @@ or rollback returns the same committed receipt; incompatible evidence, conflicting alias state and unresolved writes stop the action. All lifecycle actions must use the same externally serialized writer as training. -No additional control table is created. These actions do not launch score or -rewrite its version pin. A later `champion` score follows the restored alias; +No additional control table is created. Direct `run_action` calls do not launch +score or rewrite its version pin; the Bundle adapter can request score afterward. A later `champion` score follows the restored alias; a `pinned_version` score continues using its configured version. Rollback does not undo predictions already written; scoring's model-change policy still applies. +### Recent challenger history + +The Core lifecycle keeps the last displaced contender as `previous_challenger`: + +| Action | Champion | Challenger | Previous challenger | +| --- | --- | --- | --- | +| Starting state | v2 | v3 | unset | +| Nominate v4 | v2 | v4 | v3 | +| Repeat nomination of v4 | v2 | v4 | v3 | +| Promote v4 | v4 | unset | v3 | + +Only replacing an existing contender rotates this pointer. Evaluation and +promotion retain it, and promotion still puts the old champion in +`previous_champion`. If the historical version becomes champion through +rollback, or becomes challenger again, its history alias is cleared. The +version and its earlier event records remain available. + +This alias is neither a complete history nor a scoring fallback. It creates +no table or job. History changes share the lifecycle's pending-event checks +and writer ownership; manual alias/receipt disagreement stops further actions, +including retries. Partial writes require reconciliation before proceeding. +This history extension passed local and personal-serverless Bundle verification, +including replacement, explicit rejection and rollback while retaining a contender. + ## What is created `bundle deploy` creates only two jobs and uploads their code: | Job | Purpose | UC objects created when run | | --- | --- | --- | -| `train` | Fit one candidate and log held-out metrics | One registered model/version | +| `train` | Train/evaluate a candidate or execute approve/reject/rollback | Model/version only for training | | `score` | Score initial and later CDF rows | Prediction output and rows | The default project has no schedule. Choosing `monthly_paused` at initialization @@ -190,21 +255,22 @@ adds a paused schedule to the existing `train` job, without adding a third job or running it at deployment. The Quartz cron and timezone are selected at initialization and remain editable Bundle variables. No endpoint or Unity Catalog table is created by deployment alone. -`pinned_version` keeps manual model selection. `auto_champion` uses the same -train job to compare candidate and champion on a pinned temporal holdout. The +`promotion_policy=automatic` uses the same train job to compare candidate and +champion on a pinned temporal holdout, independently of the score selector. The selected `metric`, `min_improvement`, and absolute `quality_threshold` stay editable in `config/workflow.json`. A first champion requires a numeric absolute threshold because no prior version exists for comparison. Later versions must pass that threshold and improve on champion by the chosen minimum. A passing candidate is staged and promoted through checked registry receipts; an ineligible candidate leaves champion unchanged. The train job -then calls the existing score job. No third job or control table is added. +calls the existing score job only after a champion transition when handoff is +enabled. No third job or control table is added. In both modes, registration nominates `@challenger` before comparison. A tied or worse candidate retains that alias with `validation_status=rejected` and a reason; comparison errors retain it with `validation_status=error`. New contenders replace the pointer without deleting earlier version evidence. -Manual mode records these results without promotion or changing pinned scoring. +Manual approval records these results without automatically promoting the candidate. Training resolves the current champion; a stale explicit `champion_version` fails before fit. Generic Core training remains alias-free unless a caller supplies the explicit `on_registered` lifecycle callback. @@ -224,8 +290,9 @@ identifies the version previously held by the affected alias, not necessarily the previous champion. These are audit records, not settings to edit. Earlier compact receipts remain supported. -In automatic mode, score resolves `@champion` once to a concrete version per -run. In both modes, only the serialized train job identity may write this +With `score_model_selection=champion`, score resolves the alias once to a +concrete version per run, under either promotion policy. Only the serialized +train job identity may write this model's aliases; other alias-write grants must be removed before training. Alias promotion and Delta scoring are separate transactions. If scoring fails after promotion, the last successful prediction output remains and the score @@ -233,14 +300,16 @@ job must be retried. Unknown alias outcomes need receipt reconciliation. Skyulf marks an alias transition as pending before writing it; automatic training and scoring stop until that pending event is reconciled. An existing champion alias set outside this controlled lifecycle also needs reconciliation -before automatic mode can use it. +before controlled champion scoring or promotion can use it. For example, a regression project can select its gate in the generated config: ```json { "engine": "polars", - "model_selection_mode": "auto_champion", + "score_model_selection": "champion", + "promotion_policy": "automatic", + "score_handoff": "after_alias_change", "metric": "heldout_rmse", "min_improvement": 0.1, "quality_threshold": 5.0, @@ -255,7 +324,7 @@ from the metric: RMSE/MAE/log loss are minimized, while R²/accuracy/F1 are maximized. Use a metric supported by the configured model task. The first comparison reports `reason=no_champion` and `eligible=false` because no baseline exists; successful bootstrap is recorded separately as -`alias_change.kind=initial` after the absolute gate passes. +`result.alias_change.kind=initial` in the Bundle output after the absolute gate passes. If promotion succeeds but scoring fails, the train job reports a failed dependent score task. Correct the scoring problem and run `score` again; @@ -312,9 +381,10 @@ databricks bundle deploy -t dev --profile databricks bundle run train -t dev --profile ``` -In manual mode, inspect the registered model version, put that concrete value -in `model_version`, redeploy the changed JSON, then run `score`. In automatic -mode, inspect the train and dependent score task results. The first score +For pinned scoring, inspect the registered version, put that concrete value +in `model_version`, redeploy the changed JSON, then run `score`. For champion +scoring, approve manually or use automatic promotion gates, then run score or +enable the optional handoff. Inspect both lifecycle and score task results. The first score rejects a missing source, disabled CDF, unsuitable row keys, a model output mismatch or an existing target schema mismatch before creating prediction output. It checks initial row count against `max_rows`; each score @@ -324,8 +394,8 @@ snapshot; later runs process only new inserts since the committed Delta receipt. A repeat without new rows is a no-op. No monthly date or source version is entered for each run. -In manual mode, the first candidate does not become champion automatically; -scoring stays pinned to its configured version. At initialization, choose +With manual approval, the first candidate requires explicit approval to become +champion. Pinned scoring can use a registered version without that approval. At initialization, choose `incremental_append` to keep v1 predictions and score only later source inserts with pinned v2. Choose `full_rebuild` to write a new physical `_v2` generation, @@ -346,8 +416,9 @@ run, unpause it deliberately. Each run pins the source's latest Delta version an first day of the current UTC month as the label cutoff. The preceding month is holdout; `monthly_lookback_months` (default four) controls the full window. Only labels available by the cutoff are eligible. `@champion` is resolved to a -concrete version for comparison if present. Manual mode leaves selection -unchanged; automatic mode applies its metric gates and invokes score. The source version is +concrete version for comparison if present. Manual approval leaves champion +unchanged; automatic promotion applies its metric gates. Score handoff follows +only a successful champion transition when enabled. The source version is pinned at run start, so `label_at` must faithfully record availability. The older SM-20a personal serverless rehearsal passed, but its jobs and test diff --git a/docs/user_guide/databricks_bundle_walkthrough.md b/docs/user_guide/databricks_bundle_walkthrough.md new file mode 100644 index 000000000..cd9c5b941 --- /dev/null +++ b/docs/user_guide/databricks_bundle_walkthrough.md @@ -0,0 +1,408 @@ +# Using the Databricks Bundle + +This walkthrough explains the local-engine Bundle from an operator's point of +view. Training and prediction use pandas or Polars; Spark reads bounded Delta +data and writes predictions. Start with the [Bundle configuration guide](databricks_bundle.md) +for installation, target bindings and source requirements. + +## Three independent decisions + +Configure these in the generated project's `config/workflow.json`: + +| Setting | Choice | What it controls | +| --- | --- | --- | +| `promotion_policy` | `manual_approval` | Training creates/evaluates a candidate; an operator reviews and approves or rejects it | +| `promotion_policy` | `automatic` | Training applies the configured quality gates and promotes a qualifying candidate | +| `score_model_selection` | `champion` | Each score run resolves the current controlled champion to one concrete version | +| `score_model_selection` | `pinned_version` | Each score run uses the explicitly configured `model_version` | +| `score_handoff` | `after_alias_change` | Successful champion initialization, promotion or rollback requests score immediately | +| `score_handoff` | `disabled` | A champion change does not start score; run score explicitly or through a separately configured trigger | + +For example, manual approval + champion scoring + handoff means: train v2, +review it, approve it, then automatically score using v2. Manual refers to +the approval decision; it does not require manual scoring afterward. + +Automatic promotion + disabled handoff means: train v2, promote it if its +quality passes, and leave prediction output unchanged until score runs. + +With pinned scoring, promotion of v2 does not change a pin to v1. Even an +automatic handoff still scores with v1. Select champion scoring when the +prediction model should follow promotions and rollbacks. + +With `score_model_selection=champion`, the configured `model_version` pin is +ignored. If champion changes from v1 to v2, the next score run loads v2 without +redeployment. A score run already in progress keeps the version it resolved at +its start. Handoff controls whether the next run starts immediately; selection +controls which model that run loads. + +A pin can also select a registered version that has not become champion. +Approval governs the champion alias; it does not automatically gate an +explicit pinned scoring choice. + +```mermaid +flowchart TD + A["Run train job: train or train_monthly"] --> B["Fit with pandas or Polars; log artifacts and metrics"] + B --> C["Register candidate and nominate challenger"] + C --> D["Evaluate against current champion"] + D --> E{"Promotion policy?"} + E -->|"automatic"| F{"Quality gates pass?"} + F -->|"No"| G["Keep champion; no score handoff"] + F -->|"Yes"| H["Initialize or promote champion"] + E -->|"manual_approval"| I["Return comparison and next_actions; wait for operator"] + I --> J{"Operator action"} + J -->|"reject"| K["Record rejection; keep champion; no score handoff"] + J -->|"approve"| L["Recheck saved evidence, expected champion and quality"] + L -->|"Checks pass"| H + L -->|"Checks fail"| M["Stop; inspect error; do not score"] + R["Run train job: rollback with saved promotion receipt"] --> S["Verify transition and restore previous champion"] + S --> T{"Score handoff enabled?"} + H --> T + T -->|"disabled"| U["Wait for a separate score run"] + T -->|"after_alias_change"| V["Call existing score job"] + U --> W["Operator or configured trigger starts score"] + W --> X{"Score model selection?"} + V --> X + X -->|"champion"| Y["Resolve current champion once"] + X -->|"pinned_version"| Z["Use configured model_version"] + Y --> P["Apply saved preprocessing and predict"] + Z --> P + P --> Q["Publish predictions according to model-change policy"] +``` + +## The two jobs and their tasks + +The resource keys are `train` and `score`; their visible names include the +project name and target/user prefix. Deployment creates two jobs, not a job +for each action. It does not train or create prediction tables by itself. + +| Job/task | Purpose | +| --- | --- | +| `train` job, `train` task | Runs the selected lifecycle action: train, train_monthly, approve, reject or rollback | +| `train` job, `should_score` task | Reads the action's boolean `score_requested` output | +| `train` job, `score_after_lifecycle` task | Calls the existing score job when the condition is true | +| `score` job, `score` task | Loads the selected model/artifact, predicts and publishes rows | + +Each job queues runs and permits one active run. The lifecycle job is the +single writer for aliases. The fixed score notebook ignores inherited lifecycle parameters and never +dispatches alias actions. Role/action override attempts are rejected. +These controls still require appropriate registry/table permissions; another +independent job or a direct Catalog alias edit can violate writer ownership. + +## Prepare the project + +1. Set the engine, existing source tables, row keys, features, target, pipeline, + model name, prediction name, training split and bounded read limits. +2. Select the three policies above. For learning the approval flow, use: + + ```json + { + "promotion_policy": "manual_approval", + "score_model_selection": "champion", + "score_handoff": "after_alias_change" + } + ``` + +3. Configure `metric`, `quality_threshold` and `min_improvement` **before + training**. For `heldout_rmse`, a threshold of `5.0` means RMSE must be at + most five target units. A minimum improvement of `0.1` means RMSE must fall + by at least 0.1, not 10%. A tie never qualifies. Manual approval also + verifies quality; it is not a way to bypass the gates. +4. Place the matching Skyulf wheel in `dist/`, then validate and deploy: + + ```powershell + databricks bundle validate --strict -t dev --profile + databricks bundle deploy -t dev --profile + ``` + +The source must already exist and have Change Data Feed enabled. Training and +scoring may reference the same source table. Prediction output is created by +score when needed. No default admission/control table is created. + +Configuration changes require deploying the changed project. Choosing an +operator action or supplying its evidence through Run now does not require +redeployment. Do not switch shared configuration while jobs are running. + +## Train a candidate in the UI + +1. Open **Jobs & Pipelines** and select the project's `train` job. +2. Choose **Run with different settings** (also called **Run now with different + parameters** in some UI versions). +3. Set `lifecycle_action=train`. Leave all operator-evidence fields empty. +4. Open the completed run, then the `train` task output. +5. Read `result`: model version, MLflow run and comparison. Follow the MLflow + experiment to inspect metrics, artifacts and input provenance. + +With manual approval, training returns `next_actions.approve` and +`next_actions.reject`. `score_requested=false`; the score call is skipped. +A registered candidate can be `challenger` even when its comparison is worse +than champion. Alias nomination and quality approval are different events. + +With automatic promotion, a qualifying model becomes champion and the optional +score handoff runs. A tied/worse candidate stays challenger with its validation +status/reason; champion is unchanged and score is not triggered. + +## Understanding the run settings form + +The train job exposes the same five parameters for all lifecycle actions. Most +are intentionally empty because ordinary training needs no operator evidence. +The form does **not** discover or populate the latest candidate automatically. +Leaving `lifecycle_action=train` starts another training run and can register +another version; it does not approve the candidate you just inspected. + +| Field | Meaning | When to fill it | +| --- | --- | --- | +| `lifecycle_action` | Operation to execute on this run | `train`, `train_monthly`, `approve`, `reject` or `rollback` | +| `candidate_version` | Registered model version to approve/reject; not a job run ID or MLflow run ID | Copy from the candidate's `next_actions` for approve/reject | +| `expected_champion_version` | Champion version that must still be current when the operation executes | Copy for approve/reject/rollback; literal `none` only for first-champion approval/rejection | +| `promotion_receipt_json` | Saved JSON receipt identifying a completed promotion to reverse | Rollback only | +| `rejection_reason` | Your explanation for rejecting this candidate | Reject only | + +For training, leave the four other fields empty. For approve/reject/rollback, +start with the matching `next_actions` values and clear fields belonging to +another action. Add your own reason when rejecting. These are **run overrides**; +they do not change the deployed job defaults or the Bundle promotion policy. + +Older deployments also show `comparison_sha256`. After updating both the wheel +and notebook/job definitions, leave that field empty or regenerate the Bundle +to remove it. A supplied full digest remains supported for API callers and +older automation. Never copy only a shortened digest. + +### Why the comparison still has a SHA-256 digest + +The digest is a fingerprint of the saved evaluation report, not a metric, +password or model version. The operator chooses the candidate and expected +champion. The Bundle retrieves the **full** digest from that candidate's active, +committed lifecycle receipt, then the strict Core service verifies the saved +report against it. It does not choose the latest model or blindly trust an +artifact's current contents. Changed reports, stale aliases and missing or +uncommitted receipts are refused. Quality gates are still rechecked. + +This convenience relies on the same controlled registry writer and permissions +as the lifecycle workflow. It removes manual hash copying, not the full proof +check. Direct Core approval/rejection APIs still require their explicit digest. + +## Reading the notebook result + +Both notebook entrypoints use the shared Core output renderer. The executed +cell shows an operation summary, champion version change when relevant, metric +comparison for training, prediction counts for scoring, and **Available action** +parameter tables. Expand **Technical details (JSON)** for the full result. +If HTML display is unavailable, the notebook prints indented JSON instead. + +Databricks may also show **Notebook exited:** followed by JSON. This is the +normal return value of `dbutils.notebook.exit`, not an error. We keep that JSON +for Jobs API consumers. The readable report is in the **first cell**; a separate +final cell returns the JSON. Keeping them separate prevents notebook exit from +replacing the same cell's report. +See the [Databricks exit reference](https://docs.databricks.com/aws/en/dev-tools/databricks-utils#exit-command-dbutilsnotebookexit). + +**Scoring requested** means the lifecycle action requested a child score job. +Check that child run for success. For a no-op, the manifest in the technical +result describes the **previous prediction write**; its model version can be +older than today's champion. No new rows or model provenance were written. + +## Where to find `next_actions` + +`next_actions` is a key in the completed **train task's JSON output**. It is not +a menu, a Catalog alias, an MLflow tag or an extra field in the run settings +form. You do not need another training run to retrieve it. + +1. Close the new-run settings dialog and open the train job's **Runs** tab. +2. Open the completed training run you want to review. +3. In that run's task graph/list, click **train**. Do not select `should_score` + or `score_after_lifecycle`; those tasks do not contain the comparison. +4. Open the task's executed notebook/output and inspect the **first cell's report**. + Use the **Available action: approve/reject** parameter table. The equivalent + `next_actions` JSON is under **Technical details (JSON)** and in the notebook + exit result. Older runs still show the old single-line JSON; updating the + Bundle does not rewrite historical output. Opening the source notebook from + Workspace shows the code, not this historical run's output. +5. Copy the values inside `next_actions.approve` or `next_actions.reject` into + the run settings form on the **same train job**. After a successful promotion, + save `next_actions.rollback` from that promotion run for a possible rollback. + +For a manual candidate, the output has this shape: + +```json +{ + "action": "train", + "result": { + "model_version": "2", + "comparison": { + "candidate_version": "2", + "champion_version": "1", + "metric": "heldout_rmse", + "eligible": true, + "reason": "candidate_improved" + } + }, + "score_requested": false, + "next_actions": { + "approve": { + "lifecycle_action": "approve", + "candidate_version": "2", + "expected_champion_version": "1" + } + } +} +``` + +Before approving, inspect these values: + +| Output path | What to check | +| --- | --- | +| `result.model_version` | The candidate version you intend to review | +| `result.comparison.champion_version` | The existing champion used for the comparison | +| `result.comparison.metric` | The metric used for the promotion decision | +| `result.comparison.candidate_metrics` / `champion_metrics` | Candidate and champion performance on the comparison data; for RMSE, lower is better | +| `result.comparison.eligible` / `reason` | Whether the candidate passed the configured gates and why | +| `score_requested` | Whether this action requests scoring; false while waiting for manual approval | + +For a CLI fallback, use the **train task run ID**, not the multi-task parent run +ID: + +```powershell +databricks jobs get-run-output --profile +``` + +The returned `notebook_output.result` is a JSON string containing `result` and +`next_actions`. UI labels can differ; Databricks documents navigation from a +job run to its task output in [Monitor Lakeflow Jobs](https://docs.databricks.com/aws/en/jobs/monitor). + +## Approve without training again + +Review the comparison first. On the **same train job**, choose **Run now with +different parameters**, then copy values from `next_actions.approve`: + +| Parameter | Value | +| --- | --- | +| `lifecycle_action` | `approve` | +| `candidate_version` | Exact candidate version from the output | +| `expected_champion_version` | Expected concrete champion version, or the literal `none` for bootstrap | +| `rejection_reason` | Empty | +| `promotion_receipt_json` | Empty | + +The Bundle resolves the saved comparison proof automatically. `none` +explicitly means that no champion should exist. Blank does not +mean the same thing. If someone has changed champion since evaluation, the +action refuses the stale evidence. + +Approval reloads the candidate's evidence and pinned evaluation data and +rechecks the gates. It does not fit, register or upload a new model. A first +champion requires the absolute gate; later champions also need improvement. +An unchanged successful approval can be retried without creating a version. + +When handoff is enabled, inspect all three lifecycle tasks and follow the +linked child score run. When disabled, run the score job yourself. You do not +need to redeploy merely because champion moved to another version. + +## Reject a candidate + +Use `next_actions.reject` in the train job's Run now parameters and add a +nonempty `rejection_reason` of at most 256 UTF-8 bytes. Clear the rollback +receipt field. Rejection records `approval_status=rejected` and a readable +reason, preserves champion and never requests score. + +The challenger alias may still point to the rejected candidate. Its status +explains why it is not champion; the next nomination replaces the pointer. +There is no reopen action here. Do not approve an explicitly rejected version. + +## Roll back a completed promotion + +The report's **If rollback is needed** section is optional guidance, not a +scheduled next step. It shows the **Required current champion** separately from +the **Restore version**. For a v1-to-v5 promotion, rollback requires champion +to still be v5 and restores v1. The report does not execute rollback. + +Expand **Show parameters only if you want to roll back** to see the form values. +The complete receipt, including its technical comparison digest, stays collapsed +until needed. Do not remove or edit fields inside that receipt; its exact value +is still required by the rollback API. + +Save `next_actions.rollback` from the successful promotion output. In the +train job's Run now parameters, use: + +| Parameter | Value | +| --- | --- | +| `lifecycle_action` | `rollback` | +| `expected_champion_version` | The promoted version that should still be champion | +| `promotion_receipt_json` | The complete JSON string value from the saved output | +| Other operator fields | Empty | + +Copy the receipt's value without an extra outer JSON-string quoting layer. +The receipt names the exact transition to reverse. Rollback verifies that +transition and restores its previous champion. It cannot reverse first-champion +initialization because there is no earlier champion. An incompatible current +alias state is refused. Repeating a still-current completed rollback returns +the same receipt. + +Rollback does not retrain or delete a model. A separate contender is retained. +It can request score if handoff is enabled. Champion scoring follows the +restored version; a pinned scorer keeps its pin. + +## What happens to existing predictions? + +Changing champion alone does not rewrite prediction rows. A later score run +uses `model_change_mode`: + +| Mode | After the selected model changes | +| --- | --- | +| `incremental_append` | Keep existing predictions and score only new source inserts with the selected version | +| `full_rebuild` | Score the full bounded source into a version-specific generation, then switch the stable view after success | + +In append mode, a handoff can be a successful no-op when no new rows exist. +That does not mean promotion failed. It means there were no rows to predict. +The first score processes the initial snapshot; subsequent runs follow the +committed Delta/CDF progress, without manually entering monthly dates. + +```mermaid +flowchart TD + A["Start score; resolve concrete model version"] --> B{"Model changed and full_rebuild selected?"} + B -->|"Yes"| C["Create a full generation, or resume an existing generation on rollback"] + C --> D["Activate stable view only after successful scoring"] + B -->|"No"| E["Read initial snapshot or new CDF inserts"] + E --> F{"Any rows to process?"} + F -->|"Yes"| G["Apply saved preprocessing; predict with pandas or Polars"] + G --> H["Append predictions and commit source progress"] + F -->|"No"| I["noop=true; no new Delta commit"] +``` + +For an insert test, add rows with new valid keys to the existing scoring source, +run score and inspect the added predictions. Repeating score without more data +should return a no-op. Do not insert duplicate keys or change historical source +rows to simulate a supported append; updates/deletes need their own recovery +policy. + +## Aliases and results to inspect + +| Item | Meaning | +| --- | --- | +| `champion` | Current controlled winner | +| `challenger` | Most recently nominated contender, possibly failed/rejected | +| `previous_champion` | Previous winner recorded by a promotion | +| `previous_challenger` | Last displaced contender, not a complete version history | +| `validation_status` / `validation_reason` | Evaluation outcome | +| `approval_status` / `approval_reason` | Explicit operator decision, when present | +| `score_requested` | Whether this lifecycle action requests the score job | +| `next_actions` | Copyable evidence-bound operator parameters | +| `noop` in score result | No new prediction write was necessary | + +History aliases are cleared when needed to avoid pointing to a conflicting +current role. Model versions and earlier evidence remain. Do not edit technical +receipt tags or move controlled aliases directly through Catalog UI. + +## Recovery and schedules + +- If training fails, inspect registration/evaluation evidence before retrying; + another training attempt can create another candidate version. +- If approval/rollback reports an uncertain alias write, reconcile its pending + evidence before retrying. Do not force a competing alias update. +- If promotion succeeds and the child score fails, fix scoring and run the + score job again. Do not retrain to repair a prediction failure. +- Optional monthly training starts paused. Its cron/timezone are Bundle + settings; choosing handoff does not itself create a scoring schedule. +- Full-rebuild rollback can revisit an earlier generation. It follows that + generation's committed progress; it does not erase previously written data. + +Platform references: [job parameters](https://docs.databricks.com/aws/en/jobs/parameters) +and [Run Job tasks](https://docs.databricks.com/aws/en/jobs/tasks/run-job). diff --git a/docs/user_guide/mlflow_registry.md b/docs/user_guide/mlflow_registry.md index 3c1572d43..d6a6d5547 100644 --- a/docs/user_guide/mlflow_registry.md +++ b/docs/user_guide/mlflow_registry.md @@ -171,8 +171,8 @@ read-only; the caller explicitly logs the desired numeric metrics to its MLflow run. Unlabeled production predictions cannot produce supervised quality metrics until their true labels arrive. Evaluation does not move aliases, publish predictions or deploy endpoints. -Promotion is a separate, explicit operation. SM-28a monthly candidate training -follows before Bundle generation. +Promotion is a separate, explicit operation. Monthly candidate training and +the generated [local-engine Bundle](databricks_bundle.md) reuse these services. ## Stage, promote, and roll back a local pipeline @@ -310,6 +310,24 @@ The local workflow wrapper additionally verifies controlled champion state and requires an explicit manual policy; the low-level registry API retains its existing legacy-champion compatibility. +`previous_challenger` retains the last contender displaced by nomination or +direct staging. Repeating a nomination does not rotate it. Promotion and +rollback preserve a separate historical contender; if that version becomes +champion or challenger, the conflicting history alias is cleared. Neither +clearing nor replacing the pointer deletes model versions or event records. +This is recent contender history, not an automatic model selection rule. + +History intent is stored in a separate `challenger_history_` +model-version tag with readable `from_version`, `to_version` and `state` +fields, each value bounded to 256 UTF-8 bytes. These versions describe the +history pointer's change. The registered-model marker +`previous_challenger_current_event` identifies the event's owning version, +which may differ from the historical version. Existing promotion receipt +formats remain unchanged. A cleared pointer retains its event marker, so +an incompatible manual alias addition is detected. Pending writes, malformed +history evidence and alias disagreement fail rather than silently replacing +that history. All mutations use the same lifecycle admission. + The lock protects only participating jobs. A principal with direct registry write permission can bypass it. A crashed Delta admission owner does not expire; clear it only after proving the original job cannot publish. @@ -326,6 +344,7 @@ validation report. Local SQLite/Spark evidence does not certify live Unity Catal wheel deployment, distributed admission, Delta publication or platform scale. Registry resolution/loading does not predict, mutate aliases, start Spark or -write a table. HTTP/SQL endpoints and Databricks Bundle generation remain later -initiative tasks; the monthly Spark/Delta runner has its own +write a table. HTTP/SQL endpoints remain later initiative tasks. The +[local-engine Bundle](databricks_bundle.md) integrates the existing services; +the monthly Spark/Delta runner has its own [batch contract](databricks_batch.md). diff --git a/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md b/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md index 97a2081f3..fdc79bbe6 100644 --- a/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md +++ b/initiatives/spark_and_mlflow/38-model-selection-and-approval-design.md @@ -1,7 +1,8 @@ # Independent model selection and approval Date: 2026-09-24. User-approved direction for SM-32/SM-33. -Status: design; not current Bundle functionality. +Status: SM-32 policies/operator actions are implemented and verified live; +SM-33 runtime overrides and broader migration validation remain planned. Parent: [local Bundle improvement program](37-local-bundle-improvement-program.md). ## Two independent decisions @@ -38,7 +39,10 @@ manual/automatic decision; no implicit ungated bootstrap. Add previous_challenger as a pointer to the last contender displaced by a new nomination. It is not the complete model history or an automatic fallback. -This extension is planned for SM-32; the current implementation has no such alias. +This extension is implemented locally in SM-32; see +[history implementation evidence](47-sm32-challenger-history-progress.md). +Matching Bundle wiring and personal-serverless validation passed; see +[live evidence](51-sm32-live-validation-report.md). | Transition | Champion | Challenger | Previous challenger | | --- | --- | --- | --- | diff --git a/initiatives/spark_and_mlflow/47-sm32-challenger-history-progress.md b/initiatives/spark_and_mlflow/47-sm32-challenger-history-progress.md new file mode 100644 index 000000000..183eea397 --- /dev/null +++ b/initiatives/spark_and_mlflow/47-sm32-challenger-history-progress.md @@ -0,0 +1,54 @@ +# SM-32: recent challenger history + +Date: 2026-09-25. Baseline: `6a7f9e95` on branch `090`. +Status: implemented locally, uncommitted; SM-32 remains ACTIVE. +Design: [independent model selection and approval](38-model-selection-and-approval-design.md). + +## Behavior + +Replacing a controlled challenger sets `previous_challenger` to the displaced +version. Both nomination and direct staging use this behavior. A repeated +nomination leaves the history and its event marker unchanged. Later replacements +rotate the pointer; older versions and their records are retained. + +Promotion keeps a separate historical contender. Rollback or nomination +clears history if its version becomes champion or challenger. The pointer +is not restored to a conflicting role or used as a score fallback. + +Implementation is centralized in `integrations/mlflow/promotion.py` at the +existing checked mutation boundary. No new job, table or dependency is added. +The old promotion/rollback receipt format stays unchanged. Auxiliary bounded +history tags retain prepared/committed intent and a current-event marker, +including cleared pointers. Every mutation uses the same pending-event and +writer-admission rules as existing lifecycle changes. Invalid aliases or +history evidence stop retries; uncertain writes require reconciliation. + +## Verification + +The initial seven targeted cases failed because history aliases and protections +were absent. The first implementation passed all 42 promotion tests. An +additional test reproduced an approval-replay bypass; controlled champion +resolution now checks history before that replay can return success. + +The final combined suite passed **155 tests**, with five expected legacy-mode +deprecation warnings, in 170.87 seconds. Evidence: +`rehearsals/sm32-history-regression.log`. Scoped Ruff lint/format, full repository +ty, strict MkDocs and `git diff --check` also passed. Documentation build +evidence: `rehearsals/sm32-history-mkdocs.log` (exit 0). + +Coverage includes rotation, unchanged retries, direct staging, promotion, +rollback, re-nomination of a historical version, raw/deleted aliases, missing +markers, malformed/prepared history receipts, and injected alias/marker write +failures. Existing pandas/Polars training/approval and Bundle compatibility +tests are included in the combined suite. + +A read-only review found no additional transition defect and identified useful +coverage for re-nomination and corrupted history receipts; those cases were added. + +## Remaining work + +Expose independent selector/promotion choices and operator inputs in the +existing serialized Bundle lifecycle job. Connect optional score handoff to +the existing score job, preserving pins and avoiding retraining. Then validate +generated projects and perform the combined Databricks rehearsal. No new +Databricks run or cloud resource change occurred in this slice. diff --git a/initiatives/spark_and_mlflow/48-sm32-bundle-actions-plan.md b/initiatives/spark_and_mlflow/48-sm32-bundle-actions-plan.md new file mode 100644 index 000000000..d33a66b9c --- /dev/null +++ b/initiatives/spark_and_mlflow/48-sm32-bundle-actions-plan.md @@ -0,0 +1,58 @@ +# SM-32 Bundle operator actions implementation plan + +Date: 2026-09-25. Implements the already approved selection/approval design. +Prior history implementation remains uncommitted. Keep two persistent jobs. + +## Scope and file map + +1. Add a narrow `integrations/databricks/job_runtime.py` adapter. Parse job + parameters, enforce lifecycle/score roles, call existing `run_action`, + expose copyable operator evidence and decide optional score handoff. + Training, evaluation, registry mutation and prediction stay in existing Core services. +2. Keep two thin template entrypoints with fixed lifecycle/score roles. The + shared adapter owns widgets, target resolution, temporary artifacts, + task-value publication and JSON output. +3. Change init schema/config/examples to independent `score_model_selection` + and `promotion_policy`, plus `score_handoff=disabled|after_alias_change`. + Quality gates are configurable for manual approval as well as automatic promotion. +4. Keep the stable `train` and `score` job resource keys. `train` owns all + lifecycle actions via `lifecycle_action` and explicit evidence parameters. + Its condition task calls the existing queued score job only when the + successful action returns a champion transition and handoff is enabled. + All new projects contain this graph, so changing a policy in config does + not require conditional YAML regeneration. No new table or third job. +5. Update generated/root docs, changelog and queue. Legacy Core callers remain + supported, but migrate old generated projects' config, notebook and job + graph together; the new adapter refuses legacy/partial policy configuration. + +## Operator inputs + +- `lifecycle_action`: train, train_monthly, approve, reject or rollback. +- approve/reject: candidate_version, comparison_sha256 and + expected_champion_version. Explicit `none` means bootstrap; blank is an error. +- reject additionally requires rejection_reason. +- rollback: promotion_receipt_json copied from a completed promotion result, + plus expected_champion_version. Never infer latest or roll back initialization. +- Output includes candidate parameters and, when applicable, ready-to-copy + rollback parameters. Scoring pins never change implicitly. + +## Verification sequence + +1. Failing parameter/role/handoff tests before implementing the adapter. +2. Exercise generated notebook actions and real pandas/Polars MLflow candidate + lifecycles, including manual bootstrap, approval, rejection and rollback. +3. Generate actual projects with Databricks CLI for all four policy pairs, + handoff modes, schedules and both compute branches; parse emitted YAML/JSON + and validate resource/task dependencies and parameter bindings. +4. Strict dev validation on the selected skyulf profile, with a locally built + matching wheel. No deploy/run in this local implementation slice. +5. Relevant regression suites, Ruff, full ty, strict docs build and review. + SM-32 remains active until the live rehearsal verifies operator actions. + +## Platform references + +Use [job parameters](https://docs.databricks.com/aws/en/jobs/parameters) for +operator overrides and [task-value conditions](https://docs.databricks.com/aws/en/jobs/tasks/if-else) +for conditional handoff. The notebook uses the documented +[widgets.getAll](https://docs.databricks.com/aws/en/dev-tools/databricks-utils#widgets-getall) +mapping; selected serverless/policy runtimes meet its 13.3 LTS minimum. diff --git a/initiatives/spark_and_mlflow/49-sm32-bundle-actions-validation.md b/initiatives/spark_and_mlflow/49-sm32-bundle-actions-validation.md new file mode 100644 index 000000000..a2c8d2829 --- /dev/null +++ b/initiatives/spark_and_mlflow/49-sm32-bundle-actions-validation.md @@ -0,0 +1,86 @@ +# SM-32: Bundle operator actions and independent policies + +Date: 2026-09-25. Branch: `090`; committed baseline: `6a7f9e95`. +Status: implemented and verified locally, uncommitted. SM-32 remains ACTIVE +until the live operator rehearsal. No deployment or job run occurred here. + +## Delivered behavior + +Initialization exposes independent `score_model_selection`, `promotion_policy` +and `score_handoff`. All four selection/promotion pairs are supported. A +promotion or rollback never rewrites a configured score version pin. + +The existing `train` job owns training, approval, rejection and rollback. +Operators select `lifecycle_action` and copy explicit version/evidence inputs +from `next_actions` in the earlier output. Approval reuses the saved candidate; +rejection/rollback do not train or register another model. Empty bootstrap +versions are rejected; the explicit `none` value represents no prior champion. + +The lifecycle job has three tasks: execute, check the `score_requested` task +value, and conditionally call the existing score job. Handoff is disabled by +default. When enabled it follows a successful champion initialization, +promotion or rollback. Rejection, tied/nonpromoted training and unresolved +alias writes do not trigger scoring. Score still follows its independent +selector. Failed score can be retried without training. + +There are still two jobs, each queued with one active run, and no new control +table. Separate tiny notebooks fix their lifecycle/score roles in code. The +shared `job_runtime` adapter parses parameters and delegates to existing Core +services. Run parameters cannot change the score notebook into an alias writer. +Exclusive writer permissions remain an external deployment requirement. + +New projects use the new configuration contract. Older generated projects +must migrate configuration, both entrypoints and job graph together. Core +direct callers retain the explicit legacy compatibility path. + +## Verification + +| Check | Result | +| --- | --- | +| Combined affected regression suite | **188 passed**, five expected legacy-policy deprecation warnings, 168.91 seconds | +| Real CLI template generation | **16 passed**: two selectors x two promotion policies x two handoff modes x two compute types | +| Strict Bundle validation | **8 serverless dev configurations passed**, using the selected `skyulf` profile | +| Wheel | Built `skyulf_core-0.9.0-py3-none-any.whl`; imported adapter directly from wheel and matched packaged source to working source | +| Static checks | Scoped Ruff lint/format, full repository ty, `git diff --check` passed | +| Documentation | Strict MkDocs build exited 0 | +| Review | No correctness blocker; added explicit injected-role/action and malformed rollback receipt coverage | + +The regression suite covers real local MLflow artifacts for pandas and Polars, +manual bootstrap, saved-evidence approval, rejection, rollback/retry, historical +challengers, automatic promotion, tied candidates, independent score pins, +notebook delegation, parameter guards and failed/uncertain write boundaries. + +Generation tests invoke the installed Databricks CLI rather than substituting +Go-template text. They inspect actual emitted YAML/JSON, dynamic references, +condition dependencies, Run Job routing, schedules and compute branches. Both +engines are represented. The optional CLI tests require the explicit +`SKYULF_BUNDLE_CLI_TEST_PROFILE` environment variable. The generation run had +one pytest-cache permission warning; all 16 cases passed. + +Strict validation used CLI v1.17.0 and the built wheel. Policy-cluster projects +were generated and inspected, but company policy/compute resolution was not +validated against the personal workspace. Validation did not deploy resources, +run compute or prove runtime task-value/Run Job behavior. + +Evidence under `rehearsals/`: + +- `sm32-bundle-regression.log`: final combined suite. +- `sm32-bundle-generation.log`: real CLI generation matrix. +- `sm32_bundle_generation_tmp/*/output/sm32_generated/validation.stdout.json` + and `validation.stderr.txt`: strict validation output for serverless cases. +- `sm32-bundle-final-ty.log`, `sm32-bundle-mkdocs-clean.log`. +- `sm32-bundle-wheel/skyulf_core-0.9.0-py3-none-any.whl`. + +## Remaining acceptance + +Use the existing personal test deployment for a controlled pandas/Polars +rehearsal. Verify manual candidate output, first approval, rejected candidate, +later approval and rollback through job parameters. Check actual task-value +conditions, queued score handoff, selector preservation and recovery without +new training. Preserve two jobs and no admission tables. Include the prior +`previous_challenger` slice in the live verification. + +SM-33 continues broader configuration/migration validation; SM-37 owns enforced +production identities and writer permissions. Company targets and policy +compute remain separate acceptance gates. This evidence does not establish +production readiness or close SM-32. diff --git a/initiatives/spark_and_mlflow/50-sm32-live-rehearsal-plan.md b/initiatives/spark_and_mlflow/50-sm32-live-rehearsal-plan.md new file mode 100644 index 000000000..150e681ea --- /dev/null +++ b/initiatives/spark_and_mlflow/50-sm32-live-rehearsal-plan.md @@ -0,0 +1,31 @@ +# SM-32 live operator rehearsal + +Date: 2026-09-25. Authorized by the user's request to finish Databricks testing. + +Use profile `skyulf`, existing schema `workspace.skyulf_lifecycle_test`, and +existing Bundle jobs train `155738051514173` and score `684955889505992`. +Preserve existing source, prior models and prediction outputs. Register fresh +`sm32_model_polars` and `sm32_model_pandas` with separate prediction outputs so +bootstrap and artifact provenance can be tested without deleting earlier evidence. +No new schema, persistent job or admission table. Every job run is bounded to +900 seconds, with retries disabled and schedules inactive. + +1. Save deployed settings, migrate the existing generated project to the current + template, and upload the verified wheel under a fresh SM-32 workspace path. +2. Run Polars manual training and first approval through the real lifecycle job. + Verify manual training skips score and approval calls the separate score job. +3. Train and approve an improved candidate. Train later candidates to exercise + previous_challenger, reject one, and roll back the saved completed promotion. + Verify rejection skips score and rollback follows its explicit handoff choice. +4. Use the same two jobs with pandas/automatic configuration. Verify first + champion, improvement, tied candidate and scoring-pin independence. +5. Audit concrete UC aliases, model counts/metrics, prediction counts/provenance, + operator retry/no-fit behavior and actual condition/Run Job task outcomes. +6. Leave the Bundle in an explicit manual/champion configuration for the user's + practice, with a reviewable candidate when possible. Publish exact run links + and UI instructions in an English user guide with Mermaid diagrams. + +Deployment/config changes occur only between completed runs. An unexpected +alias outcome requires inspection before any retry. A score failure after a +committed promotion is recovered by scoring without retraining. Do not declare +SM-32 complete until the planned runtime checks have evidence. diff --git a/initiatives/spark_and_mlflow/51-sm32-live-validation-report.md b/initiatives/spark_and_mlflow/51-sm32-live-validation-report.md new file mode 100644 index 000000000..af11c2c9c --- /dev/null +++ b/initiatives/spark_and_mlflow/51-sm32-live-validation-report.md @@ -0,0 +1,161 @@ +# SM-32 live Bundle operator validation + +Date: 2026-09-25. Status: PASSED for the personal serverless SM-32 scope. +Profile: `skyulf`. Existing schema: `workspace.skyulf_lifecycle_test`. +Plan: [live rehearsal](50-sm32-live-rehearsal-plan.md). + +Historical snapshot: the practice candidate below was subsequently approved by +the user. Polars champion is now v5; see [report 52](52-sm32-operator-output-and-evidence.md) +for the user approval and later report/form acceptance. + +## Scope + +The existing `skyulf_lifecycle` Bundle and two persistent jobs are reused: +train `155738051514173`, score `684955889505992`. Both jobs are queued with +one active run; no schedule is active. Existing source, models and predictions +are retained. Fresh `sm32_model_polars` and `sm32_model_pandas` support testing +first-champion behavior without deleting earlier evidence; each has a separate +prediction output. No new schema, persistent job or admission table. + +The source is the existing deterministic lifecycle fixture, not a business +accuracy benchmark. Training reads Delta version 0: 120 fit rows and 40 +holdout rows. Initial scoring reads the current 170-row source. A deliberately +weak intercept-free model followed by an intercept-enabled model gives a +predictable improvement for testing promotion. The threshold `500.0` is a +rehearsal gate, not a recommended production threshold. + +## Live defect and repair + +First deployment exposed an unsupported timeout on the rehearsal's If/else +task. That timeout was added by the test harness, not the product template; +the harness now bounds compute tasks and the overall job only. + +Initial manual training passed. Approval initialized champion successfully, +but its child score failed: Databricks automatically forwarded the parent's +`lifecycle_action=approve` and evidence into the child Run Job task. The fixed +score adapter correctly refused an explicit lifecycle dispatch, exposing the +missing notebook-boundary filtering in local tests. + +The repair filters only inherited lifecycle/evidence fields at the fixed score +notebook boundary. Role/action overrides remain rejected, and direct adapter +API validation is unchanged. Four inherited-parameter tests failed before the +fix and passed afterward. Two further notebook tests preserve override guards. +Review found no blocker. + +The corrected wheel was uploaded under a fresh `sm32/r2` path. SHA-256: +`420833172d6392964fd695aa64d277637648d195f11cd836fa894f6d295085f5`. +Packaged adapter source was compared with the working source. The completed +approval was replayed without training/registration, returned the same receipt, +and its child score successfully wrote 170 predictions. The original failed +run remains available as evidence; no alias was manually moved to repair it. + +## Verification + +- Local affected regression: **194 passed**, five expected legacy deprecation + warnings, 135.26 seconds (`rehearsals/sm32_live/regression.log`). +- Scoped Ruff and full repository ty passed. +- Strict documentation build passed; the walkthrough's two Mermaid diagrams + were parsed with the real Mermaid parser. +- Deployed configuration inspection confirmed exactly two persistent jobs, + correct conditional graph, serialized queues and no active schedule. + +All 13 expected-success lifecycle job runs completed, together with five +successful conditional child score runs. The initial pushdown failure remains +in the run table below. This is not company-environment production acceptance. + +## Recorded lifecycle job runs + +| Scenario | Run | Outcome | Score requested | +| --- | --- | --- | --- | +| `polars_manual_v1` | [503746906366109](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/503746906366109) | SUCCESS | False | +| `polars_approve_v1` | [906338302689820](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/906338302689820) | FAILED | True | +| `polars_approve_v1_recovery` | [755489153097671](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/755489153097671) | SUCCESS | True | +| `polars_manual_v2` | [108692285496124](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/108692285496124) | SUCCESS | False | +| `polars_approve_v2` | [728667696836302](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/728667696836302) | SUCCESS | True | +| `polars_manual_v3` | [238888283154553](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/238888283154553) | SUCCESS | False | +| `polars_reject_v3` | [305664316009276](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/305664316009276) | SUCCESS | False | +| `polars_manual_v4` | [450726548945680](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/450726548945680) | SUCCESS | False | +| `polars_rollback_v2` | [317513046274699](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/317513046274699) | SUCCESS | True | +| `polars_rollback_retry` | [167619432389655](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/167619432389655) | SUCCESS | True | +| `pandas_auto_v1` | [1066520934685111](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/1066520934685111) | SUCCESS | False | +| `pandas_auto_v2` | [384007232635977](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/384007232635977) | SUCCESS | True | +| `pandas_auto_v3` | [107464962193774](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/107464962193774) | SUCCESS | False | +| `polars_practice_v5` | [888140358241905](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/888140358241905) | SUCCESS | False | + +The original failed approval had already committed champion. Its `score_requested=true` +means the child was requested, not that scoring succeeded. Recovery reused the +committed approval; the later successful handoff was captured separately. + +## Final registry and prediction audit + +[Audit run 939680081628471](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/360955161400049/run/939680081628471) +passed. This was a one-time submitted run, not a third persistent Bundle job. +It checked all eight model versions and their six held-out regression metrics. +No approval/rejection/rollback/retry registered an extra model version. + +| Engine | Versions | Champion | Challenger | History retained | Predictions | +| --- | --- | --- | --- | --- | --- | +| Polars | 5 | 1 | 5 | previous_challenger=4; v3 explicit rejection recorded | 180 unique rows, model v1 | +| pandas | 3 | 2 | 3 | previous_champion=1 | 180 unique rows, pinned model v1 | + +The audit appended ten new keys to the existing source (170 -> 180 rows). +Each engine's existing prediction output received exactly ten new rows. +Replaying each scorer returned noop=true and retained Delta version 2. +Insert/replay verification called the existing Core run_action score service +inside the one-time notebook. Conditional dispatch, parameter inheritance and +pinned scoring had already been verified through the actual Bundle jobs. + +Live combinations: Polars manual approval with champion scoring; pandas +automatic promotion with pinned scoring. Handoff enabled and disabled were +both exercised. The complete four-pair policy matrix remains covered by local +pandas/Polars tests and actual CLI template generation; this report does not +claim every matrix combination was separately deployed live. + +## Retained practice configuration + +The two Bundle jobs now use Polars, manual_approval, champion scoring, +after_alias_change handoff and incremental_append. No schedule is active. +Model: workspace.skyulf_lifecycle_test.sm32_model_polars. +Source: workspace.skyulf_lifecycle_test.source. +Output: workspace.skyulf_lifecycle_test.sm32_predictions_polars. + +The eligible v5 candidate is intentionally not approved. Its training run is +[888140358241905](https://dbc-45604623-c18b.cloud.databricks.com/?o=7474646244882000#job/155738051514173/run/888140358241905). +These values are a snapshot; after another nomination or champion change, +use the current candidate output rather than replaying stale practice inputs. + +1. Open that run's train task output and review the comparison/MLflow metrics. +2. On the same train job choose Run now with different parameters. +3. Copy the following values; leave rejection_reason and promotion_receipt_json empty. + +```json +{ + "lifecycle_action": "approve", + "candidate_version": "5", + "comparison_sha256": "51358cdc74ec62aa14f689cfa2b06532e83f338ecf6a0ff5c9605dc26d2c3c62", + "expected_champion_version": "1" +} +``` + +4. Expect champion v5 and a successful child score run. No new source rows means + score can be a no-op: existing append-mode v1 predictions remain unchanged. +5. To reverse this new promotion, copy next_actions.rollback from that approval + result into another lifecycle run. Do not use the old v2 receipt for v5. +6. To practice rejection instead, use the pending candidate's reject parameters + and add a reason before approving it. A rejected version cannot be reopened; + another training run creates another candidate. + +The generic English walkthrough, including two Mermaid diagrams, is in +[docs/user_guide/databricks_bundle_walkthrough.md](../../docs/user_guide/databricks_bundle_walkthrough.md). +The final queue marks SM-32 DONE and SM-33 READY. Company identities/permissions, +policy compute, broader config migration, production operations and combined +acceptance remain in their own queued tasks. Broad Spark/serving work remains later. + +## Evidence locations + +Exact requests, run states, notebook results and child score outputs are under +rehearsals/sm32_live/. sequence-r2.log records the successful continuation; +sequence.log retains the first failed handoff. audit-result.json records final +UC aliases, per-version metrics, row counts and Delta publication receipts. +The corrected wheel is in wheel_r2/. Plan/report files are ignored by the +repository's broad initiative rule and need explicit inclusion at commit time. diff --git a/initiatives/spark_and_mlflow/52-sm32-operator-output-and-evidence.md b/initiatives/spark_and_mlflow/52-sm32-operator-output-and-evidence.md new file mode 100644 index 000000000..163b48bf1 --- /dev/null +++ b/initiatives/spark_and_mlflow/52-sm32-operator-output-and-evidence.md @@ -0,0 +1,111 @@ +# SM-32 follow-up: readable output and automatic comparison proof lookup + +Date: 2026-09-25. This is an operator usability follow-up to SM-32; the broader +SM-33 configuration/migration work remains READY. + +## User observation and verified initial state + +The user approved Polars candidate v5 through the train job. Parent run +`24807365707427` and child score run `379146043586828` succeeded. Promotion +event `74ff48555f304272ae50c59f771295b0` changed champion from v1 to v5. +The score result was a no-op: input/output counts were zero and the prediction +Delta version remained 2. Its manifest described the previous v1 write, +not a new prediction with v1. + +The raw `Notebook exited` result was difficult to read and the manual form +required copying a 64-character comparison digest. + +## Implementation + +- `job_output.py` renders a shared, HTML-escaped report for train, approve, + reject, rollback and score. Reports separate operation/alias outcomes, + comparison metrics, prediction counts and next-action parameter tables. + Technical JSON remains available in a disclosure and in the Jobs API result. +- Notebook entrypoints render the report in the first cell and return the + machine-readable JSON in a separate final cell. A live R3 experiment proved + that `notebook.exit` replaces the same-cell result; R4 addresses that behavior. +- The generated form has five fields. `comparison_sha256` is removed from its + job defaults and base parameters. Approval/rejection requires a concrete + candidate and explicit expected champion (`none` for bootstrap). +- The adapter reads the full proof from that candidate's active committed + lifecycle receipt. It delegates to the existing strict Core operation, + which verifies artifact/receipt consistency, aliases, policy and quality. + No hash truncation, latest-candidate fallback or extra table is introduced. +- Explicit full digests remain supported for older/API callers. Direct Core + approval/rejection APIs retain their required digest contract. Rollback still + uses the exact promotion receipt and expected champion. +- If rendering fails, indented JSON is printed and the already-completed + lifecycle action is not turned into a failure inviting a mutation retry. + +## Verification + +- 80 focused behavior tests passed, including pandas/Polars with explicit and + automatically resolved proof, bootstrap, approval/rejection retries, stale + champion, changed comparison artifacts, wrong policy, rejection and rollback. +- 16 real CLI generation combinations passed; 46 promotion lifecycle tests passed. +- After the live same-cell discovery, 19 output/notebook tests passed, including + two separate-cell regressions. Scoped Ruff, ty and strict docs passed. +- R3 parent `605352825761827` succeeded without a digest parameter, returning + the user's exact existing promotion event; the new five-field form was read + back through Jobs API. Exported notebook output exposed the same-cell issue. +- R4 parent `719498349185749` succeeded. Task `1009765289788596` returned the + exact same promotion event without a hash input. Jobs export proved two + notebook cells: a persisted HTML report (`listResults`) followed by the raw + JSON exit result. Both the summary and Technical details disclosure exist. +- Child score `959432187722626` succeeded: zero input/output rows, `noop=true`, + Delta version 2. Its exported HTML explicitly labels the manifest as the + previous write. Final aliases: champion v5, previous_champion v1, + previous_challenger v4; no challenger alias remains on the promoted version. + +Live follow-up is complete. The existing schema/model/output and two persistent +jobs were reused; no company-target readiness claim is made. + +R4 wheel: `skyulf_lifecycle_test/sm32/r4/skyulf_core-0.9.0-py3-none-any.whl`. +SHA-256: `2c0bea77d8d09418f2aa8b3d465cc0eb047da9418615eb8a74745716f9654d06`. +Both jobs retain 900-second timeouts. No new schema, source/prediction table, +registered model version or persistent job was created by this follow-up. + +Local rehearsal evidence is under `rehearsals/sm32_live/output-*` (ignored). +The walkthrough is `docs/user_guide/databricks_bundle_walkthrough.md`. + +## R5 presentation clarification + +The user found the rollback block misleading. It now says **If rollback is +needed**, explicitly states that rollback is optional, and separates **Required +current champion: v5** from **Restore version: v1** for the retained example. +The full receipt (including its comparison proof) is inside a closed parameters +disclosure. API values and rollback validation are unchanged. + +Seven report tests, scoped Ruff/ty and strict docs passed. R5 was deployed to +the same two jobs and their wheel references were read back successfully. No +new job run was started for this presentation-only change; historical outputs +remain unchanged. A preview using the actual R4 receipt is saved locally in +`rehearsals/sm32_live/operator-output-preview.html`. + +R5 wheel directory: `skyulf_lifecycle_test/sm32/r5`. +SHA-256: `9e40dfbbd5af4791d06c1f04a61d23c3cf8f9646258fd34ee4f305b741bf5882`. + +## Requested R5 live rerun and commit validation + +The user subsequently requested a live rerun before commit. Parent lifecycle +run `769913416634457`, train task `1092954776398504`, and child score run +`690155923861600` all succeeded on R5. Approval supplied only candidate v5 and +expected prior champion v1, without a comparison digest. It replayed the exact +existing event `74ff48555f304272ae50c59f771295b0`. + +The exported, executed notebook was decoded and its actual HTML checked: + +- The report says **If rollback is needed** and states rollback is optional. +- Required current champion is v5; restore version is v1. +- Visible text outside disclosures contains neither `comparison_sha256` nor + `promotion_receipt_json`; the complete proof remains in collapsed details. +- The separate final cell retains the raw JSON result for API clients. +- Child score also persisted its HTML report and returned zero input/output + rows, `noop=true`, prediction Delta version 2. +- Final aliases remained champion v5, previous_champion v1 and + previous_challenger v4. No rollback or new training was executed. + +Fresh commit verification: 144 affected tests passed, including both local +engines, explicit/saved proof checks, lifecycle history, notebook output, +rollback/retry, and 16 real CLI generation combinations. Strict docs passed. +Rehearsal evidence filenames use the `output-replay-r5-*` prefix. diff --git a/initiatives/spark_and_mlflow/HANDOFF.md b/initiatives/spark_and_mlflow/HANDOFF.md index 371533920..0794afa29 100644 --- a/initiatives/spark_and_mlflow/HANDOFF.md +++ b/initiatives/spark_and_mlflow/HANDOFF.md @@ -1,10 +1,42 @@ # Session handoff - 2026-09-25 -## Current priority: SM-30 through SM-43 +## Current snapshot after SM-32 delivery + +SM-32 is DONE for its documented local/personal-serverless scope; SM-33 is READY. +The delivery includes checked challenger history, independent Bundle policies, +serialized operator actions, score parameter-pushdown handling, automatic proof +lookup, readable reports and the English operator walkthrough. + +The user approved Polars v5 in run `24807365707427`; its score child +`379146043586828` succeeded with no new data. Current model: +`workspace.skyulf_lifecycle_test.sm32_model_polars`; champion v5, +previous_champion v1, previous_challenger v4. The former practice candidate +has already been approved; do not treat the older report's v1/v5 state as current. + +Existing Bundle: Polars/manual_approval/champion/after_alias_change/incremental_append. +Two persistent jobs remain: train `155738051514173`, score `684955889505992`. +Schedules are inactive; both jobs use 900-second timeouts and the R5 wheel. +Existing source and prediction resources are retained. + +R4 proved separate persisted HTML and JSON notebook cells. R5 makes rollback +optional in the report, distinguishes required/restore versions and collapses +the receipt. Requested R5 live acceptance: parent `769913416634457`; +HTML assertions passed for task `1092954776398504`; child score +`690155923861600` succeeded with a no-op and Delta version 2. All 144 affected +tests and strict docs passed before commit. Final run/check results +are in [the operator follow-up](52-sm32-operator-output-and-evidence.md). +The broader SM-32 live evidence is [report 51](51-sm32-live-validation-report.md). +The user guide is `docs/user_guide/databricks_bundle_walkthrough.md`. + +The SM-32 delivery commit follows `6a7f9e95`; use git log for its final hash. +Reports 47 through 52 belong to that delivery. SM-33/37/43 retain +config/identity/company gates; do not claim company production readiness. + +## Historical implementation context through SM-32 local preparation The user approved the [local Bundle improvement program](37-local-bundle-improvement-program.md) and explicitly requested [independent scoring selection and promotion policy](38-model-selection-and-approval-design.md). -**SM-30, company tags and SM-31 are committed as `fcfcee31`; SM-32 is ACTIVE.** +**Earlier baseline: SM-30, company tags and SM-31 committed as `fcfcee31`.** The requested commit passed 116 tests and all applicable hooks (including ty). SM-32 now separates score_model_selection and promotion_policy at the library run_action boundary. All four combinations passed on pandas and Polars; @@ -20,19 +52,29 @@ or registration; see [manual approval progress](45-sm32-manual-approval-progress Final combined regression suite passed 321 tests; full repository ty and scoped Ruff passed. Commit `94b28320` includes the SM-32 policy/approval slice and the Core test relocation; the complete SM-32 task remains open. -The continuation implements library reject/rollback and safe retries; +Commit `6a7f9e95` implements library reject/rollback and safe retries; see [its evidence and limits](46-sm32-reject-rollback-progress.md). The combined affected suites passed 145 tests, scoped Ruff lint/format and full repository ty passed, and strict MkDocs built successfully. The progress report is included alongside this implementation. -Next implement previous_challenger and matching Bundle actions/handoff; -do not mark SM-32 complete yet. No new Databricks run was made. +The subsequent uncommitted slice implements previous_challenger history; +see [its evidence and boundaries](47-sm32-challenger-history-progress.md). +Its combined affected suites passed 155 tests; Ruff, full ty and strict MkDocs +passed. Include the new progress report explicitly at commit time because +the repository's broad initiative ignore rule applies to new files. +Matching Bundle choices and serialized operator actions/handoff are now +implemented locally; see [the plan](48-sm32-bundle-actions-plan.md) and +[validation](49-sm32-bundle-actions-validation.md). That local-only slice +was followed by the completed live rehearsal in report 51. Combined affected regression: 188 passed; real CLI +generation: 16 passed; all eight serverless configurations passed strict dev +validation. Wheel import/source check, Ruff, full ty and strict MkDocs passed. +Reports 47, 48 and 49 need explicit inclusion at commit time. Latest follow-up: Bundle initialization now asks for optional risk_category, PayingRegNo has an explicit policy-compute example, and new receipts use from_version while reading older formats. 44 relevant tests and real CLI generation/strict serverless validation passed. No live resources changed. -The requested previous_challenger replacement-history alias is specified in -the SM-32 design and queue, not implemented yet. +The requested previous_challenger replacement-history alias now exists in +Core; its live Databricks validation subsequently passed in report 51. The user requested readable/company-compatible tags and a clean live reset before SM-31. [The clean rehearsal](41-company-tags-and-clean-live-validation.md) passed all four tasks in run 607409241163605. [SM-31 evidence](42-sm31-refactor-plan-and-evidence.md) @@ -45,8 +87,10 @@ jobs (train 155738051514173, score 684955889505992). One source and two engine prediction tables each contain 170 rows. Main model_polars has champion=2, challenger=3 rejected. model_pandas has champion=1 and challenger=5 error after the explicit rollback test. Both scorers replayed without new commits. -No schedule is active. The notebook is now 44 lines, delegating to Core -local_workflow.py and prediction_output.py. Keep business config in the project. +No schedule is active. That deployed notebook delegates to Core local_workflow.py +and prediction_output.py. The new, locally verified template uses separate +seven-line lifecycle and score entrypoints calling job_runtime. Keep business +config in the project. SM-30 changes challenger semantics: a trained/registered contender such as tied v3 remains challenger, with evaluation status/reason visible; only @@ -55,8 +99,7 @@ pointer while retaining history. Rollback now preserves a separate contender with a verified receipt. Real local MLflow tests cover pandas and Polars, including manual nomination, tied candidates and comparison errors. -Next separate pinned/champion selection from -manual/automatic promotion, expose validated runtime/configuration choices +After SM-32 live acceptance, expose validated runtime/configuration choices and independent schedules, improve metrics/search, identities/operations, packaging, generated CI, data recovery and documentation. SM-43a verifies the combined personal-workspace workflow; SM-43b separately gates company use. diff --git a/initiatives/spark_and_mlflow/OPEN_QUEUE.md b/initiatives/spark_and_mlflow/OPEN_QUEUE.md index 51b1d0093..b5c92a124 100644 --- a/initiatives/spark_and_mlflow/OPEN_QUEUE.md +++ b/initiatives/spark_and_mlflow/OPEN_QUEUE.md @@ -1,6 +1,6 @@ # Spark ve MLflow — Open Queue -Updated: 2026-09-24. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b, SM-20a/20R/20S and SM-27/29 complete for their documented scopes. Target: 0.9.0.** +Updated: 2026-09-25. **SM-00 through SM-16, SM-15L/15I/24a/25/26, SM-22a/b/c/28a/28b, SM-20a/20R/20S and SM-27/29 complete for their documented scopes. Target: 0.9.0.** The pre-Spark local Bundle lifecycle gate passed live: selectable rescoring, automatic champion selection, failed-score recovery and serialized handoff. This is functional completion for the selected workflow. Production must @@ -39,14 +39,27 @@ scope and do not imply the improvements below already exist. Read [the improvement program](37-local-bundle-improvement-program.md) and [the independent selection/approval design](38-model-selection-and-approval-design.md). Each task includes implementation locations and concrete acceptance checks. -**SM-30, company-compatible tags and SM-31 are committed; SM-32 is ACTIVE.** +**SM-32 is DONE for the documented local/personal-serverless scope; SM-33 is READY.** +User-requested operator usability follow-up: readable notebook reports and +automatic full-proof lookup are implemented and verified locally and in the +same personal Bundle; see [the follow-up evidence](52-sm32-operator-output-and-evidence.md). +See [live operator evidence and practice instructions](51-sm32-live-validation-report.md). +The SM-32 delivery includes the history/Bundle/live-fix and operator usability +slices with reports 47 through 52; it follows baseline commit `6a7f9e95`. Commit `fcfcee31` passed 116 tests and all applicable commit hooks. The first SM-32 library policy slice passed 78 tests; see [policy separation progress](43-sm32-policy-separation-progress.md). The [manual approve library action](45-sm32-manual-approval-progress.md) now rechecks saved candidate evidence without training. Library reject/rollback and checked retries are implemented in the [current slice](46-sm32-reject-rollback-progress.md); -145 affected tests passed locally; contender history and Bundle wiring remain open. +145 affected tests passed locally. The subsequent +[challenger history slice](47-sm32-challenger-history-progress.md) is implemented +locally with 155 affected tests passing. Matching Bundle choices, serialized +operator actions and optional score handoff are now implemented locally; see +[Bundle validation](49-sm32-bundle-actions-validation.md). The subsequent +[live rehearsal](51-sm32-live-validation-report.md) passed: 194 local tests, +manual/automatic decisions, history, conditional score, rollback/retry and +170+10-row inference/no-op for both engines. The user has a pending v5 to practice. [36 misplaced Core test files](44-core-test-relocation.md) were relocated and verified before this continuation. See [the implementation evidence](40-sm30-challenger-validation-report.md): 104 @@ -62,8 +75,8 @@ on an existing candidate without retraining or reuploading the model. | --- | --- | --- | --- | --- | | SM-30 | Challenger nomination and visible evaluation status | Existing SM-22c/29 | DONE | 104 local tests and live run 607409241163605 passed; company tags, both engines, retained contender, replacement, error and rollback verified | | SM-31 | Thin template and reusable workflow/publication services | SM-30 | DONE | 44-line notebook, two Core services, 110 tests, wheel installation/import, strict generation validation and live score run 383572337148835 passed | -| SM-32 | Independent score selection and promotion policy | SM-31 | ACTIVE | Library's four combinations and approve/reject/rollback implemented; remaining: previous_challenger history, serialized Bundle operator actions and score handoff without fit, matching choices and live proof | -| SM-33 | Validated config, migration and runtime parameters | SM-32 | WAIT | Per-run version/action/evidence inputs; task/column/key setup; migrate old mode and reject config/job-graph disagreement | +| SM-32 | Independent score selection and promotion policy | SM-31 | DONE | 194 local tests and personal serverless manual/automatic, approve/reject/rollback/retry, history and score handoff/pin preservation passed; [live evidence](51-sm32-live-validation-report.md) | +| SM-33 | Validated config, migration and runtime parameters | SM-32 | READY | Per-run version/action/evidence inputs; task/column/key setup; migrate old mode and reject config/job-graph disagreement | | SM-34 | Independent score/train schedules and training windows | SM-33 | WAIT | Editable paused score/train cron/timezone, explicit lookback/holdout/label windows; scoring needs no manual dates or retraining | | SM-35 | Multi-metric quality gates and clear thresholds | SM-33 | WAIT | One selection metric plus optional guardrails; task/domain validation, first-model gate, failed-gate explanations and no probability-threshold confusion | | SM-36 | Core tuning, model search and optional explainability | SM-35 | WAIT | Existing Core search/trials and FE reused with budgets, protected holdout, MLflow evidence and selected-model inference parity | diff --git a/mkdocs.yml b/mkdocs.yml index 2e51e287b..d5834a0be 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -41,6 +41,12 @@ plugins: show_source: true show_root_heading: true +markdown_extensions: + - pymdownx.superfences: + custom_fences: + - name: mermaid + class: mermaid + nav: - Home: index.md - Backend: @@ -82,6 +88,7 @@ nav: - Databricks Batch (Development): user_guide/databricks_batch.md - Databricks Local SDK (Development): user_guide/databricks_local_sdk.md - Databricks Local Bundle (Development): user_guide/databricks_bundle.md + - Databricks Bundle Operator Walkthrough: user_guide/databricks_bundle_walkthrough.md - Pipeline Quickstart: user_guide/pipeline_quickstart.md - Step-by-Step (No Config): user_guide/step_by_step_no_config.md - Automated EDA: user_guide/eda_profiling.md diff --git a/skyulf-core/skyulf/integrations/databricks/job_output.py b/skyulf-core/skyulf/integrations/databricks/job_output.py new file mode 100644 index 000000000..304b9a3f4 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/job_output.py @@ -0,0 +1,147 @@ +"""Render shared, escaped operator reports for Bundle notebook results.""" + +import json +from html import escape +from typing import Any + + +def _text(value: Any) -> str: + """Escape dynamic registry, parameter and result values before rendering HTML.""" + return escape(str(value)) + + +def _table(headers: tuple[str, ...], rows: list[tuple[Any, ...]]) -> str: + """Render small comparison and parameter tables without injecting dynamic markup.""" + head = "".join(f"{_text(value)}" for value in headers) + body = "".join( + "" + "".join(f"{_text(value)}" for value in row) + "" for row in rows + ) + return f"{head}{body}
" + + +def render_bundle_output(payload: dict[str, Any]) -> str: + """Present lifecycle, comparison, scoring and next steps with raw JSON in a disclosure. + + The report describes only this task's completed work. A handoff request + does not imply success of the separate score job. No-op manifests describe + the previous prediction write, not the model selected by the current run. + """ + action = payload["action"] + result = payload["result"] + candidate = result.get("candidate", result) + receipt = result.get("alias_change") or result + sections = [f"

{_text(action.replace('_', ' ').title())} completed

"] + kind = receipt.get("kind") + if kind in {"initial", "promotion", "rollback"}: + prior = receipt.get("prior_version") + sections.append( + "

Champion changed: " + f"{_text('v' + prior if prior else 'none')} → " + f"{_text('v' + receipt['new_version'])}

" + ) + elif kind == "rejection": + sections.append("

Candidate rejected. Champion is unchanged.

") + name = candidate.get("model_name") or receipt.get("model_name") + if name: + sections.append(f"

Model: {_text(name)}

") + if action.startswith("train"): + sections.append( + f"

Candidate version: {_text(candidate.get('model_version'))}

" + ) + comparison = candidate.get("comparison", {}) + if comparison: + sections.append( + f"

Decision metric: {_text(comparison['metric'])}
" + f"Eligible: {_text(comparison['eligible'])}
" + f"Reason: {_text(comparison['reason'])}

" + ) + challenger = comparison.get("candidate_metrics", {}) + champion = comparison.get("champion_metrics", {}) + sections.append( + _table( + ("Metric", "Candidate", "Champion"), + [ + (key, value, champion.get(key, "No champion")) + for key, value in challenger.items() + ], + ) + ) + if action == "score": + noop = result.get("noop", False) + sections.append( + "

No new predictions written.

" + if noop + else "

Prediction write completed.

" + ) + sections.append( + _table( + ("Result", "Value"), + [ + (label, result[key]) + for key, label in ( + ("input_count", "Input rows"), + ("output_count", "Output rows"), + ("commit_version", "Prediction table Delta version"), + ) + if key in result + ], + ) + ) + manifest = result.get("manifest", {}) + if manifest: + label = "Model recorded by the previous write" if noop else "Prediction model" + sections.append( + f"

{label}: {_text(manifest.get('model_name'))} " + f"v{_text(manifest.get('model_version'))}

" + ) + elif payload["score_requested"]: + sections.append("

Scoring requested. Check the child score run for its result.

") + else: + sections.append("

This action did not request scoring.

") + for next_action, parameters in payload.get("next_actions", {}).items(): + rollback = next_action == "rollback" + if rollback: + expected = parameters["expected_champion_version"] + sections.append("

If rollback is needed

") + sections.append( + "

You can use the information below to restore the previous champion. " + "Rollback is optional and does not run automatically.

" + ) + sections.append( + _table( + ("Rollback", "Version"), + [ + ("Required current champion", "v" + expected), + ("Restore version", "v" + receipt["prior_version"]), + ], + ) + ) + sections.append( + f"

Rollback proceeds only if champion is still v{_text(expected)}. " + "The expected champion is a safety check, not the restore target.

" + "
Show parameters only if you want to roll back" + ) + else: + sections.append(f"

Available action: {_text(next_action)}

") + sections.append( + "

Use Run with different settings on the same train job. " + "Clear fields not listed below.

" + ) + rows = list(parameters.items()) + if next_action == "reject": + rows.append(("rejection_reason", "Enter your reason")) + sections.append(_table(("Parameter", "Value"), rows)) + if rollback: + sections.append("
") + raw = json.dumps(payload, indent=2, default=str, allow_nan=False) + sections.append( + f"
Technical details (JSON)
{_text(raw)}
" + ) + return ( + '
' + "" + + "".join(sections) + + "
" + ) diff --git a/skyulf-core/skyulf/integrations/databricks/job_runtime.py b/skyulf-core/skyulf/integrations/databricks/job_runtime.py new file mode 100644 index 000000000..6895e38b9 --- /dev/null +++ b/skyulf-core/skyulf/integrations/databricks/job_runtime.py @@ -0,0 +1,246 @@ +"""Adapt Bundle parameters and task values to the existing local workflow services.""" + +import json +import logging +import re +import tempfile +from collections.abc import Callable +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +from ..mlflow.promotion import AliasChangeReceipt +from .job_output import render_bundle_output +from .local_approval import resolve_candidate_comparison_digest +from .local_retraining import LocalCandidateResult +from .local_workflow import ( + AutoTrainingOutcome, + _workflow_policies, + resolve_target_config, + run_action, +) + +_OPERATOR_FIELDS = { + "candidate_version", + "comparison_sha256", + "expected_champion_version", + "rejection_reason", + "promotion_receipt_json", +} + + +@dataclass(frozen=True, slots=True) +class BundleActionResult: + """Expose Core output, optional score handoff and copyable operator inputs.""" + + action: str + result: Any + score_requested: bool + next_actions: dict[str, dict[str, str]] + + +def _version(value: str, *, allow_none: bool = False) -> str | None: + """Require a concrete version or an explicitly chosen bootstrap sentinel.""" + if allow_none and value == "none": + return None + if not re.fullmatch(r"[1-9][0-9]*", value): + raise ValueError("Expected a concrete model version; use none only for bootstrap.") + return value + + +def _operator_options(action: str, values: dict[str, str]) -> dict[str, Any]: + """Reject incomplete and irrelevant operator inputs before any Core side effects.""" + allowed = { + "approve": {"candidate_version", "comparison_sha256", "expected_champion_version"}, + "reject": { + "candidate_version", + "comparison_sha256", + "expected_champion_version", + "rejection_reason", + }, + "rollback": {"promotion_receipt_json", "expected_champion_version"}, + }.get(action, set()) + if any(values.get(key, "") for key in _OPERATOR_FIELDS - allowed): + raise ValueError(f"Unexpected operator parameters for {action}.") + if not allowed: + return {} + expected = _version( + values.get("expected_champion_version", ""), allow_none=action != "rollback" + ) + options: dict[str, Any] = {"expected_champion_version": expected} + if action == "rollback": + try: + payload = json.loads(values.get("promotion_receipt_json", "")) + if not isinstance(payload, dict) or any( + value is not None and not isinstance(value, str) for value in payload.values() + ): + raise ValueError + receipt = AliasChangeReceipt(**payload) + if receipt.kind != "promotion" or receipt.alias != "champion": + raise ValueError + if receipt.new_version != expected or receipt.prior_version is None: + raise ValueError + _version(receipt.prior_version) + except (TypeError, ValueError) as exc: + raise ValueError( + "Rollback needs a complete promotion_receipt_json matching the expected champion." + ) from exc + options["promotion_receipt"] = receipt + return options + options["candidate_version"] = _version(values.get("candidate_version", "")) + digest = values.get("comparison_sha256", "") + if digest and not re.fullmatch(r"[a-f0-9]{64}", digest): + raise ValueError("comparison_sha256 must be empty or an exact 64-character digest.") + options["comparison_sha256"] = digest + if action == "reject": + reason = values.get("rejection_reason", "") + if not reason.strip() or len(reason.encode("utf-8")) > 256: + raise ValueError("Rejection needs a reason of at most 256 UTF-8 bytes.") + options["rejection_reason"] = reason + return options + + +def _next_actions(result: Any, policy: str) -> dict[str, dict[str, str]]: + """Expose the exact evidence accepted by existing Core approval and rollback APIs.""" + actions: dict[str, dict[str, str]] = {} + candidate = result.candidate if isinstance(result, AutoTrainingOutcome) else result + if isinstance(candidate, LocalCandidateResult) and policy == "manual_approval": + for action in ("approve", "reject"): + actions[action] = { + "lifecycle_action": action, + "candidate_version": candidate.model_version, + "expected_champion_version": candidate.comparison.champion_version or "none", + } + receipt = result.alias_change if isinstance(result, AutoTrainingOutcome) else result + if isinstance(receipt, AliasChangeReceipt) and receipt.kind == "promotion": + actions["rollback"] = { + "lifecycle_action": "rollback", + "expected_champion_version": receipt.new_version, + "promotion_receipt_json": json.dumps( + asdict(receipt), sort_keys=True, separators=(",", ":") + ), + } + return actions + + +def run_bundle_action( + spark: Any, + config: dict[str, Any], + parameters: dict[str, str], + *, + task_role: str, + experiment_name: str | None = None, + artifact_path: str | Path | None = None, +) -> BundleActionResult: + """Run one role-bound action; score handoff follows only a successful champion transition. + + Role is fixed by the deployed notebook, never by a run parameter. This is + input isolation, not a substitute for workspace permissions or serialized + writer ownership. A failed Core action produces no success task value. + """ + if "score_model_selection" not in config or "promotion_policy" not in config: + raise ValueError( + "Regenerate the Bundle config and job graph with both independent policies." + ) + _, policy = _workflow_policies(config) + if config.get("score_handoff") not in {"disabled", "after_alias_change"}: + raise ValueError("score_handoff must be disabled or after_alias_change.") + for key in _OPERATOR_FIELDS | {"lifecycle_action", "task_role", "action"}: + if key in parameters and not isinstance(parameters[key], str): + raise ValueError("Job parameters must be strings.") + if parameters.get("task_role") or parameters.get("action"): + raise ValueError("Notebook role and score action cannot be overridden by job parameters.") + if task_role == "score": + if parameters.get("lifecycle_action"): + raise ValueError("Score job refuses lifecycle actions.") + action = "score" + elif task_role == "lifecycle": + action = parameters.get("lifecycle_action", "") + if action not in {"train", "train_monthly", "approve", "reject", "rollback"}: + raise ValueError( + "Lifecycle action must be train, train_monthly, approve, reject or rollback." + ) + else: + raise ValueError("Notebook task_role must be lifecycle or score.") + options = _operator_options(action, parameters) + if action in {"approve", "reject"} and not options["comparison_sha256"]: + options["comparison_sha256"] = resolve_candidate_comparison_digest( + config, options["candidate_version"], action=action + ) + if action in {"train", "train_monthly"}: + options.update(experiment_name=experiment_name, artifact_path=artifact_path) + result = run_action(spark, config, action, **options) + receipt = result.alias_change if isinstance(result, AutoTrainingOutcome) else result + score_requested = ( + config["score_handoff"] == "after_alias_change" + and action in {"train", "train_monthly", "approve", "rollback"} + and isinstance(receipt, AliasChangeReceipt) + and receipt.kind in {"initial", "promotion", "rollback"} + ) + return BundleActionResult(action, result, score_requested, _next_actions(result, policy)) + + +def run_notebook( + spark: Any, + dbutils: Any, + *, + task_role: str, + display_html: Callable[[str], Any] | None = None, + exit_notebook: bool = True, +) -> str: + """Run the fixed role and render results, optionally deferring the notebook exit. + + Generated notebooks defer exit to a separate cell: Databricks otherwise + replaces the readable report with the exit value in the same cell. + """ + values = dbutils.widgets.getAll() + # Databricks pushes parent job parameters into Run Job children. The score + # entrypoint ignores inherited lifecycle evidence and always dispatches score. + # Keep role/action override guards; only lifecycle fields are discarded here. + parameters = ( + { + key: value + for key, value in values.items() + if key not in _OPERATOR_FIELDS | {"lifecycle_action"} + } + if task_role == "score" + else values + ) + config = json.loads(Path(values["config_path"]).read_text(encoding="utf-8")) + config = resolve_target_config( + config, + { + name: values[name] + for name in ( + "catalog", + "input_schema", + "output_schema", + "metadata_schema", + "resource_suffix", + ) + }, + ) + with tempfile.TemporaryDirectory(prefix="skyulf-bundle-") as directory: + outcome = run_bundle_action( + spark, + config, + parameters, + task_role=task_role, + experiment_name=values.get("experiment_name"), + artifact_path=Path(directory) / "artifact", + ) + payload = asdict(outcome) + output = json.dumps(payload, default=str, allow_nan=False) + if task_role == "lifecycle": + dbutils.jobs.taskValues.set(key="score_requested", value=outcome.score_requested) + if display_html is not None: + try: + display_html(render_bundle_output(payload)) + except Exception: # noqa: BLE001 - a display failure must not invite alias mutation retries + logging.getLogger(__name__).warning("Readable output unavailable; see JSON result.") + print(json.dumps(payload, indent=2, default=str, allow_nan=False)) + else: + print(json.dumps(payload, indent=2, default=str, allow_nan=False)) + if exit_notebook: + dbutils.notebook.exit(output) + return output diff --git a/skyulf-core/skyulf/integrations/databricks/local_approval.py b/skyulf-core/skyulf/integrations/databricks/local_approval.py index 06a5198fd..a24528a54 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_approval.py +++ b/skyulf-core/skyulf/integrations/databricks/local_approval.py @@ -35,6 +35,51 @@ from .local_retraining import LocalTrainingSpec +def resolve_candidate_comparison_digest( + config: dict[str, Any], candidate_version: str, *, action: str +) -> str: + """Resolve a named candidate's proof from its active committed lifecycle receipt. + + This is the Bundle convenience path, not a latest-candidate lookup. The + strict approval/rejection service still verifies the downloaded comparison, + expected champion and active receipt against the full returned digest. + """ + if config.get("promotion_policy") != "manual_approval" or action not in {"approve", "reject"}: + raise ValueError("Evidence lookup requires manual_approval and approve/reject.") + if not isinstance(candidate_version, str) or not re.fullmatch( + r"[1-9][0-9]*", candidate_version + ): + raise ValueError("Evidence lookup requires a concrete candidate_version.") + tracking_uri = config.get("tracking_uri", "databricks") + registry_uri = config.get("registry_uri", "databricks-uc") + name = config["model_name"] + current = controlled_champion_version( + name, tracking_uri=tracking_uri, registry_uri=registry_uri + ) + client = _make_client(_require_mlflow(), tracking_uri, registry_uri) + replay = action == "approve" and current == candidate_version + alias = "champion" if replay else "challenger" + event_id = _active_marker(client, name, candidate_version, alias) + if event_id is None: + raise AliasConflictError("Candidate has no active saved comparison receipt.") + raw = (client.get_model_version(name, candidate_version).tags or {}).get(_event_tag(event_id)) + try: + event = _read_event(raw) + except (TypeError, ValueError) as exc: + raise AliasConflictError("Saved comparison receipt is malformed.") from exc + kinds = {"initial", "promotion"} if replay else {"challenger"} + if action == "approve" and isinstance(event, dict) and event.get("k") == "rejection": + raise AliasConflictError("Candidate was explicitly rejected.") + if action == "reject": + kinds.add("rejection") + if not isinstance(event, dict) or event.get("s") != "committed" or event.get("k") not in kinds: + raise AliasConflictError("Candidate has no committed comparison for this action.") + digest = event.get("h") + if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest): + raise AliasConflictError("Saved comparison receipt has no valid digest.") + return digest + + def _load_evidence( client: Any, name: str, version: str, digest: str ) -> tuple[ModelComparisonReport, LocalTrainingSpec, str]: diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py index d047036a7..83082aaea 100644 --- a/skyulf-core/skyulf/integrations/mlflow/promotion.py +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -33,6 +33,8 @@ _ALIAS = "champion" _CHALLENGER = "challenger" _PREVIOUS = "previous_champion" +_HISTORY = "previous_challenger" +_HISTORY_TAG = "previous_challenger_current_event" _ACTIVE_TAG = "champion_current_event" _CHALLENGER_TAG = "challenger_current_event" _PENDING_TAG = "pending_alias_event" @@ -181,6 +183,93 @@ def _assert_no_pending(client: Any, name: str) -> None: tags = client.get_registered_model(name).tags or {} if tags.get(_PENDING_TAG): raise AliasConflictError("A pending alias event requires reconciliation.") + _read_challenger_history(client, name) + + +def _read_challenger_history(client: Any, name: str) -> str | None: + """Verify the history pointer, including an explicitly cleared pointer's receipt.""" + current = _read_optional_alias(client, name, _HISTORY) + raw = (client.get_registered_model(name).tags or {}).get(_HISTORY_TAG) + if raw is None: + if current is not None: + raise AliasConflictError("Challenger history alias lacks a controlled receipt.") + return None + try: + marker = json.loads(raw) + if ( + not isinstance(marker, dict) + or not isinstance(marker.get("event_id"), str) + or not marker["event_id"] + or not isinstance(marker.get("version"), str) + or not marker["version"].isascii() + or not marker["version"].isdigit() + ): + raise ValueError + tags = client.get_model_version(name, marker["version"]).tags or {} + history = json.loads(tags[f"challenger_history_{marker['event_id']}"]) + event = _read_event(tags[_event_tag(marker["event_id"])]) + if ( + history["state"] != "committed" + or event["s"] != "committed" + or history["to_version"] != current + or event["k"] not in {"nomination", "challenger", "initial", "promotion", "rollback"} + ): + raise ValueError + if current is not None: + if event["k"] not in {"nomination", "challenger"} or event["p"] != current: + raise ValueError + if current in { + _read_optional_alias(client, name, _ALIAS), + _read_optional_alias(client, name, _CHALLENGER), + }: + raise ValueError + elif history["from_version"] != marker["version"]: + raise ValueError + except (TypeError, ValueError, KeyError) as exc: + raise AliasConflictError( + "Challenger history disagrees with its committed receipt." + ) from exc + return current + + +def _plan_challenger_history( + client: Any, receipt: AliasChangeReceipt, updates: list[tuple[str, str | None, str | None]] +) -> tuple[str | None, str | None] | None: + """Archive only displaced contenders and clear history when it becomes a current role.""" + previous = _read_challenger_history(client, receipt.model_name) + desired = previous + champion = _read_optional_alias(client, receipt.model_name, _ALIAS) + challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) + for alias, new_version, old_version in updates: + if alias == _ALIAS: + champion = new_version + elif alias == _CHALLENGER: + challenger = new_version + if new_version is not None and old_version is not None and new_version != old_version: + _checked_challenger_event(client, receipt.model_name, old_version) + desired = old_version + if desired in {champion, challenger}: + desired = None + return (previous, desired) if previous != desired else None + + +def _write_challenger_history( + client: Any, + receipt: AliasChangeReceipt, + change: tuple[str | None, str | None], + status: str, +) -> None: + """Persist history intent separately to preserve the existing bounded receipt format.""" + value = json.dumps( + {"from_version": change[0], "to_version": change[1], "state": status}, + sort_keys=True, + separators=(",", ":"), + ) + if len(value.encode("utf-8")) > 256: + raise ValueError("Challenger history exceeds the 256-byte tag value limit.") + client.set_model_version_tag( + receipt.model_name, receipt.new_version, f"challenger_history_{receipt.event_id}", value + ) def _assert_not_rejected(client: Any, name: str, version: str) -> None: @@ -207,6 +296,7 @@ def controlled_champion_version( tags = registered.tags or {} if tags.get(_PENDING_TAG): raise AliasConflictError("A pending alias event requires reconciliation.") + _read_challenger_history(client, model_name) current = _read_optional_alias(client, model_name, _ALIAS) if current is None: if tags.get(_ACTIVE_TAG): @@ -329,6 +419,9 @@ def _commit_change( failures are reported as unknown and require reconciliation before retry. """ _assert_no_pending(client, receipt.model_name) + history = _plan_challenger_history(client, receipt, updates) + if history is not None: + updates = [*updates, (_HISTORY, history[1], history[0])] try: _write_event(client, receipt, "prepared") except Exception as exc: # noqa: BLE001 - registry transport boundary @@ -342,6 +435,13 @@ def _commit_change( raise AliasOutcomeUnknownError( f"Alias preparation outcome unknown; inspect event {receipt.event_id}." ) from exc + if history is not None: + try: + _write_challenger_history(client, receipt, history, "prepared") + except Exception as exc: # noqa: BLE001 - pending history requires reconciliation + raise AliasOutcomeUnknownError( + f"History preparation outcome unknown; inspect event {receipt.event_id}." + ) from exc changed = False for alias, new_version, old_version in updates: try: @@ -381,6 +481,14 @@ def _commit_change( if any(stored.get(key) != value for key, value in tags.items()): raise AliasOutcomeUnknownError("Model version status was not verified.") _write_event(client, receipt, "committed") + if history is not None: + _write_challenger_history(client, receipt, history, "committed") + client.set_registered_model_tag( + receipt.model_name, + _HISTORY_TAG, + json.dumps({"event_id": receipt.event_id, "version": receipt.new_version}), + ) + _read_challenger_history(client, receipt.model_name) tag = _ACTIVE_TAG if receipt.alias == _ALIAS else _CHALLENGER_TAG client.set_registered_model_tag( receipt.model_name, diff --git a/skyulf-core/templates/databricks/databricks_template_schema.json b/skyulf-core/templates/databricks/databricks_template_schema.json index 98731a431..b1f0d38c9 100644 --- a/skyulf-core/templates/databricks/databricks_template_schema.json +++ b/skyulf-core/templates/databricks/databricks_template_schema.json @@ -36,35 +36,47 @@ "description": "Keep old predictions and append new rows, or rebuild all rows into a new model-version generation", "enum": ["incremental_append", "full_rebuild"] }, - "model_selection_mode": { + "score_model_selection": { "order": 16, "type": "string", "default": "pinned_version", - "description": "Pin one model version manually or select champion after a gated training run", - "enum": ["pinned_version", "auto_champion"] + "description": "Score with one pinned version or resolve the controlled champion on each run", + "enum": ["pinned_version", "champion"] }, - "metric": { + "promotion_policy": { "order": 17, "type": "string", + "default": "manual_approval", + "description": "Require operator approval or promote automatically after quality gates pass", + "enum": ["manual_approval", "automatic"] + }, + "score_handoff": { + "order": 18, + "type": "string", + "default": "disabled", + "description": "Optionally run the existing score job after champion initialization, promotion or rollback; score keeps its selected model policy", + "enum": ["disabled", "after_alias_change"] + }, + "metric": { + "order": 19, + "type": "string", "default": "heldout_rmse", "description": "Heldout metric for candidate/champion comparison; must match the model task", "enum": ["heldout_mae", "heldout_mse", "heldout_rmse", "heldout_r2", "heldout_mape", "heldout_explained_variance", "heldout_accuracy", "heldout_balanced_accuracy", "heldout_precision_weighted", "heldout_recall_weighted", "heldout_f1_weighted", "heldout_matthews_corrcoef", "heldout_precision", "heldout_recall", "heldout_f1", "heldout_g_score", "heldout_log_loss", "heldout_roc_auc", "heldout_pr_auc", "heldout_roc_auc_ovr_weighted", "heldout_roc_auc_weighted", "heldout_roc_auc_ovr", "heldout_roc_auc_ovo", "heldout_roc_auc_ovo_weighted", "heldout_pr_auc_weighted"] }, "min_improvement": { - "order": 18, + "order": 20, "type": "number", "default": 0.0, "minimum": 0, - "description": "Minimum metric improvement over champion; ties never pass", - "skip_prompt_if": {"properties": {"model_selection_mode": {"const": "pinned_version"}}} + "description": "Minimum metric improvement required for manual or automatic promotion; ties never pass" }, "quality_threshold": { - "order": 19, + "order": 21, "type": "string", "default": "null", - "description": "Enter a numeric absolute heldout gate for the first champion; null is rejected in automatic mode", - "pattern": "^(null|-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)$", - "skip_prompt_if": {"properties": {"model_selection_mode": {"const": "pinned_version"}}} + "description": "Absolute quality gate; numeric required for automatic promotion or manual first-champion approval. Choose for your metric and task.", + "pattern": "^(null|-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)$" }, "retraining_cron_expression": { "order": 14, @@ -140,7 +152,7 @@ "skip_prompt_if": {"properties": {"compute_mode": {"const": "serverless"}}} }, "risk_category": { - "order": 20, + "order": 22, "type": "string", "default": "", "description": "Optional business risk label (e.g. Low, Medium, High); leave blank when unused. This label does not change promotion gates.", diff --git a/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json b/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json index de6b2bc58..517a90d7a 100644 --- a/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json +++ b/skyulf-core/templates/databricks/examples/paying-reg-no-init.example.json @@ -4,7 +4,9 @@ "row_key": "customer_id", "retraining_mode": "manual", "model_change_mode": "incremental_append", - "model_selection_mode": "pinned_version", + "score_model_selection": "pinned_version", + "promotion_policy": "manual_approval", + "score_handoff": "disabled", "compute_mode": "policy_cluster", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", diff --git a/skyulf-core/templates/databricks/examples/policy-init.example.json b/skyulf-core/templates/databricks/examples/policy-init.example.json index e878bece0..df0fd0db4 100644 --- a/skyulf-core/templates/databricks/examples/policy-init.example.json +++ b/skyulf-core/templates/databricks/examples/policy-init.example.json @@ -4,7 +4,9 @@ "row_key": "entity_id", "retraining_mode": "manual", "model_change_mode": "incremental_append", - "model_selection_mode": "pinned_version", + "score_model_selection": "pinned_version", + "promotion_policy": "manual_approval", + "score_handoff": "disabled", "compute_mode": "policy_cluster", "catalog": "REPLACE_DEV_CATALOG", "schema": "REPLACE_DEV_SCHEMA", diff --git a/skyulf-core/templates/databricks/examples/serverless-init.example.json b/skyulf-core/templates/databricks/examples/serverless-init.example.json index dd7e5e895..7b5b4be42 100644 --- a/skyulf-core/templates/databricks/examples/serverless-init.example.json +++ b/skyulf-core/templates/databricks/examples/serverless-init.example.json @@ -4,7 +4,9 @@ "row_key": "customer_id", "retraining_mode": "manual", "model_change_mode": "incremental_append", - "model_selection_mode": "pinned_version", + "score_model_selection": "pinned_version", + "promotion_policy": "manual_approval", + "score_handoff": "disabled", "compute_mode": "serverless", "catalog": "workspace", "schema": "my_dev_schema" diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl index 645a71795..f0a8b0bde 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/README.md.tmpl @@ -7,9 +7,9 @@ same Skyulf workflow code with different target bindings. ## What deployment creates -`src/workflow.py` is a thin widget/JSON entry point. Common behavior is provided -by the installed `skyulf.integrations.databricks.local_workflow` and -`prediction_output` modules. Customize your preprocessing/model pipeline in +`src/workflow.py` and `src/score.py` are thin, fixed-role entry points. The +installed `job_runtime` adapter handles widgets/JSON and calls Core's existing +`local_workflow` and `prediction_output` services. Customize your pipeline in `config/workflow.json`; common workflow changes belong in the Skyulf wheel. `bundle deploy` uploads the wheel, notebook and configuration, and creates @@ -19,7 +19,7 @@ schedule to the existing `train` job; the default `manual` choice adds none. | Job | Run it when | UC effect | | --- | --- | --- | -| `train` | Labeled data is ready or the schedule runs | Registers and nominates a challenger; logs metrics and evaluation status | +| `train` | Train, approve, reject or roll back using `lifecycle_action` | Training registers a candidate; operator actions reuse existing versions | | `score` | A model is pinned and rows need scoring | Appends rows or builds a new generation | In both selection modes, each registered contender becomes `@challenger` @@ -41,27 +41,62 @@ your company and provide the approved number as the cost tag value. The complete dataset identity is in the run's training_data.json artifact. Technical promotion event tags contain recovery receipts; do not edit them. -{{if eq .model_selection_mode "auto_champion"}} -This project uses automatic champion selection. `train` compares a candidate -against champion on a pinned temporal holdout. The first champion needs a -numeric absolute `quality_threshold`; later candidates need strictly positive -improvement that meets `min_improvement`. A passing candidate is staged then -promoted through checked registry receipts. A failed candidate leaves champion -unchanged. The train job calls the existing score job after it succeeds. - -Score resolves `@champion` once to a concrete version at run start. Alias -promotion and Delta publication are separate transactions. If scoring fails -after promotion, retry `score`; the previous successful prediction output -remains until a new score completes. An -unknown alias-write outcome leaves a pending marker and blocks later automatic -training and scoring until registry receipt reconciliation. An existing -`@champion` set outside Skyulf's guarded promotion path has no committed -receipt and must be reconciled before automatic mode can use it. -{{else}} -Training records challenger status but never promotes it or activates it for -scoring. Set `model_version` to a concrete registered version and redeploy -when you want scoring to use it. -{{end}} +## Model selection and operator actions + +This project uses `score_model_selection={{.score_model_selection}}`, +`promotion_policy={{.promotion_policy}}`, and `score_handoff={{.score_handoff}}`. +These choices remain editable in `config/workflow.json`. + +| Setting | Choices | +| --- | --- | +| `score_model_selection` | `pinned_version` keeps `model_version`; `champion` resolves the controlled alias once per score run | +| `promotion_policy` | `manual_approval` waits for an operator; `automatic` promotes only after quality gates pass | +| `score_handoff` | `disabled`, or `after_alias_change` to call the existing score job after champion initialization, promotion or rollback | + +All four selector/promotion combinations are supported. Promotion never rewrites +a scoring pin. A first champion requires a numeric absolute `quality_threshold`, +including manual approval; subsequent candidates also need positive improvement +meeting `min_improvement`. Configure the metric and gates for your task before fit. + +Use the **train job's Run now parameters** for every lifecycle action. It is +queued with one active run, so operator actions share training's writer. + +| `lifecycle_action` | Additional parameters | +| --- | --- | +| `train` / `train_monthly` | Leave operator evidence fields empty | +| `approve` | `candidate_version`, `expected_champion_version` | +| `reject` | Same evidence plus `rejection_reason` | +| `rollback` | `promotion_receipt_json`, `expected_champion_version` | + +Training output contains `next_actions.approve` and `next_actions.reject` in +manual mode. Copy the relevant fields, adding a reason for rejection. Explicit +`none` is used for a first champion; blank is not accepted. A completed promotion +returns `next_actions.rollback`, including a ready-to-copy receipt JSON string. +Copy that string's value into `promotion_receipt_json`; do not edit receipt fields. +Approval/rejection resolves the full comparison digest from the named model +version's committed receipt. You do not copy a hash. Missing/stale evidence and +changed comparison artifacts still fail the strict Core checks. Older callers +can continue supplying `comparison_sha256` explicitly. +The executed notebook shows a readable summary and next-action parameter tables; +expand Technical details for JSON. The standard Notebook exited JSON is retained +for API consumers. A no-op manifest describes the previous prediction write. +Initial champion creation has no prior champion and cannot be rolled back. +Clear fields unrelated to the selected action. All prior evidence is verified +against the registry; changing an alias directly in Catalog UI is not approval. + +Operator actions never retrain/register/upload another model. A retry of the +same still-current committed operation returns its receipt. Rejected or tied +candidates do not trigger score. Manual training also waits for approval. +With handoff enabled, a completed champion change triggers score using the +configured selector, including an unchanged pinned version if selected. +The score notebook has a fixed score role. It ignores inherited lifecycle +parameters from the parent job and rejects role/action override attempts. + +Handoff and Delta publication remain separate operations. If score fails, +retry the independent score job or repair only the handoff task; do not rerun +training. An unknown alias write leaves a pending marker requiring reconciliation. +`previous_challenger` retains displaced candidates and clears if that version +becomes champion/challenger again. Model versions and evidence remain available. In monthly mode, the schedule starts paused. Its Quartz cron and IANA timezone are selected at initialization and remain editable as @@ -80,8 +115,7 @@ The run compares against the concrete version behind `@champion` if present; a missing alias means first-model training. An explicit `champion_version` must match the current champion or training fails before fit. Registry access failures still fail the job. Retry runs can create additional candidate versions. -{{if eq .model_selection_mode "pinned_version"}}None is promoted or used by -`score` automatically.{{end}} +Manual approval mode retains the candidate until a separate operator action. `training_table` is the existing labeled input. `score_source_table` is the existing input to predict; the generated config points both at **one table**. @@ -154,14 +188,10 @@ clusters are a separate compute choice at project initialization. 1. Run `train` against a pinned labeled Delta version. It logs held-out MLflow metrics and registers a concrete model version. -{{if eq .model_selection_mode "auto_champion"}} -2. The train job evaluates the candidate and calls the existing score job. - Inspect both task results. The first score requires a champion that passed - the absolute threshold. -{{else}} -2. Put that concrete version in `model_version` in `config/workflow.json` and - redeploy. Run `score`. -{{end}} +2. In manual mode, approve the existing candidate if champion-based scoring + is desired. Pinned scoring instead uses the explicit `model_version`; + update and redeploy that config to change its pin. Run `score` independently, + or inspect the optional handoff following a successful champion transition. Scoring verifies the source, Change Data Feed, model outputs, row keys and any existing target schema before writing. It creates only a missing physical prediction table; it never overwrites an existing @@ -173,13 +203,13 @@ clusters are a separate compute choice at project initialization. is entered for each run. Source updates or deletes require a separate rescore policy. -{{if eq .model_selection_mode "pinned_version"}} +{{if eq .score_model_selection "pinned_version"}} `score` always uses its configured concrete model version. Training a new candidate or changing a registry alias alone does not change predictions. {{else}} `score` loads the concrete champion version at run start. A later alias change -cannot alter that run's pinned model. The train job invokes scoring after -selection; score remains independently runnable for new source rows. +cannot alter that run's pinned model. Score remains independently runnable +for new source rows, regardless of the configured handoff choice. {{end}} After pinning v2 and redeploying, `incremental_append` leaves v1 rows intact and scores only new source inserts with v2. `full_rebuild` scores every current @@ -187,6 +217,5 @@ source row into a new v2 table, switches the view only after success, then uses that table's Delta receipt to append future inserts. A failed rebuild leaves the old view active. The new generation must retain the active output schema; an incompatible model needs a new logical view or an explicit migration. -{{if eq .model_selection_mode "pinned_version"}}The optional training schedule -does not run `score`.{{end}} There is no online +The training schedule uses the same promotion and handoff choices. There is no online endpoint or Spark-native FE/model execution in this starting project. diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl index 6dd0d603a..55f043c94 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/config/workflow.json.tmpl @@ -8,7 +8,9 @@ "model_name": "{catalog}.{metadata_schema}.{{.project_name}}_model{resource_suffix}", "model_version": "1", "model_change_mode": "{{.model_change_mode}}", - "model_selection_mode": "{{.model_selection_mode}}", + "score_model_selection": "{{.score_model_selection}}", + "promotion_policy": "{{.promotion_policy}}", + "score_handoff": "{{.score_handoff}}", "champion_version": null, "risk_category": {{if .risk_category}}"{{.risk_category}}"{{else}}null{{end}}, "row_keys": ["{{.row_key}}"], @@ -23,7 +25,7 @@ "max_bytes": 67108864, "metric": "{{.metric}}", "min_improvement": {{.min_improvement}}, - "quality_threshold": {{if eq .model_selection_mode "auto_champion"}}{{.quality_threshold}}{{else}}null{{end}}, + "quality_threshold": {{.quality_threshold}}, "pipeline": { "preprocessing": [], "modeling": {"type": "linear_regression"} diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl index a5548ab0e..69f4f81db 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/databricks.yml.tmpl @@ -9,6 +9,7 @@ sync: - dist/*.whl - config/workflow.json - src/workflow.py + - src/score.py variables: catalog: diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl index 335ab018b..c8c91d3b7 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/resources/workflow.jobs.yml.tmpl @@ -5,6 +5,17 @@ resources: max_concurrent_runs: 1 queue: enabled: true + parameters: + - name: lifecycle_action + default: {{if eq .retraining_mode "monthly_paused"}}train_monthly{{else}}train{{end}} + - name: candidate_version + default: "" + - name: expected_champion_version + default: "" + - name: rejection_reason + default: "" + - name: promotion_receipt_json + default: "" {{if eq .retraining_mode "monthly_paused"}} schedule: quartz_cron_expression: ${var.retraining_cron_expression} @@ -16,7 +27,11 @@ resources: notebook_task: notebook_path: ../src/workflow.py base_parameters: - action: {{if eq .retraining_mode "monthly_paused"}}train_monthly{{else}}train{{end}} + lifecycle_action: '{{"{{job.parameters.lifecycle_action}}"}}' + candidate_version: '{{"{{job.parameters.candidate_version}}"}}' + expected_champion_version: '{{"{{job.parameters.expected_champion_version}}"}}' + rejection_reason: '{{"{{job.parameters.rejection_reason}}"}}' + promotion_receipt_json: '{{"{{job.parameters.promotion_receipt_json}}"}}' config_path: ${workspace.file_path}/config/workflow.json experiment_name: ${workspace.root_path}/experiment catalog: ${var.catalog} @@ -33,13 +48,19 @@ resources: - pypi: package: mlflow==3.16.1 {{end}} -{{if eq .model_selection_mode "auto_champion"}} - - task_key: score_after_training + - task_key: should_score depends_on: - task_key: train + condition_task: + op: EQUAL_TO + left: '{{"{{tasks.train.values.score_requested}}"}}' + right: "true" + - task_key: score_after_lifecycle + depends_on: + - task_key: should_score + outcome: "true" run_job_task: job_id: ${resources.jobs.score.id} -{{end}} {{if eq .compute_mode "serverless"}} environments: - environment_key: skyulf @@ -69,9 +90,8 @@ resources: tasks: - task_key: score notebook_task: - notebook_path: ../src/workflow.py + notebook_path: ../src/score.py base_parameters: - action: score config_path: ${workspace.file_path}/config/workflow.json catalog: ${var.catalog} input_schema: ${var.input_schema} diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/src/score.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/score.py new file mode 100644 index 000000000..b1b4f01da --- /dev/null +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/src/score.py @@ -0,0 +1,18 @@ +# Databricks notebook source +"""Run scoring with a fixed role that cannot dispatch lifecycle mutations.""" + +from skyulf.integrations.databricks.job_runtime import run_notebook + +if __name__ == "__main__": + output = run_notebook( + globals()["spark"], + globals()["dbutils"], + task_role="score", + display_html=globals().get("displayHTML"), + exit_notebook=False, + ) + +# COMMAND ---------- + +if __name__ == "__main__": + globals()["dbutils"].notebook.exit(output) diff --git a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py index 459cde28b..0995901d9 100644 --- a/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py +++ b/skyulf-core/templates/databricks/template/{{.project_name}}/src/workflow.py @@ -1,44 +1,18 @@ # Databricks notebook source -"""Read job settings and call the installed Skyulf workflow services.""" +"""Run lifecycle actions through the installed Skyulf job adapter.""" -import json -import tempfile -from dataclasses import asdict -from pathlib import Path +from skyulf.integrations.databricks.job_runtime import run_notebook -from skyulf.integrations.databricks.local_workflow import resolve_target_config, run_action - - -def main() -> None: - """Read deployed configuration and job widgets only at the notebook boundary.""" - widgets = globals()["dbutils"].widgets - config = json.loads(Path(widgets.get("config_path")).read_text(encoding="utf-8")) - config = resolve_target_config( - config, - { - name: widgets.get(name) - for name in ( - "catalog", - "input_schema", - "output_schema", - "metadata_schema", - "resource_suffix", - ) - }, +if __name__ == "__main__": + output = run_notebook( + globals()["spark"], + globals()["dbutils"], + task_role="lifecycle", + display_html=globals().get("displayHTML"), + exit_notebook=False, ) - action = widgets.get("action") - with tempfile.TemporaryDirectory(prefix="skyulf-bundle-") as directory: - result = run_action( - globals()["spark"], - config, - action, - experiment_name=widgets.get("experiment_name") if action.startswith("train") else None, - artifact_path=Path(directory) / "artifact" if action.startswith("train") else None, - ) - output = json.dumps(asdict(result), default=str, allow_nan=False) - print(output) - globals()["dbutils"].notebook.exit(output) +# COMMAND ---------- if __name__ == "__main__": - main() + globals()["dbutils"].notebook.exit(output) diff --git a/skyulf-core/tests/integrations/test_databricks_bundle_generation.py b/skyulf-core/tests/integrations/test_databricks_bundle_generation.py new file mode 100644 index 000000000..3ad060daf --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_bundle_generation.py @@ -0,0 +1,115 @@ +"""Opt-in real CLI generation checks for the deployable two-job operator graph.""" + +import json +import os +import shutil +import subprocess +from pathlib import Path + +import pytest +import yaml + +PROFILE = os.environ.get("SKYULF_BUNDLE_CLI_TEST_PROFILE") +CLI = shutil.which("databricks") +pytestmark = pytest.mark.skipif( + not PROFILE or not CLI, + reason="Set SKYULF_BUNDLE_CLI_TEST_PROFILE to explicitly opt into installed CLI generation.", +) + + +@pytest.mark.parametrize("selection", ["pinned_version", "champion"]) +@pytest.mark.parametrize("policy", ["manual_approval", "automatic"]) +@pytest.mark.parametrize("handoff", ["disabled", "after_alias_change"]) +@pytest.mark.parametrize("compute", ["serverless", "policy_cluster"]) +def test_cli_emits_independent_policies_and_serialized_operator_graph( + tmp_path, selection, policy, handoff, compute +): + """Render real Go templates so broken dynamic references or job dependencies cannot hide.""" + root = Path(__file__).resolve().parents[2] / "templates/databricks" + schema = json.loads((root / "databricks_template_schema.json").read_text()) + values = {key: spec["default"] for key, spec in schema["properties"].items()} + monthly = handoff == "after_alias_change" + values.update( + project_name="sm32_generated", + score_model_selection=selection, + promotion_policy=policy, + score_handoff=handoff, + compute_mode=compute, + engine="polars" if policy == "automatic" else "pandas", + quality_threshold="100.0", + retraining_mode="monthly_paused" if monthly else "manual", + ) + inputs = tmp_path / "init.json" + inputs.write_text(json.dumps(values), encoding="utf-8") + generated = subprocess.run( + [ + str(CLI), + "bundle", + "init", + str(root), + "--config-file", + str(inputs), + "--output-dir", + str(tmp_path / "output"), + "--profile", + str(PROFILE), + ], + capture_output=True, + text=True, + timeout=60, + ) + assert generated.returncode == 0, generated.stdout + generated.stderr + project = tmp_path / "output" / "sm32_generated" + jobs = yaml.safe_load((project / "resources/workflow.jobs.yml").read_text())["resources"][ + "jobs" + ] + config = json.loads((project / "config/workflow.json").read_text()) + assert set(jobs) == {"train", "score"} + for job in jobs.values(): + assert job["max_concurrent_runs"] == 1 and job["queue"]["enabled"] is True + tasks = {task["task_key"]: task for task in jobs["train"]["tasks"]} + assert set(tasks) == {"train", "should_score", "score_after_lifecycle"} + assert tasks["should_score"]["depends_on"] == [{"task_key": "train"}] + assert tasks["should_score"]["condition_task"] == { + "op": "EQUAL_TO", + "left": "{{tasks.train.values.score_requested}}", + "right": "true", + } + assert tasks["score_after_lifecycle"]["depends_on"] == [ + {"task_key": "should_score", "outcome": "true"} + ] + assert tasks["score_after_lifecycle"]["run_job_task"] == { + "job_id": "${resources.jobs.score.id}" + } + defaults = {item["name"]: item["default"] for item in jobs["train"]["parameters"]} + assert defaults["lifecycle_action"] == ("train_monthly" if monthly else "train") + assert set(defaults) == { + "lifecycle_action", + "candidate_version", + "expected_champion_version", + "rejection_reason", + "promotion_receipt_json", + } + parameters = tasks["train"]["notebook_task"]["base_parameters"] + for name in defaults: + assert parameters[name] == "{{job.parameters." + name + "}}" + score_task = jobs["score"]["tasks"][0] + assert score_task["notebook_task"]["notebook_path"] == "../src/score.py" + assert "lifecycle_action" not in score_task["notebook_task"]["base_parameters"] + assert "parameters" not in jobs["score"] + assert (project / "src/score.py").is_file() + assert config["score_model_selection"] == selection + assert config["promotion_policy"] == policy + assert config["score_handoff"] == handoff + assert config["quality_threshold"] == 100.0 # Manual gates must not be erased. + assert "model_selection_mode" not in config + if monthly: + assert jobs["train"]["schedule"]["pause_status"] == "PAUSED" + else: + assert "schedule" not in jobs["train"] + if compute == "serverless": + assert tasks["train"]["environment_key"] == "skyulf" + assert "job_clusters" not in jobs["train"] + else: + assert tasks["train"]["job_cluster_key"] == "skyulf" + assert "environments" not in jobs["train"] diff --git a/skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py b/skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py index 6488e9aa8..4e36c13ec 100644 --- a/skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py +++ b/skyulf-core/tests/integrations/test_databricks_bundle_lifecycle.py @@ -1,12 +1,9 @@ """Exercise generated lifecycle orchestration against a real local MLflow store.""" -import importlib.util -from pathlib import Path - import pandas as pd import pytest -from skyulf.integrations.databricks import local_retraining, local_workflow +from skyulf.integrations.databricks import job_runtime, local_retraining, local_workflow mlflow = pytest.importorskip("mlflow") @@ -17,13 +14,6 @@ def test_bundle_nomination_comparison_and_promotion_are_separate( tmp_path, monkeypatch, engine, selection ): """Real artifacts must retain a tied contender and survive failed comparison on either engine.""" - path = Path(__file__).resolve().parents[2] / ( - "templates/databricks/template/{{.project_name}}/src/workflow.py" - ) - spec = importlib.util.spec_from_file_location("sm30_workflow", path) - assert spec is not None and spec.loader is not None - workflow = importlib.util.module_from_spec(spec) - spec.loader.exec_module(workflow) frame = pd.DataFrame( { "id": range(12), @@ -47,6 +37,7 @@ def test_bundle_nomination_comparison_and_promotion_are_separate( "registry_uri": store, "score_model_selection": selection, "promotion_policy": "automatic", + "score_handoff": "after_alias_change", "model_version": "1", "row_keys": ["id"], "input_columns": ["x"], @@ -72,13 +63,16 @@ def test_bundle_nomination_comparison_and_promotion_are_separate( def run(version): """Use the exact template action with only its Spark input boundary replaced.""" - return workflow.run_action( + outcome = job_runtime.run_bundle_action( None, config, - "train", + {"lifecycle_action": "train"}, + task_role="lifecycle", experiment_name="lifecycle", artifact_path=tmp_path / f"model-{version}", ) + assert outcome.score_requested == (version in {1, 2}) + return outcome.result first = run(1) assert first.alias_change.kind == "initial" diff --git a/skyulf-core/tests/integrations/test_databricks_bundle_notebook.py b/skyulf-core/tests/integrations/test_databricks_bundle_notebook.py index 5d25f95c4..2ef89bcb6 100644 --- a/skyulf-core/tests/integrations/test_databricks_bundle_notebook.py +++ b/skyulf-core/tests/integrations/test_databricks_bundle_notebook.py @@ -1,7 +1,7 @@ """A generated notebook must delegate behavior to the installed Core library.""" -import importlib.util import json +import runpy from dataclasses import dataclass from pathlib import Path from types import SimpleNamespace @@ -11,23 +11,27 @@ @pytest.mark.parametrize("engine", ["pandas", "polars"]) -@pytest.mark.parametrize("action", ["train", "train_monthly", "score"]) +@pytest.mark.parametrize( + "action", ["train", "train_monthly", "score", "score_from_approve", "score_from_rollback"] +) def test_notebook_delegates_bound_target_and_selected_action(tmp_path, monkeypatch, engine, action): """All widget actions must use the public library while preserving engine and target binding.""" - from skyulf.integrations.databricks import local_workflow + from skyulf.integrations.databricks import job_runtime + inherited_action = ( + action.removeprefix("score_from_") if action.startswith("score_from_") else None + ) + action = "score" if inherited_action else action path = ( Path(__file__).resolve().parents[2] - / "templates/databricks/template/{{.project_name}}/src/workflow.py" + / "templates/databricks/template/{{.project_name}}/src" + / ("score.py" if action == "score" else "workflow.py") ) - spec = importlib.util.spec_from_file_location("thin_notebook", path) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - assert module.run_action is local_workflow.run_action - assert module.resolve_target_config is local_workflow.resolve_target_config config = { "engine": engine, + "score_model_selection": "pinned_version", + "promotion_policy": "manual_approval", + "score_handoff": "disabled", **{ key: "{catalog}.{input_schema}." + key for key in ("training_table", "score_source_table", "prediction_table", "model_name") @@ -37,7 +41,6 @@ def test_notebook_delegates_bound_target_and_selected_action(tmp_path, monkeypat config_path.write_text(json.dumps(config)) values = { "config_path": str(config_path), - "action": action, "experiment_name": "/test/experiment", "catalog": "workspace", "input_schema": "test", @@ -45,6 +48,18 @@ def test_notebook_delegates_bound_target_and_selected_action(tmp_path, monkeypat "metadata_schema": "test", "resource_suffix": "", } + if action != "score": + values["lifecycle_action"] = action + if inherited_action: + # Run Job receives parent job parameters automatically, including evidence. + values.update( + lifecycle_action=inherited_action, + candidate_version="2", + comparison_sha256="b" * 64, + expected_champion_version="1", + rejection_reason="", + promotion_receipt_json='{"kind":"promotion"}', + ) @dataclass class Result: @@ -55,15 +70,20 @@ class Result: run = Mock(return_value=Result()) notebook = Mock() spark = object() - monkeypatch.setattr(module, "run_action", run) - monkeypatch.setattr(module, "spark", spark, raising=False) - monkeypatch.setattr( - module, - "dbutils", - SimpleNamespace(widgets=SimpleNamespace(get=values.__getitem__), notebook=notebook), - raising=False, + monkeypatch.setattr(job_runtime, "run_action", run) + task_values = Mock() + runpy.run_path( + str(path), + run_name="__main__", + init_globals={ + "spark": spark, + "dbutils": SimpleNamespace( + widgets=SimpleNamespace(getAll=lambda: values), + notebook=notebook, + jobs=SimpleNamespace(taskValues=task_values), + ), + }, ) - module.main() assert run.call_args.args == ( spark, { @@ -80,8 +100,60 @@ class Result: }, action, ) - assert run.call_args.kwargs["experiment_name"] == ( + assert run.call_args.kwargs.get("experiment_name") == ( "/test/experiment" if action.startswith("train") else None ) - assert (run.call_args.kwargs["artifact_path"] is not None) == action.startswith("train") - assert json.loads(notebook.exit.call_args.args[0]) == {"ok": True} + assert (run.call_args.kwargs.get("artifact_path") is not None) == action.startswith("train") + output = json.loads(notebook.exit.call_args.args[0]) + assert output["result"] == {"ok": True} + assert output["score_requested"] is False + if action == "score": + task_values.set.assert_not_called() + else: + task_values.set.assert_called_once_with(key="score_requested", value=False) + + +@pytest.mark.parametrize("override", ["task_role", "action"]) +def test_score_notebook_retains_override_guards_when_removing_parent_evidence( + tmp_path, monkeypatch, override +): + """Filtering inherited approval inputs must not hide attempts to override the fixed role.""" + from skyulf.integrations.databricks import job_runtime + + config_path = tmp_path / "workflow.json" + config_path.write_text( + json.dumps( + { + "score_model_selection": "champion", + "promotion_policy": "manual_approval", + "score_handoff": "after_alias_change", + **{ + key: "workspace.test." + key + for key in ( + "training_table", + "score_source_table", + "prediction_table", + "model_name", + ) + }, + } + ) + ) + values = { + "config_path": str(config_path), + "catalog": "workspace", + "input_schema": "test", + "output_schema": "test", + "metadata_schema": "test", + "resource_suffix": "", + "lifecycle_action": "approve", + "candidate_version": "2", + override: "approve", + } + run = Mock() + monkeypatch.setattr(job_runtime, "run_action", run) + with pytest.raises(ValueError, match="cannot be overridden"): + job_runtime.run_notebook( + None, SimpleNamespace(widgets=SimpleNamespace(getAll=lambda: values)), task_role="score" + ) + run.assert_not_called() diff --git a/skyulf-core/tests/integrations/test_databricks_bundle_template.py b/skyulf-core/tests/integrations/test_databricks_bundle_template.py index 9cc214955..d6d4a218f 100644 --- a/skyulf-core/tests/integrations/test_databricks_bundle_template.py +++ b/skyulf-core/tests/integrations/test_databricks_bundle_template.py @@ -40,10 +40,7 @@ def _render_default_config(row_key="entity_id", risk_category=""): '{{if .risk_category}}"{{.risk_category}}"{{else}}null{{end}}', json.dumps(risk_category or None), ) - .replace( - '{{if eq .model_selection_mode "auto_champion"}}{{.quality_threshold}}{{else}}null{{end}}', - "null", - ) + .replace("{{.quality_threshold}}", "null") ) return json.loads(content) @@ -166,7 +163,7 @@ def test_generated_bundle_has_only_train_and_serialized_score_jobs(): ) assert 'if eq .retraining_mode "monthly_paused"' in template assert "pause_status: PAUSED" in template - assert 'action: {{if eq .retraining_mode "monthly_paused"}}train_monthly' in template + assert 'default: {{if eq .retraining_mode "monthly_paused"}}train_monthly' in template assert "quartz_cron_expression: ${var.retraining_cron_expression}" in template assert "timezone_id: ${var.retraining_timezone_id}" in template @@ -189,18 +186,19 @@ def test_auto_champion_init_exposes_metric_gates_and_reuses_score_job(): root = WORKFLOW.parents[3] schema = json.loads((root / "databricks_template_schema.json").read_text(encoding="utf-8")) properties = schema["properties"] - assert properties["model_selection_mode"]["enum"] == [ + assert properties["score_model_selection"]["enum"] == [ "pinned_version", - "auto_champion", + "champion", ] + assert properties["promotion_policy"]["enum"] == ["manual_approval", "automatic"] assert "heldout_rmse" in properties["metric"]["enum"] assert "heldout_f1" in properties["metric"]["enum"] assert properties["quality_threshold"]["type"] == "string" assert properties["quality_threshold"]["default"] == "null" config = (WORKFLOW.parents[1] / "config/workflow.json.tmpl").read_text(encoding="utf-8") - assert '"model_selection_mode": "{{.model_selection_mode}}"' in config + assert '"score_model_selection": "{{.score_model_selection}}"' in config assert '"metric": "{{.metric}}"' in config jobs = (WORKFLOW.parents[1] / "resources/workflow.jobs.yml.tmpl").read_text(encoding="utf-8") assert "job_id: ${resources.jobs.score.id}" in jobs - assert "task_key: score_after_training" in jobs + assert "task_key: score_after_lifecycle" in jobs assert jobs.count("queue:\n enabled: true") == 2 diff --git a/skyulf-core/tests/integrations/test_databricks_job_output.py b/skyulf-core/tests/integrations/test_databricks_job_output.py new file mode 100644 index 000000000..5d6a753e3 --- /dev/null +++ b/skyulf-core/tests/integrations/test_databricks_job_output.py @@ -0,0 +1,147 @@ +"""Operator output must explain results without exposing technical copy requirements.""" + +import json + +import pytest + +from skyulf.integrations.databricks import job_runtime + + +def test_promotion_summary_separates_handoff_request_from_score_completion(): + """A successful alias change must not claim that prediction already succeeded.""" + from skyulf.integrations.databricks.job_output import render_bundle_output + + payload = { + "action": "approve", + "result": { + "kind": "promotion", + "model_name": "test.model", + "prior_version": "1", + "new_version": "5", + }, + "score_requested": True, + "next_actions": { + "rollback": { + "lifecycle_action": "rollback", + "expected_champion_version": "5", + "promotion_receipt_json": '{"event_id":"saved","comparison_sha256":"proof"}', + } + }, + } + html = render_bundle_output(payload) + assert "Champion changed" in html and "v1" in html and "v5" in html + assert "requested" in html and "child score run" in html + assert "promotion_receipt_json" in html and "Technical details" in html + visible_summary = html.split("
", 1)[0] + assert "If rollback is needed" in visible_summary + assert "Required current championv5" in visible_summary + assert "Restore versionv1" in visible_summary + assert "does not run automatically" in visible_summary + assert "comparison_sha256" not in visible_summary + assert "promotion_receipt_json" not in visible_summary + assert "Next action: rollback" not in html + + +def test_output_escapes_model_names_and_explains_noop_manifest(): + """Registry text cannot inject HTML and a no-op must not mislabel old write provenance.""" + from skyulf.integrations.databricks.job_output import render_bundle_output + + html = render_bundle_output( + { + "action": "score", + "score_requested": False, + "next_actions": {}, + "result": { + "noop": True, + "input_count": 0, + "output_count": 0, + "manifest": {"model_name": "", "model_version": "1"}, + }, + } + ) + assert "", "model_version": "1"}, @@ -62,6 +64,7 @@ def test_output_escapes_model_names_and_explains_noop_manifest(): assert ""}, + ) + visible = output.split("
")[0] + assert "16" in visible + assert "a" * 64 not in visible + assert " + diff --git a/tests/integration/test_nested_training_modes.py b/tests/integration/test_nested_training_modes.py new file mode 100644 index 000000000..2a90ba7b6 --- /dev/null +++ b/tests/integration/test_nested_training_modes.py @@ -0,0 +1,150 @@ +"""Exercise real backend Basic/Advanced routes with ordinary and nested CV.""" + +import numpy as np +import pandas as pd +import pytest + +from backend.data.catalog import FileSystemCatalog +from backend.ml_pipeline._execution.engine import PipelineEngine +from backend.ml_pipeline._execution.schemas import NodeConfig, PipelineConfig +from backend.ml_pipeline.artifacts.local import LocalArtifactStore +from backend.ml_pipeline.constants import StepType + + +def _model_settings(model, classification): + """Use small real ensembles with nondefault composition and two search candidates.""" + parameter = "C" if classification else "alpha" + if not model.startswith(("voting", "stacking")): + return {parameter: 0.5}, {parameter: [0.1, 1.0]} + params = { + "base_estimators": ["logistic_regression", "gaussian_nb"] + if classification + else ["linear_regression", "ridge"], + "n_jobs": 1, + } + if model.startswith("voting"): + params["weights"] = [2, 1] + if classification: + params["voting"] = "soft" + else: + params.update( + cv=2, + passthrough=True, + final_estimator="logistic_regression" if classification else "ridge", + ) + axis = "logistic_regression__C" if classification else "ridge__alpha" + return params, {axis: [0.1, 1.0]} + + +@pytest.mark.parametrize("method", ["ordinary", "nested_cv"]) +@pytest.mark.parametrize("mode", ["fixed", "tuned"]) +@pytest.mark.parametrize( + "model", + [ + "logistic_regression", + "ridge_regression", + "voting_classifier", + "voting_regressor", + "stacking_classifier", + "stacking_regressor", + ], +) +def test_backend_training_modes_preserve_cv_and_artifacts(tmp_path, model, mode, method): + """UI Basic/Advanced payloads must train, preserve fold isolation and reload results.""" + classification = model.endswith("classifier") or model == "logistic_regression" + rng = np.random.default_rng(12) + frame = pd.DataFrame(rng.normal(size=(120, 3)), columns=["x", "z", "w"]) + score = frame.x + frame.z - 0.2 * frame.w + frame["target"] = (score > 0).astype(int) if classification else score + csv = tmp_path / "data.csv" + frame.to_csv(csv, index=False) + model_params, space = _model_settings(model, classification) + cv = { + "cv_enabled": True, + "cv_folds": 2, + "cv_type": "nested_cv" + if method == "nested_cv" + else ("stratified_k_fold" if classification else "k_fold"), + "cv_shuffle": True, + "cv_random_state": 42, + } + if method == "nested_cv": + cv["cv_inner_folds"] = 2 + params = {"run_mode": mode, "algorithm": model, "target_column": "target"} + if mode == "fixed": + params.update(hyperparameters=model_params, **cv) + else: + params["tuning_config"] = { + **model_params, + **cv, + "strategy": "grid", + "metric": "accuracy" if classification else "r2", + "search_space": space, + "n_trials": 2, + } + nodes = [ + NodeConfig( + node_id="data", + step_type=StepType.DATA_LOADER, + params={"source": "csv", "path": str(csv)}, + ), + NodeConfig( + node_id="split", + step_type="TrainTestSplitter", + inputs=["data"], + params={"target_column": "target", "test_size": 0.2, "random_state": 42}, + ), + NodeConfig( + node_id="scale", + step_type="StandardScaler", + inputs=["split"], + params={"columns": ["x", "z", "w"]}, + ), + NodeConfig( + node_id="training", step_type=StepType.TRAINING, inputs=["scale"], params=params + ), + ] + store = LocalArtifactStore(str(tmp_path / "artifacts")) + engine = PipelineEngine(store, catalog=FileSystemCatalog()) + result = engine.run(PipelineConfig(pipeline_id="modes", nodes=nodes), job_id="modes") + assert result.status == "success", { + key: value.error for key, value in result.node_results.items() + } + metrics = result.node_results["training"].metrics + assert "fold_refit_fallback" not in metrics + assert metrics["fold_refit_audit"]["isolation_ok"] is True + assert metrics["fold_refit_audit"]["train_rows"] == 96 + saved_model, saved_result = store.load("training") + if model.startswith(("voting", "stacking")): + assert [name for name, _ in saved_model.estimators] == model_params["base_estimators"] + if model.startswith("voting"): + assert saved_model.weights == [2, 1] + if classification: + assert saved_model.voting == "soft" + else: + assert saved_model.cv == 2 and saved_model.passthrough is True + elif mode == "fixed": + parameter = "C" if classification else "alpha" + assert saved_model.get_params()[parameter] == 0.5 + expected_trials = 1 if mode == "fixed" else 2 + assert len(metrics["trials"]) == saved_result.n_trials == expected_trials + assert np.isfinite(metrics["best_score"]) + split = store.load("scale") + test_x, _test_y = split.test + test_frame = test_x.to_pandas() if hasattr(test_x, "to_pandas") else test_x + predictions = saved_model.predict(test_frame) + assert len(predictions) == 24 and np.isfinite(predictions).all() + if method == "nested_cv": + nested = metrics["nested_cv"] + assert saved_result.nested_cv == nested + assert nested["outer_folds"] == nested["inner_folds"] == 2 + assert nested["total_trials"] == 3 * expected_trials + assert all(f["train_rows"] == f["test_rows"] == 48 for f in nested["folds"]) + assert nested["mean_score"] == pytest.approx( + np.mean([f["outer_score"] for f in nested["folds"]]) + ) + assert metrics[f"cv_{nested['scoring_metric']}_mean"] == nested["mean_score"] + else: + assert "nested_cv" not in metrics + assert saved_result.nested_cv is None + assert any(key.startswith("cv_") and key.endswith("_mean") for key in metrics) diff --git a/tests/integration/test_node_runners_extra.py b/tests/integration/test_node_runners_extra.py index 6ad6688be..9cc4d44e1 100644 --- a/tests/integration/test_node_runners_extra.py +++ b/tests/integration/test_node_runners_extra.py @@ -494,9 +494,14 @@ def test_basic_training_with_cross_validation(pipeline_data_csv, tmp_path): assert cv_keys, f"expected cv_ metrics, got: {train_res.metrics.keys()}" -def test_advanced_tuning_with_cross_validation_nested(pipeline_data_csv, tmp_path): - """cv_enabled + cv_type='nested_cv' on tuning exercises the post-tuning CV downgrade path.""" +@pytest.mark.parametrize("fallback", [None, "unsupported_graph"]) +def test_advanced_tuning_with_cross_validation_nested( + pipeline_data_csv, tmp_path, monkeypatch, fallback +): + """The backend must expose independent outer scores from the Core nested searches.""" engine = _make_engine(tmp_path, "artifacts_cv_tuning") + if fallback: + monkeypatch.setattr(engine, "_resolve_fold_preprocessing", lambda *args: (None, fallback)) config = PipelineConfig( pipeline_id="p_cv_tuning", nodes=[ @@ -520,15 +525,27 @@ def test_advanced_tuning_with_cross_validation_nested(pipeline_data_csv, tmp_pat "search_space": {"C": [0.1, 1.0]}, "cv_enabled": True, "cv_type": "nested_cv", + "cv_inner_folds": 3, }, }, ), ], ) result = engine.run(config) + if fallback: + assert result.status != "success" + assert ( + "Nested CV requires fold-local preprocessing" + in result.node_results["node_tuning"].error + ) + return assert result.status == "success" tuning_res = result.node_results["node_tuning"] assert tuning_res.status == "success" + nested = tuning_res.metrics["nested_cv"] + assert nested["inner_folds"] == 3 + assert len(nested["folds"]) == 2 + assert tuning_res.metrics["cv_accuracy_mean"] == nested["mean_score"] cv_keys = [k for k in tuning_res.metrics if k.startswith("cv_")] assert cv_keys, f"expected cv_ metrics, got: {tuning_res.metrics.keys()}" From 4f7999a64336269d81aba09f8819cc896cfa4c14 Mon Sep 17 00:00:00 2001 From: flyingriverhorse Date: Sun, 27 Sep 2026 20:49:06 +0300 Subject: [PATCH 81/85] refactor: simplify lifecycle code and repair CI analysis gates Reduce Core and backend complexity without changing lifecycle contracts. Fix optional test dependencies and monitoring types, simplify CV output, refresh frontend assets, and exclude test rehearsals from static analysis. Signed-off-by: flyingriverhorse --- .codacy.yml | 7 + .github/codeql-config.yml | 12 + .github/workflows/codeql.yml | 1 + .../_execution/_leakage_validation.py | 19 +- .../_execution/engine/_node_runners.py | 23 +- backend/monitoring/router.py | 10 +- .../ml-canvas/scripts/check-bundle-size.mjs | 13 +- .../jobs/jobDetails/TuningConfiguration.tsx | 7 +- pyproject.toml | 7 +- requirements-ci.txt | 2 + requirements-dev.txt | 2 + skyulf-core/setup.py | 1 + skyulf-core/skyulf/core/portable_pipeline.py | 7 +- skyulf-core/skyulf/core/portable_state.py | 21 +- skyulf-core/skyulf/inference/_manifest.py | 82 +- skyulf-core/skyulf/inference/bundle.py | 53 +- .../skyulf/inference/local_evaluation.py | 38 +- .../skyulf/inference/local_pipeline.py | 54 +- skyulf-core/skyulf/inference/project_code.py | 84 ++- skyulf-core/skyulf/inference/spark.py | 95 ++- .../integrations/databricks/_contracts.py | 77 +- .../databricks/_lifecycle_state.py | 16 +- .../skyulf/integrations/databricks/batch.py | 141 ++-- .../databricks/delta_admission.py | 23 +- .../integrations/databricks/job_output.py | 186 +++-- .../integrations/databricks/job_runtime.py | 94 ++- .../databricks/lifecycle_tasks.py | 215 ++++-- .../integrations/databricks/local_approval.py | 67 +- .../integrations/databricks/local_batch.py | 102 ++- .../integrations/databricks/local_cv.py | 102 +-- .../integrations/databricks/local_ensemble.py | 14 +- .../databricks/local_incremental.py | 451 +++++++---- .../databricks/local_pre_split.py | 233 +++--- .../integrations/databricks/local_publish.py | 161 ++-- .../databricks/local_retraining.py | 704 +++++++++++------- .../integrations/databricks/local_sdk.py | 434 ++++++----- .../integrations/databricks/local_search.py | 175 +++-- .../databricks/local_search_results.py | 32 +- .../databricks/local_training_evidence.py | 28 +- .../integrations/databricks/local_workflow.py | 155 ++-- .../databricks/prediction_output.py | 145 ++-- .../skyulf/integrations/databricks/project.py | 11 +- .../integrations/databricks/training_dates.py | 209 ++++-- .../databricks/workflow_config.py | 56 +- .../skyulf/integrations/mlflow/challenger.py | 23 +- .../skyulf/integrations/mlflow/local_model.py | 21 +- .../skyulf/integrations/mlflow/model.py | 17 +- .../skyulf/integrations/mlflow/promotion.py | 284 ++++--- .../skyulf/integrations/mlflow/registry.py | 81 +- .../skyulf/integrations/mlflow/rejection.py | 61 +- .../skyulf/integrations/mlflow/validation.py | 50 +- skyulf-core/skyulf/leakage.py | 13 +- skyulf-core/skyulf/modeling/_tuning/engine.py | 25 +- .../modeling/_tuning/strategies/halving.py | 126 ++-- skyulf-core/skyulf/pipeline/_pipeline.py | 110 +-- .../skyulf/preprocessing/_feature_state.py | 24 +- .../skyulf/preprocessing/_spark_numeric.py | 11 +- .../preprocessing/imputation/_spark_simple.py | 37 +- skyulf-core/skyulf/preprocessing/pipeline.py | 42 +- .../preprocessing/scaling/_spark_standard.py | 72 +- skyulf-core/skyulf/utils.py | 11 +- .../integrations/test_local_hard_voting.py | 28 +- .../integrations/test_mlflow_promotion.py | 5 +- sonar-project.properties | 3 + ...e-CU3Ws-p_.js => AuditLogPage-BjT9Erh4.js} | 2 +- ...f.js => BaseModelParamsEditor-CyS6uUs-.js} | 2 +- ...-Dpmcy0d5.js => DataDriftPage-BjX1Ahxl.js} | 2 +- ...KzmwjpY.js => DeploymentsPage-BeXYd7e4.js} | 2 +- ...DAPage-BYX7As83.js => EDAPage-D-AvDDu5.js} | 2 +- ...rLj.js => GeoDistanceSettings-B1xj7Hl4.js} | 2 +- ...-CxgKkiJo.js => InferencePage-D5u_4kVQ.js} | 2 +- ...-lyme2_ha.js => ModelRegistry-B8Vj7yFC.js} | 2 +- ...-aiRJX30H.js => SlowNodesPage-CVIoKIrD.js} | 2 +- ...h.js => TemplatesGalleryModal-CbchbwFl.js} | 2 +- ...Ht.js => abnfDiagram-VCTEODGH-C_J13ClI.js} | 2 +- ... architectureDiagram-5GKGNRK7-D0TnY4Wf.js} | 2 +- ...X.js => blockDiagram-I7D4REHJ-Dwrazez5.js} | 2 +- ...oWFY.js => c4Diagram-7LVT6UL2-Dp-1gW55.js} | 2 +- static/ml_canvas/assets/channel-CtKHr9fF.js | 1 + static/ml_canvas/assets/channel-Dp8JVrfa.js | 1 - ...DEOZDP-3.js => chunk-2Q5K7J3B-BAAo9EN0.js} | 2 +- ...W4WNe2RE.js => chunk-5VM5RSS4-CKRC1CIZ.js} | 2 +- ...Dm2Us476.js => chunk-F27PBJKO-B7fm5O2R.js} | 2 +- ...DCz6O-wt.js => chunk-IMKFNOWR-CU8_Ku5h.js} | 2 +- ..._bXip4eZ.js => chunk-JWPE2WC7-BQCQvAYF.js} | 2 +- ...BOk39pqP.js => chunk-POPQ4Y6H-BR_pO24v.js} | 2 +- ...Bg03xQLN.js => chunk-SVP7TREG-CbDuCHXJ.js} | 2 +- ...BxRYcV3C.js => chunk-TICWLB2K-DjtJsWp0.js} | 2 +- ...CZsBIZJg.js => chunk-XXDRQBXY-DdoFz10O.js} | 2 +- .../assets/classDiagram-ZZMXUADV-CFWCbgE-.js | 1 - .../assets/classDiagram-ZZMXUADV-H8j0jcWO.js | 1 + .../classDiagram-v2-VYDZK3BY-CFWCbgE-.js | 1 - .../classDiagram-v2-VYDZK3BY-H8j0jcWO.js | 1 + ...E.js => cose-bilkent-JH36ORCC-Bxg7khAP.js} | 2 +- ...4gGbOM.js => cynefin-OW5HDTMX-DHAz5VCH.js} | 2 +- ...js => cynefinDiagram-5FMLGOSQ-CGTI0njV.js} | 2 +- ...DEDHweD_.js => dagre-GXQ25YYZ-DJLeXd5X.js} | 2 +- ...yT750N.js => diagram-S7CK7UJ4-Cau7m6k6.js} | 2 +- ...cOn3R5.js => diagram-UQ7AKVKN-BZwlTNIF.js} | 2 +- ...NV46Gu.js => diagram-VSXAHHWV-pcXZrHId.js} | 2 +- ...GIU6Vi.js => diagram-VX7I27RA-BgSJwATP.js} | 2 +- ...PVkxAQ.js => diagram-Z3DM3KII-CcZJy4uA.js} | 2 +- ...-5.js => ebnfDiagram-PWID7BFC-BcRWm148.js} | 2 +- ...1oAm.js => erDiagram-RLTQ6QDP-Dw35YtFf.js} | 2 +- ...Yj.js => flowDiagram-HODETNUW-Xqmx_yL9.js} | 2 +- ...K.js => ganttDiagram-EL5Y4UJY-BmyJJ4Bd.js} | 2 +- ...s => gitGraphDiagram-WWUBYQGX-CmGc_tMG.js} | 2 +- .../{index-BXksgzya.js => index-DYMv5Ibu.js} | 32 +- ...be.js => infoDiagram-27XIBGKW-tuTGkgp-.js} | 2 +- ...s => ishikawaDiagram-5VMMS53U-_C6MBdni.js} | 2 +- ...js => journeyDiagram-3NMN7TZE-BttQZK2k.js} | 2 +- ...=> kanban-definition-UXKFOSKX-CIHXDXA9.js} | 2 +- ...{layout-DCa88gcB.js => layout-CjvZl75P.js} | 2 +- ...e-BCO0YdKy.js => mermaid.core-BRmiRRt4.js} | 10 +- ...> mindmap-definition-YA3MSWOX-VFLZDj1N.js} | 2 +- ...VKH.js => pegDiagram-XKGWAZYB-CPYeUcHw.js} | 2 +- ...PQz.js => pieDiagram-E7YTZNPT-D5fGIpVH.js} | 2 +- ...s => quadrantDiagram-AXDQQJYC-Oo9Gnh_m.js} | 2 +- ...s => railroadDiagram-O6MQD6OU-BL4Z-2gP.js} | 2 +- ...> requirementDiagram-BXWQKSXE-CeL2qgUG.js} | 2 +- ....js => sankeyDiagram-P5KCCOFB-CB8vm4I1.js} | 2 +- ...s => sequenceDiagram-WJ2MYXX4-CGAwbz3z.js} | 2 +- ...Y3.js => sizeCapture-INFHLROL-Un2kUMnF.js} | 2 +- ...7.js => stateDiagram-D77RDMKH-BjRhmXkW.js} | 2 +- .../stateDiagram-v2-MP3YSRHH-BIkHRQ53.js | 1 - .../stateDiagram-v2-MP3YSRHH-DRwRHPIc.js | 1 + ...DVF4.js => swimlanes-42K2YHIH-TKp3b_ow.js} | 2 +- .../swimlanesDiagram-VR7AAH4N--nyp5ly9.js | 8 - .../swimlanesDiagram-VR7AAH4N-B-btUR64.js | 8 + ... timeline-definition-24CTP7MA-D0nsWFjv.js} | 2 +- ...Ga.js => vennDiagram-4TSXK5OY--WliFuM1.js} | 2 +- ...js => wardleyDiagram-VM6X3IG4-Dl8jhst9.js} | 2 +- ...js => xychartDiagram-S5SC5T6Z-Bczh05PY.js} | 2 +- static/ml_canvas/index.html | 2 +- uv.lock | 6 + 135 files changed, 3512 insertions(+), 2089 deletions(-) create mode 100644 .github/codeql-config.yml rename static/ml_canvas/assets/{AuditLogPage-CU3Ws-p_.js => AuditLogPage-BjT9Erh4.js} (99%) rename static/ml_canvas/assets/{BaseModelParamsEditor-CrBgCypf.js => BaseModelParamsEditor-CyS6uUs-.js} (98%) rename static/ml_canvas/assets/{DataDriftPage-Dpmcy0d5.js => DataDriftPage-BjX1Ahxl.js} (99%) rename static/ml_canvas/assets/{DeploymentsPage-DKzmwjpY.js => DeploymentsPage-BeXYd7e4.js} (99%) rename static/ml_canvas/assets/{EDAPage-BYX7As83.js => EDAPage-D-AvDDu5.js} (99%) rename static/ml_canvas/assets/{GeoDistanceSettings-q_f9JrLj.js => GeoDistanceSettings-B1xj7Hl4.js} (98%) rename static/ml_canvas/assets/{InferencePage-CxgKkiJo.js => InferencePage-D5u_4kVQ.js} (99%) rename static/ml_canvas/assets/{ModelRegistry-lyme2_ha.js => ModelRegistry-B8Vj7yFC.js} (99%) rename static/ml_canvas/assets/{SlowNodesPage-aiRJX30H.js => SlowNodesPage-CVIoKIrD.js} (99%) rename static/ml_canvas/assets/{TemplatesGalleryModal-sEhNFzeh.js => TemplatesGalleryModal-CbchbwFl.js} (99%) rename static/ml_canvas/assets/{abnfDiagram-VCTEODGH-Bv6eSEHt.js => abnfDiagram-VCTEODGH-C_J13ClI.js} (83%) rename static/ml_canvas/assets/{architectureDiagram-5GKGNRK7-CSxe9SIw.js => architectureDiagram-5GKGNRK7-D0TnY4Wf.js} (99%) rename static/ml_canvas/assets/{blockDiagram-I7D4REHJ-C2vNrp8X.js => blockDiagram-I7D4REHJ-Dwrazez5.js} (99%) rename static/ml_canvas/assets/{c4Diagram-7LVT6UL2-F8JSoWFY.js => c4Diagram-7LVT6UL2-Dp-1gW55.js} (99%) create mode 100644 static/ml_canvas/assets/channel-CtKHr9fF.js delete mode 100644 static/ml_canvas/assets/channel-Dp8JVrfa.js rename static/ml_canvas/assets/{chunk-2Q5K7J3B-DEOZDP-3.js => chunk-2Q5K7J3B-BAAo9EN0.js} (66%) rename static/ml_canvas/assets/{chunk-5VM5RSS4-W4WNe2RE.js => chunk-5VM5RSS4-CKRC1CIZ.js} (83%) rename static/ml_canvas/assets/{chunk-F27PBJKO-Dm2Us476.js => chunk-F27PBJKO-B7fm5O2R.js} (96%) rename static/ml_canvas/assets/{chunk-IMKFNOWR-DCz6O-wt.js => chunk-IMKFNOWR-CU8_Ku5h.js} (99%) rename static/ml_canvas/assets/{chunk-JWPE2WC7-_bXip4eZ.js => chunk-JWPE2WC7-BQCQvAYF.js} (78%) rename static/ml_canvas/assets/{chunk-POPQ4Y6H-BOk39pqP.js => chunk-POPQ4Y6H-BR_pO24v.js} (87%) rename static/ml_canvas/assets/{chunk-SVP7TREG-Bg03xQLN.js => chunk-SVP7TREG-CbDuCHXJ.js} (99%) rename static/ml_canvas/assets/{chunk-TICWLB2K-BxRYcV3C.js => chunk-TICWLB2K-DjtJsWp0.js} (99%) rename static/ml_canvas/assets/{chunk-XXDRQBXY-CZsBIZJg.js => chunk-XXDRQBXY-DdoFz10O.js} (76%) delete mode 100644 static/ml_canvas/assets/classDiagram-ZZMXUADV-CFWCbgE-.js create mode 100644 static/ml_canvas/assets/classDiagram-ZZMXUADV-H8j0jcWO.js delete mode 100644 static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-CFWCbgE-.js create mode 100644 static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-H8j0jcWO.js rename static/ml_canvas/assets/{cose-bilkent-JH36ORCC-CDsnQ2ME.js => cose-bilkent-JH36ORCC-Bxg7khAP.js} (99%) rename static/ml_canvas/assets/{cynefin-OW5HDTMX-WQ4gGbOM.js => cynefin-OW5HDTMX-DHAz5VCH.js} (99%) rename static/ml_canvas/assets/{cynefinDiagram-5FMLGOSQ-G5v2g310.js => cynefinDiagram-5FMLGOSQ-CGTI0njV.js} (98%) rename static/ml_canvas/assets/{dagre-GXQ25YYZ-DEDHweD_.js => dagre-GXQ25YYZ-DJLeXd5X.js} (98%) rename static/ml_canvas/assets/{diagram-S7CK7UJ4-BWyT750N.js => diagram-S7CK7UJ4-Cau7m6k6.js} (96%) rename static/ml_canvas/assets/{diagram-UQ7AKVKN-4ucOn3R5.js => diagram-UQ7AKVKN-BZwlTNIF.js} (95%) rename static/ml_canvas/assets/{diagram-VSXAHHWV-BgNV46Gu.js => diagram-VSXAHHWV-pcXZrHId.js} (97%) rename static/ml_canvas/assets/{diagram-VX7I27RA-CkGIU6Vi.js => diagram-VX7I27RA-BgSJwATP.js} (97%) rename static/ml_canvas/assets/{diagram-Z3DM3KII-BwPVkxAQ.js => diagram-Z3DM3KII-CcZJy4uA.js} (95%) rename static/ml_canvas/assets/{ebnfDiagram-PWID7BFC-C7ZAuv-5.js => ebnfDiagram-PWID7BFC-BcRWm148.js} (84%) rename static/ml_canvas/assets/{erDiagram-RLTQ6QDP-g1-M1oAm.js => erDiagram-RLTQ6QDP-Dw35YtFf.js} (98%) rename static/ml_canvas/assets/{flowDiagram-HODETNUW-Bb_JgsYj.js => flowDiagram-HODETNUW-Xqmx_yL9.js} (99%) rename static/ml_canvas/assets/{ganttDiagram-EL5Y4UJY-CcMHMo5K.js => ganttDiagram-EL5Y4UJY-BmyJJ4Bd.js} (99%) rename static/ml_canvas/assets/{gitGraphDiagram-WWUBYQGX-CtsDT5Wk.js => gitGraphDiagram-WWUBYQGX-CmGc_tMG.js} (99%) rename static/ml_canvas/assets/{index-BXksgzya.js => index-DYMv5Ibu.js} (90%) rename static/ml_canvas/assets/{infoDiagram-27XIBGKW-CjfUgjbe.js => infoDiagram-27XIBGKW-tuTGkgp-.js} (72%) rename static/ml_canvas/assets/{ishikawaDiagram-5VMMS53U-BWhitzUu.js => ishikawaDiagram-5VMMS53U-_C6MBdni.js} (99%) rename static/ml_canvas/assets/{journeyDiagram-3NMN7TZE-kEQaEPaA.js => journeyDiagram-3NMN7TZE-BttQZK2k.js} (98%) rename static/ml_canvas/assets/{kanban-definition-UXKFOSKX-B6eEdnO2.js => kanban-definition-UXKFOSKX-CIHXDXA9.js} (99%) rename static/ml_canvas/assets/{layout-DCa88gcB.js => layout-CjvZl75P.js} (99%) rename static/ml_canvas/assets/{mermaid.core-BCO0YdKy.js => mermaid.core-BRmiRRt4.js} (99%) rename static/ml_canvas/assets/{mindmap-definition-YA3MSWOX-Dhhr4u43.js => mindmap-definition-YA3MSWOX-VFLZDj1N.js} (98%) rename static/ml_canvas/assets/{pegDiagram-XKGWAZYB-xUdzLVKH.js => pegDiagram-XKGWAZYB-CPYeUcHw.js} (84%) rename static/ml_canvas/assets/{pieDiagram-E7YTZNPT-BTW6UPQz.js => pieDiagram-E7YTZNPT-D5fGIpVH.js} (96%) rename static/ml_canvas/assets/{quadrantDiagram-AXDQQJYC-DP9rDu6T.js => quadrantDiagram-AXDQQJYC-Oo9Gnh_m.js} (99%) rename static/ml_canvas/assets/{railroadDiagram-O6MQD6OU-C3qQCGAw.js => railroadDiagram-O6MQD6OU-BL4Z-2gP.js} (81%) rename static/ml_canvas/assets/{requirementDiagram-BXWQKSXE-EOiW9RIt.js => requirementDiagram-BXWQKSXE-CeL2qgUG.js} (99%) rename static/ml_canvas/assets/{sankeyDiagram-P5KCCOFB-Eyzw6Em6.js => sankeyDiagram-P5KCCOFB-CB8vm4I1.js} (99%) rename static/ml_canvas/assets/{sequenceDiagram-WJ2MYXX4-_oG_BpO0.js => sequenceDiagram-WJ2MYXX4-CGAwbz3z.js} (99%) rename static/ml_canvas/assets/{sizeCapture-INFHLROL-0wNySBY3.js => sizeCapture-INFHLROL-Un2kUMnF.js} (88%) rename static/ml_canvas/assets/{stateDiagram-D77RDMKH-CfZ9lMu7.js => stateDiagram-D77RDMKH-BjRhmXkW.js} (96%) delete mode 100644 static/ml_canvas/assets/stateDiagram-v2-MP3YSRHH-BIkHRQ53.js create mode 100644 static/ml_canvas/assets/stateDiagram-v2-MP3YSRHH-DRwRHPIc.js rename static/ml_canvas/assets/{swimlanes-42K2YHIH-CUheDVF4.js => swimlanes-42K2YHIH-TKp3b_ow.js} (99%) delete mode 100644 static/ml_canvas/assets/swimlanesDiagram-VR7AAH4N--nyp5ly9.js create mode 100644 static/ml_canvas/assets/swimlanesDiagram-VR7AAH4N-B-btUR64.js rename static/ml_canvas/assets/{timeline-definition-24CTP7MA-CehSUwIu.js => timeline-definition-24CTP7MA-D0nsWFjv.js} (99%) rename static/ml_canvas/assets/{vennDiagram-4TSXK5OY-C8O-XZGa.js => vennDiagram-4TSXK5OY--WliFuM1.js} (99%) rename static/ml_canvas/assets/{wardleyDiagram-VM6X3IG4-C4Ri7dfd.js => wardleyDiagram-VM6X3IG4-Dl8jhst9.js} (99%) rename static/ml_canvas/assets/{xychartDiagram-S5SC5T6Z-CnsYxfvZ.js => xychartDiagram-S5SC5T6Z-Bczh05PY.js} (99%) diff --git a/.codacy.yml b/.codacy.yml index dc199eec1..617bb54e0 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -4,5 +4,12 @@ exclude_paths: - "site/**" - "tests/**" - "skyulf-core/tests/**" + # Test execution and coverage stay enabled in CI; these are not product sources. + - "frontend/ml-canvas/e2e/**" + - "frontend/ml-canvas/src/test/**" + - "**/__tests__/**" + - "**/*.test.*" + - "**/*.spec.*" + - "initiatives/spark_and_mlflow/rehearsals/**" - "temp/**" - "tmp_repro_artifacts/**" diff --git a/.github/codeql-config.yml b/.github/codeql-config.yml new file mode 100644 index 000000000..427cc9868 --- /dev/null +++ b/.github/codeql-config.yml @@ -0,0 +1,12 @@ +name: Skyulf product sources + +# Python and JavaScript/TypeScript analysis only; CI still executes these tests. +paths-ignore: + - tests/** + - skyulf-core/tests/** + - frontend/ml-canvas/e2e/** + - frontend/ml-canvas/src/test/** + - '**/__tests__/**' + - '**/*.test.*' + - '**/*.spec.*' + - initiatives/spark_and_mlflow/rehearsals/** diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index aca8d50b4..d599b1952 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -44,6 +44,7 @@ jobs: uses: github/codeql-action/init@v4.37.4 with: languages: ${{ matrix.language }} + config-file: ./.github/codeql-config.yml # queries: security-and-quality # optional - name: Install Python dependencies diff --git a/backend/ml_pipeline/_execution/_leakage_validation.py b/backend/ml_pipeline/_execution/_leakage_validation.py index 2ee561ee8..0192245a8 100644 --- a/backend/ml_pipeline/_execution/_leakage_validation.py +++ b/backend/ml_pipeline/_execution/_leakage_validation.py @@ -319,6 +319,17 @@ def _exemption_reason(step_type: str, params: dict, target_column: str | None) - return leakage_exemption_reason(step_type, params, target_column=target_column) +def _validate_temporal_targets(execution_nodes: list[NodeConfig]) -> None: + """Reject rolling target features independently of split and warning policies.""" + for node in execution_nodes: + if node.step_type == "RollingAggregate": + validate_temporal_target( + node.step_type, + node.params, + target_column=_target_column_for_node(execution_nodes, node.node_id), + ) + + def validate_no_preprocessing_before_split( nodes: list[NodeConfig], on_leakage: OnLeakage = "raise", @@ -381,13 +392,7 @@ def validate_no_preprocessing_before_split( execution_splitters = splitter_ids & execution_ids execution_nodes = [n for n in nodes if n.node_id in execution_ids] data_dependent = data_dependent_step_types() - for node in execution_nodes: - if node.step_type == "RollingAggregate": - validate_temporal_target( - node.step_type, - node.params, - target_column=_target_column_for_node(execution_nodes, node.node_id), - ) + _validate_temporal_targets(execution_nodes) checked, exempted, messages = _inspect_pre_split_nodes( nodes, diff --git a/backend/ml_pipeline/_execution/engine/_node_runners.py b/backend/ml_pipeline/_execution/engine/_node_runners.py index df79d6804..bd6dc0442 100644 --- a/backend/ml_pipeline/_execution/engine/_node_runners.py +++ b/backend/ml_pipeline/_execution/engine/_node_runners.py @@ -960,6 +960,20 @@ def _record_iteration_metrics( if last_point.get("direction"): metrics["iteration_direction"] = last_point["direction"] + @staticmethod + def _require_nested_fold_preprocessing( + tuning_params: dict[str, Any], refit_fallback: str | None + ) -> None: + """Reject nested evaluation when preprocessing cannot be refit within each fold.""" + if ( + tuning_params.get("cv_enabled", False) + and tuning_params.get("cv_type") == "nested_cv" + and refit_fallback is not None + ): + raise ValueError( + f"Nested CV requires fold-local preprocessing; cannot use {refit_fallback}." + ) + def _run_training_tuned( self, node: NodeConfig, @@ -1016,14 +1030,7 @@ def _run_training_tuned( # Unsupported learned graphs fail closed. Explicit warn/ignore mode # permits fallback, recorded by the stable reason code in the metrics. fold_preprocessing, refit_fallback = self._resolve_fold_preprocessing(node, target_col) - if ( - tuning_params.get("cv_enabled", False) - and tuning_params.get("cv_type") == "nested_cv" - and refit_fallback is not None - ): - raise ValueError( - f"Nested CV requires fold-local preprocessing; cannot use {refit_fallback}." - ) + self._require_nested_fold_preprocessing(tuning_params, refit_fallback) # Audit telemetry (findings 2026-08-26 §3/B): record the input row # count of every per-fold fit/transform so the run can be audited diff --git a/backend/monitoring/router.py b/backend/monitoring/router.py index 5afac3576..7469e68c7 100644 --- a/backend/monitoring/router.py +++ b/backend/monitoring/router.py @@ -1085,7 +1085,8 @@ async def list_error_events( .distinct() .order_by(ErrorEvent.job_id) ) - facet_job_ids = [row[0] for row in facet_job_ids_result.all()] + # The SQL IS NOT NULL predicate guarantees strings at this boundary. + facet_job_ids = [cast(str, row[0]) for row in facet_job_ids_result.all()] total_result = await db.execute( select(sa_func.count()).select_from(ErrorEvent).where(*conditions) @@ -1770,7 +1771,8 @@ async def list_pipeline_logs( .distinct() .order_by(PipelineRunLog.node_type) ) - facet_node_types = [row[0] for row in facet_node_types_result.all()] + # SQL IS NOT NULL predicates narrow these nullable model fields to strings. + facet_node_types = [cast(str, row[0]) for row in facet_node_types_result.all()] facet_pipeline_ids_result = await db.execute( select(PipelineRunLog.pipeline_id) @@ -1778,7 +1780,7 @@ async def list_pipeline_logs( .distinct() .order_by(PipelineRunLog.pipeline_id) ) - facet_pipeline_ids = [row[0] for row in facet_pipeline_ids_result.all()] + facet_pipeline_ids = [cast(str, row[0]) for row in facet_pipeline_ids_result.all()] facet_node_ids_result = await db.execute( select(PipelineRunLog.node_id) @@ -1786,7 +1788,7 @@ async def list_pipeline_logs( .distinct() .order_by(PipelineRunLog.node_id) ) - facet_node_ids = [row[0] for row in facet_node_ids_result.all()] + facet_node_ids = [cast(str, row[0]) for row in facet_node_ids_result.all()] total_result = await db.execute( select(sa_func.count()).select_from(PipelineRunLog).where(*conditions) diff --git a/frontend/ml-canvas/scripts/check-bundle-size.mjs b/frontend/ml-canvas/scripts/check-bundle-size.mjs index 676207b9d..16fa427b4 100644 --- a/frontend/ml-canvas/scripts/check-bundle-size.mjs +++ b/frontend/ml-canvas/scripts/check-bundle-size.mjs @@ -36,18 +36,7 @@ const BUDGETS = [ { prefix: 'vendor-flow', maxGzipBytes: 80 * 1024, label: 'vendor-flow', kind: 'vendor' }, { prefix: 'vendor-react', maxGzipBytes: 70 * 1024, label: 'vendor-react', kind: 'vendor' }, { prefix: 'vendor-utils', maxGzipBytes: 90 * 1024, label: 'vendor-utils', kind: 'vendor' }, - // App entry — bumped 220→240 KB for Ensemble modeling node panel components (v0.6.0), - // then 240→260 KB for the SHAP Explainability tab (Summary/Beeswarm/Dependence/ - // Waterfall/Force/Interaction) + Segmentation (4 clustering algorithms, auto-profile - // labeling, reference-column UI/crosstab) shipped in v0.7.0, - // then 260→275 KB for slow-nodes observability instrumentation + concurrent - // execution rendering (v0.7.x). Raised 300→325 KB for canvas connection guidance, - // grouped split outputs, and component discovery improvements (v0.8.16). - // 325→326 KB for type-preserving config equality in undo history (v0.8.23). - // 326→327 KB for graph-aware Optuna pruning support and request state (v0.8.23). - // 327→330 KB for Manual Bounds controls and Geo Distance graph validation - // (v0.8.23). Geo Distance settings remain lazy; measured main: 328.8 KB gzip. - { prefix: 'index', maxGzipBytes: 330 * 1024, label: 'index (main)', kind: 'vendor' }, + { prefix: 'index', maxGzipBytes: 340 * 1024, label: 'index (main)', kind: 'vendor' }, // Lazy route chunks — keep tight so an EDA-only regression surfaces // here rather than getting absorbed by the global index ceiling. { prefix: 'EDAPage', maxGzipBytes: 140 * 1024, label: 'route:EDA', kind: 'route' }, diff --git a/frontend/ml-canvas/src/components/panels/jobs/jobDetails/TuningConfiguration.tsx b/frontend/ml-canvas/src/components/panels/jobs/jobDetails/TuningConfiguration.tsx index 693683b2b..45c2bf2a8 100644 --- a/frontend/ml-canvas/src/components/panels/jobs/jobDetails/TuningConfiguration.tsx +++ b/frontend/ml-canvas/src/components/panels/jobs/jobDetails/TuningConfiguration.tsx @@ -151,6 +151,11 @@ function getTuningConfig(job: JobInfo): TuningConfig | undefined { return Object.keys(saved || {}).length > 0 ? saved : node?.params?.tuning_config as TuningConfig | undefined; } +function getInnerFoldCount(config: TuningConfig): number { + const outerFolds = config.cv_folds ?? 5; + return config.cv_inner_folds ?? (outerFolds > 2 ? Math.min(3, outerFolds - 1) : 2); +} + function TuningCrossValidation({ config }: { config: TuningConfig }) { return ( <> @@ -171,7 +176,7 @@ function TuningCrossValidation({ config }: { config: TuningConfig }) { {config.cv_type === 'nested_cv' && (
Inner folds: - {config.cv_inner_folds ?? ((config.cv_folds ?? 5) > 2 ? Math.min(3, (config.cv_folds ?? 5) - 1) : 2)} + {getInnerFoldCount(config)}
)}
diff --git a/pyproject.toml b/pyproject.toml index 8ef7cc0c8..5135045fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,6 +104,8 @@ dev = [ "hypothesis>=6.100,<7.0.0", "syrupy>=4.0.0", "pytest-benchmark>=5.0.0,<6.0.0", + "jsonschema>=4.0.0,<5.0.0", # Databricks template prompt visibility tests + "mlflow>=3.10,<4.0", # Tracking integration tests and type checking # Linters/formatters/typecheckers (>=0.15: PLC0415 rule, audit finding F-11) "ruff>=0.15,<1.0", @@ -342,7 +344,10 @@ members = [ [tool.bandit] # Bandit B101 (assert_used) flags every `assert`. In pytest suites `assert` is the # idiomatic, correct construct, so we exclude test trees from Bandit entirely. -exclude_dirs = ["tests", "skyulf-core/tests", "temp", ".venv", "node_modules", "frontend"] +exclude_dirs = [ + "tests", "skyulf-core/tests", "initiatives/spark_and_mlflow/rehearsals", + "temp", ".venv", "node_modules", "frontend", +] [tool.bandit.assert_used] # Belt-and-suspenders: even if a test file is scanned outside the excluded dirs diff --git a/requirements-ci.txt b/requirements-ci.txt index 88e47f1bb..93a1276a4 100644 --- a/requirements-ci.txt +++ b/requirements-ci.txt @@ -3,6 +3,7 @@ # Local monorepo package (provides the `skyulf` module) -e ./skyulf-core +-r requirements-mlflow.txt # Exercise tracking tests and resolve their types fastapi>=0.104.0,<1.0.0 anyio>=4.14.2,<5.0.0 # Security floor for TLS and process-pool fixes @@ -46,6 +47,7 @@ pytest-cov>=4.1.0,<8.0.0 hypothesis>=6.100,<7.0.0 syrupy>=4.0.0 pytest-benchmark>=5.0.0,<6.0.0 +jsonschema>=4.0.0,<5.0.0 # Databricks template prompt visibility tests ipython>=8.18.1 # Imported by full executable notebook exports jinja2>=3.1.6 # Required by pandas Styler in compact notebook exports ruff>=0.15,<1.0 # >=0.15 for PLC0415 (F-11 deferred-import enforcement) diff --git a/requirements-dev.txt b/requirements-dev.txt index 212079cec..5f5d09c0e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,5 @@ # Development requirements (linters, formatters, test runners) +-r requirements-mlflow.txt # Tracking integration tests and type checking ruff>=0.8,<1.0 # Lint + format + import sort (replaces black/flake8/isort) pytest>=7.4.0,<10.0.0 pytest-asyncio>=0.21.0,<2.0.0 @@ -6,6 +7,7 @@ pytest-cov>=4.1.0,<8.0.0 hypothesis>=6.100,<7.0.0 # Property-based tests (engine parity, ingestion fuzz) syrupy>=4.0.0 # Snapshot assertions — pipeline JSON regression tests pytest-benchmark>=5.0.0,<6.0.0 # Opt-in performance benchmarks (--benchmark-only) +jsonschema>=4.0.0,<5.0.0 # Databricks template prompt visibility tests lizard>=1.23.0 # Cyclomatic-complexity gate (CCN 8) — mirrors CI factory-boy>=3.3.0,<4.0.0 faker>=19.0.0,<41.0.0 diff --git a/skyulf-core/setup.py b/skyulf-core/setup.py index d065187a0..a46753c08 100644 --- a/skyulf-core/setup.py +++ b/skyulf-core/setup.py @@ -55,6 +55,7 @@ "hypothesis>=6.100", "syrupy>=4.0.0", "pytest-benchmark>=5.0.0,<6.0.0", + "jsonschema>=4.0.0,<5.0.0", ], "viz": ["matplotlib>=3.7.0", "rich>=13.0.0"], "eda": [ diff --git a/skyulf-core/skyulf/core/portable_pipeline.py b/skyulf-core/skyulf/core/portable_pipeline.py index e905d3244..ae9eb5aaa 100644 --- a/skyulf-core/skyulf/core/portable_pipeline.py +++ b/skyulf-core/skyulf/core/portable_pipeline.py @@ -84,6 +84,12 @@ def _config(node: str, raw: Any, state: dict) -> dict[str, Any]: ) params = {**defaults, **params} keys = ("strategy",) if node == "SimpleImputer" else ("with_mean", "with_std") + _validate_config(node, params, state, keys) + return params + + +def _validate_config(node: str, params: dict, state: dict, keys: tuple[str, ...]) -> None: + """Check resolved settings against learned state and supported node options.""" for key in keys: if state and (type(params[key]) is not type(state[key]) or params[key] != state[key]): raise ValueError("Portable config disagrees with fitted state.") @@ -91,7 +97,6 @@ def _config(node: str, raw: Any, state: dict) -> dict[str, Any]: raise ValueError("Unsupported portable SimpleImputer strategy.") if node == "StandardScaler" and any(type(params[key]) is not bool for key in keys): raise ValueError("Scaler flags must be booleans.") - return params def _validate_envelope(document: Any) -> None: diff --git a/skyulf-core/skyulf/core/portable_state.py b/skyulf-core/skyulf/core/portable_state.py index abaef09cc..2c28a41ec 100644 --- a/skyulf-core/skyulf/core/portable_state.py +++ b/skyulf-core/skyulf/core/portable_state.py @@ -189,6 +189,11 @@ def _validate_imputer(params: dict[str, Any]) -> None: for value in params["fill_values"].values() ): raise ValueError("Imputer fill values must be scalars.") + _validate_missing_counts(params) + + +def _validate_missing_counts(params: dict[str, Any]) -> None: + """Check nonnegative per-column counts and their recorded total.""" counts = [*params["missing_counts"].values(), params["total_missing"]] if any(type(value) is not int or value < 0 for value in counts): raise ValueError("Missing counts must be nonnegative integers.") @@ -256,11 +261,17 @@ def _unpack_scalar(kind: Any, value: Any) -> Any: if str(result) == value: return result if kind == "float" and type(value) is str: - result = {"nan": math.nan, "+inf": math.inf, "-inf": -math.inf}.get(value) - if result is None: - result = float.fromhex(value) - if _float_token(result) == value: - return result + return _unpack_float(value) + raise ValueError("Unknown or malformed portable scalar tag.") + + +def _unpack_float(value: str) -> float: + """Decode a canonical finite or explicitly tagged non-finite floating value.""" + result = {"nan": math.nan, "+inf": math.inf, "-inf": -math.inf}.get(value) + if result is None: + result = float.fromhex(value) + if _float_token(result) == value: + return result raise ValueError("Unknown or malformed portable scalar tag.") diff --git a/skyulf-core/skyulf/inference/_manifest.py b/skyulf-core/skyulf/inference/_manifest.py index d60e7efce..674454fc3 100644 --- a/skyulf-core/skyulf/inference/_manifest.py +++ b/skyulf-core/skyulf/inference/_manifest.py @@ -74,16 +74,27 @@ class BundleManifest(BaseModel): @model_validator(mode="after") def validate_contract(self) -> "BundleManifest": """Reject internally inconsistent schemas and decision metadata before model loading.""" + self._validate_schemas() + self._validate_outputs() + self._validate_thresholds() + names = [name for name, _ in self.requirements] + if sorted(names) != sorted(("python", *_PACKAGES)): + raise ValueError("Requirements must contain exactly the supported runtime packages.") + return self + + def _validate_schemas(self) -> None: + """Require distinct ordered feature names and supported input dtypes.""" for schema in (self.input_schema, self.feature_schema, self.output_schema): - names = tuple(col.name for col in schema) - if not names or len(names) != len(set(names)): - raise ValueError("Bundle schemas require distinct nonempty column names.") + _validate_schema_names(schema) if self.feature_order != tuple(col.name for col in self.feature_schema): raise ValueError("feature_order must match feature_schema.") if self.input_stage == "features" and self.input_schema != self.feature_schema: raise ValueError("features input_schema must match feature_schema.") if any(col.dtype not in _DTYPES for col in (*self.input_schema, *self.feature_schema)): raise ValueError("Initial bundle inputs require primitive numeric or boolean dtypes.") + + def _validate_outputs(self) -> None: + """Match the prediction schema to task and class metadata.""" expected = ("prediction", *self.probability_columns) if tuple(col.name for col in self.output_schema) != expected: raise ValueError("Prediction schema and probability columns disagree.") @@ -93,39 +104,26 @@ def validate_contract(self) -> "BundleManifest": if self.output_schema[0].dtype != "float64": raise ValueError("Regression prediction dtype must be float64.") else: - if len(self.classes) < 2 or len(set(self.classes)) != len(self.classes): - raise ValueError("Classification requires distinct scalar classes.") - if self.probability_columns != tuple( - f"probability_{i}" for i in range(len(self.classes)) - ): - raise ValueError("Probability columns must follow class positions.") - if self.positive_label != (self.classes[1] if len(self.classes) == 2 else None): - raise ValueError("positive_label must follow the binary class convention.") - if self.output_schema[0].dtype != label_dtype(self.classes): - raise ValueError("Prediction dtype must match classes.") - if any(col.dtype != "float64" for col in self.output_schema[1:]): - raise ValueError("Probability columns require float64.") - self._validate_thresholds() - names = [name for name, _ in self.requirements] - if sorted(names) != sorted(("python", *_PACKAGES)): - raise ValueError("Requirements must contain exactly the supported runtime packages.") - return self + self._validate_classification() + + def _validate_classification(self) -> None: + """Keep scalar labels and probability positions consistent with model classes.""" + if len(self.classes) < 2 or len(set(self.classes)) != len(self.classes): + raise ValueError("Classification requires distinct scalar classes.") + if self.probability_columns != tuple(f"probability_{i}" for i in range(len(self.classes))): + raise ValueError("Probability columns must follow class positions.") + if self.positive_label != (self.classes[1] if len(self.classes) == 2 else None): + raise ValueError("positive_label must follow the binary class convention.") + if self.output_schema[0].dtype != label_dtype(self.classes): + raise ValueError("Prediction dtype must match classes.") + if any(col.dtype != "float64" for col in self.output_schema[1:]): + raise ValueError("Probability columns require float64.") def _validate_thresholds(self) -> None: """Threshold arrays are class-ordered and must agree with their active source.""" state = self.thresholds for values in (state.values, state.tuning_values, state.pipeline_values): - if values and (len(values) != len(self.classes) or not self.classes): - raise ValueError("Threshold values must cover every class.") - minimum_ok = all( - value >= 0 if len(self.classes) == 2 else value > 0 for value in values - ) - if values and ( - not all(math.isfinite(value) for value in values) - or not minimum_ok - or not any(values) - ): - raise ValueError("Invalid decision thresholds.") + self._validate_threshold_values(values) selected = { "estimator": (), "tuning": state.tuning_values, @@ -134,6 +132,28 @@ def _validate_thresholds(self) -> None: if state.values != selected or (state.source != "estimator" and not selected): raise ValueError("Threshold provenance disagrees with the active decision rule.") + def _validate_threshold_values(self, values: tuple[float, ...]) -> None: + """Require complete class coverage before checking numeric threshold bounds.""" + if values and (len(values) != len(self.classes) or not self.classes): + raise ValueError("Threshold values must cover every class.") + _validate_threshold_bounds(values, len(self.classes) == 2) + + +def _validate_schema_names(schema: tuple[ColumnSpec, ...]) -> None: + """Require a nonempty schema with distinct column names.""" + names = tuple(col.name for col in schema) + if not names or len(names) != len(set(names)): + raise ValueError("Bundle schemas require distinct nonempty column names.") + + +def _validate_threshold_bounds(values: tuple[float, ...], binary: bool) -> None: + """Allow zero binary thresholds while rejecting non-finite or all-zero arrays.""" + minimum_ok = all(value >= 0 if binary else value > 0 for value in values) + if values and ( + not all(math.isfinite(value) for value in values) or not minimum_ok or not any(values) + ): + raise ValueError("Invalid decision thresholds.") + def schema_columns(schema: SkyulfSchema) -> tuple[ColumnSpec, ...]: """Normalize equivalent pandas/Polars numeric labels without casting any input data.""" diff --git a/skyulf-core/skyulf/inference/bundle.py b/skyulf-core/skyulf/inference/bundle.py index 623b99a22..3f35cb48b 100644 --- a/skyulf-core/skyulf/inference/bundle.py +++ b/skyulf-core/skyulf/inference/bundle.py @@ -7,7 +7,7 @@ import json from dataclasses import dataclass, replace from pathlib import Path -from typing import Any +from typing import Any, Literal import numpy as np import pandas as pd @@ -100,6 +100,32 @@ def build_bundle( raise ValueError("Invalid input_stage or use_tuned_thresholds.") budget = _options(options) model = pipeline_model(pipeline) + raw_schema, feature_schema = _fitted_schemas(pipeline, model, feature_order) + feature_state = export_feature_state(pipeline.feature_engineer, options=budget) + if len(feature_state) > budget.state_max_bytes: + raise ValueError("Feature state exceeds state_max_bytes.") + payload = serialize_model(model, budget.model_max_bytes) + manifest = _build_manifest( + pipeline, + model, + input_stage, + feature_order, + raw_schema, + feature_schema, + feature_state, + payload, + use_tuned_thresholds, + ) + manifest = manifest.model_copy(update={"semantic_digest": semantic_digest(manifest)}) + bundle = InferenceBundle(manifest, feature_state, payload) + _validate_bundle(bundle, budget) + return bundle + + +def _fitted_schemas( + pipeline: SkyulfPipeline, model: Any, feature_order: tuple[str, ...] +) -> tuple[tuple[ColumnSpec, ...], tuple[ColumnSpec, ...]]: + """Recover recorded schemas and verify the requested feature order and model width.""" schemas = getattr(pipeline, "_inference_schemas", None) if schemas is None: raise ValueError("Missing fitted input schemas; refit this legacy standalone pipeline.") @@ -110,10 +136,21 @@ def build_bundle( raise ValueError("feature_order must match the actual model training order.") if len(feature_order) != int(model.n_features_in_): raise ValueError("Recorded model feature width is inconsistent.") - feature_state = export_feature_state(pipeline.feature_engineer, options=budget) - if len(feature_state) > budget.state_max_bytes: - raise ValueError("Feature state exceeds state_max_bytes.") - payload = serialize_model(model, budget.model_max_bytes) + return raw_schema, feature_schema + + +def _build_manifest( + pipeline: SkyulfPipeline, + model: Any, + input_stage: Literal["raw", "features"], + feature_order: tuple[str, ...], + raw_schema: tuple[ColumnSpec, ...], + feature_schema: tuple[ColumnSpec, ...], + feature_state: bytes, + payload: bytes, + use_tuned_thresholds: bool, +) -> BundleManifest: + """Describe frozen payload identities and the model's task-specific output columns.""" classification = is_classifier(model) classes = tuple(np.asarray(model.classes_).tolist()) if classification else () probabilities = tuple(f"probability_{i}" for i in range(len(classes))) @@ -121,7 +158,7 @@ def build_bundle( ColumnSpec(name="prediction", dtype=label_dtype(classes) if classification else "float64"), *(ColumnSpec(name=name, dtype="float64") for name in probabilities), ) - manifest = BundleManifest( + return BundleManifest( input_stage=input_stage, feature_order=feature_order, input_schema=raw_schema if input_stage == "raw" else feature_schema, @@ -139,10 +176,6 @@ def build_bundle( fe_sha256=checksum(feature_state), fe_semantic_digest=json.loads(feature_state)["semantic_digest"], ) - manifest = manifest.model_copy(update={"semantic_digest": semantic_digest(manifest)}) - bundle = InferenceBundle(manifest, feature_state, payload) - _validate_bundle(bundle, budget) - return bundle def _options(options: ExecutionOptions | None) -> ExecutionOptions: diff --git a/skyulf-core/skyulf/inference/local_evaluation.py b/skyulf-core/skyulf/inference/local_evaluation.py index 2a06fc05a..ed7bfaede 100644 --- a/skyulf-core/skyulf/inference/local_evaluation.py +++ b/skyulf-core/skyulf/inference/local_evaluation.py @@ -1,5 +1,7 @@ """Held-out metrics for a saved pandas/Polars local pipeline.""" +from typing import Any + import pandas as pd import polars as pl from joblib import parallel_config @@ -28,6 +30,22 @@ def evaluate_local_holdout( normal training/batch prediction parallelism remain unchanged. This does not guarantee determinism for arbitrary models or other numerical runtimes. """ + _validate_holdout(artifact, heldout, target_column) + columns = list(artifact.manifest.input_columns) + features = ( + heldout.select(columns) if isinstance(heldout, pl.DataFrame) else heldout.loc[:, columns] + ) + actual = heldout[target_column].to_numpy() + with parallel_config(backend="sequential"): + predictions = predict_local_pipeline(features, artifact) + raw_metrics = _holdout_metrics(artifact, features, heldout, target_column, actual, predictions) + return {f"heldout_{name}": value for name, value in sanitize_metrics(raw_metrics).items()} + + +def _validate_holdout( + artifact: LocalPipelineArtifact, heldout: pd.DataFrame | pl.DataFrame, target_column: str +) -> None: + """Require labeled evaluation rows with a target outside the model inputs.""" if not isinstance(artifact, LocalPipelineArtifact): raise TypeError("artifact must be a LocalPipelineArtifact.") if not isinstance(heldout, pd.DataFrame | pl.DataFrame): @@ -36,13 +54,17 @@ def evaluate_local_holdout( raise ValueError("heldout must contain at least two labeled rows.") if target_column not in heldout.columns or target_column in artifact.manifest.input_columns: raise ValueError("heldout must contain a separate target column.") - columns = list(artifact.manifest.input_columns) - features = ( - heldout.select(columns) if isinstance(heldout, pl.DataFrame) else heldout.loc[:, columns] - ) - actual = heldout[target_column].to_numpy() - with parallel_config(backend="sequential"): - predictions = predict_local_pipeline(features, artifact) + + +def _holdout_metrics( + artifact: LocalPipelineArtifact, + features: pd.DataFrame | pl.DataFrame, + heldout: pd.DataFrame | pl.DataFrame, + target_column: str, + actual: Any, + predictions: pd.DataFrame, +) -> dict[str, Any]: + """Score existing predictions using the saved model's task and probability contract.""" estimator = artifact.pipeline.model_estimator if estimator is None: raise ValueError("Local artifact has no fitted model.") @@ -71,4 +93,4 @@ def evaluate_local_holdout( ), **scoring_args, ) - return {f"heldout_{name}": value for name, value in sanitize_metrics(raw_metrics).items()} + return raw_metrics diff --git a/skyulf-core/skyulf/inference/local_pipeline.py b/skyulf-core/skyulf/inference/local_pipeline.py index 8cf51f19e..d833d9f5e 100644 --- a/skyulf-core/skyulf/inference/local_pipeline.py +++ b/skyulf-core/skyulf/inference/local_pipeline.py @@ -84,10 +84,9 @@ def _manifest( classification_probabilities = not classification or callable( getattr(model, "predict_proba", None) ) - if use_tuned_thresholds and not classification_probabilities: - raise ValueError("Tuned thresholds require classification probabilities.") - if use_tuned_thresholds and (not classification or pipeline._tuned_thresholds is None): - raise ValueError("Tuned thresholds require fitted classification thresholds.") + _validate_tuned_thresholds( + pipeline, use_tuned_thresholds, classification, classification_probabilities + ) return LocalPipelineManifest( fitted_engine=fitted_engine, input_columns=raw.columns, @@ -109,6 +108,16 @@ def _manifest( ) +def _validate_tuned_thresholds( + pipeline: SkyulfPipeline, enabled: bool, classification: bool, probabilities: bool +) -> None: + """Require probability support and fitted thresholds before recording their use.""" + if enabled and not probabilities: + raise ValueError("Tuned thresholds require classification probabilities.") + if enabled and (not classification or pipeline._tuned_thresholds is None): + raise ValueError("Tuned thresholds require fitted classification thresholds.") + + def _check_runtime(manifest: LocalPipelineManifest) -> None: """Reject incompatible Python or dependency versions before loading pickle.""" current = dict(runtime_requirements()) @@ -171,15 +180,7 @@ def load_local_pipeline(path: str | Path) -> LocalPipelineArtifact: if type(document) is not dict or type(document.get("format_version")) is not int: raise ValueError("Invalid local artifact format_version.") manifest = LocalPipelineManifest.model_validate_json(metadata) - if len(manifest.input_columns) != len(manifest.input_dtypes) or len( - manifest.feature_columns - ) != len(manifest.feature_dtypes): - raise ValueError("Local artifact schema columns and dtypes disagree.") - if any( - len(set(columns)) != len(columns) - for columns in (manifest.input_columns, manifest.feature_columns) - ): - raise ValueError("Local artifact schema columns must be unique.") + _validate_manifest_schema(manifest) _check_runtime(manifest) payload = _read_bounded(source / "pipeline.pkl", _MAX_PIPELINE_BYTES) if checksum(payload) != manifest.pipeline_sha256: @@ -197,6 +198,19 @@ def load_local_pipeline(path: str | Path) -> LocalPipelineArtifact: return LocalPipelineArtifact(manifest, pipeline) +def _validate_manifest_schema(manifest: LocalPipelineManifest) -> None: + """Require matching dtype counts and unique names for input and model schemas.""" + if len(manifest.input_columns) != len(manifest.input_dtypes) or len( + manifest.feature_columns + ) != len(manifest.feature_dtypes): + raise ValueError("Local artifact schema columns and dtypes disagree.") + if any( + len(set(columns)) != len(columns) + for columns in (manifest.input_columns, manifest.feature_columns) + ): + raise ValueError("Local artifact schema columns must be unique.") + + def require_local_pipeline_scope( artifact: LocalPipelineArtifact, scope: Literal["whole_frame_local", "row_local_http", "spark_worker", "spark_native"], @@ -216,10 +230,7 @@ def predict_local_pipeline( raise TypeError("Expected a LocalPipelineArtifact.") if not isinstance(frame, pd.DataFrame | pl.DataFrame): raise TypeError("Local prediction requires a pandas or Polars DataFrame.") - if artifact.manifest.fitted_engine == "polars": - native = pl.from_pandas(frame) if isinstance(frame, pd.DataFrame) else frame - else: - native = frame.to_pandas() if isinstance(frame, pl.DataFrame) else frame + native = _prediction_frame(frame, artifact.manifest) expected = SkyulfSchema( artifact.manifest.input_columns, dict(zip(artifact.manifest.input_columns, artifact.manifest.input_dtypes, strict=True)), @@ -250,3 +261,12 @@ def predict_local_pipeline( for position in range(len(artifact.manifest.classes)): result[f"probability_{position}"] = probabilities[:, position] return result + + +def _prediction_frame( + frame: pd.DataFrame | pl.DataFrame, manifest: LocalPipelineManifest +) -> pd.DataFrame | pl.DataFrame: + """Convert inputs to the engine recorded during the successful model fit.""" + if manifest.fitted_engine == "polars": + return pl.from_pandas(frame) if isinstance(frame, pd.DataFrame) else frame + return frame.to_pandas() if isinstance(frame, pl.DataFrame) else frame diff --git a/skyulf-core/skyulf/inference/project_code.py b/skyulf-core/skyulf/inference/project_code.py index 2868ebbb6..0c9b064db 100644 --- a/skyulf-core/skyulf/inference/project_code.py +++ b/skyulf-core/skyulf/inference/project_code.py @@ -64,41 +64,9 @@ def custom_step( must live in the same source file. Pre-split use requires an explicit filter-only declaration; it is an assertion by trusted project code. """ - if ( - not isinstance(calculator, type) - or not isinstance(applier, type) - or not calculator.__module__.startswith(_PREFIX) - or calculator.__module__ != applier.__module__ - or "" in calculator.__qualname__ - or "" in applier.__qualname__ - ): - raise ValueError("Custom classes must be top-level definitions in preprocessing.py.") - if not callable(getattr(calculator, "fit", None)) or not callable( - getattr(applier, "apply", None) - ): - raise ValueError("Custom preprocessing needs calculator.fit and applier.apply.") + _validate_custom_classes(calculator, applier) if pre_split is not None: - columns = pre_split.get("required_columns") if type(pre_split) is dict else None - if ( - type(pre_split) is not dict - or set(pre_split) != {"effect", "required_columns", "learns_from_data"} - or pre_split["effect"] != "filter" - or pre_split["learns_from_data"] is not False - or type(columns) is not list - or not columns - or any( - type(column) is not str - or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", column) - or column.casefold().startswith("__skyulf_") - for column in columns - ) - or len({column.casefold() for column in columns}) != len(columns) - ): - raise ValueError( - "Custom pre_split declaration requires effect='filter', distinct simple " - "required_columns, and learns_from_data=False; use ordinary custom " - "preprocessing for value changes." - ) + _validate_pre_split(pre_split) identity = f"{calculator.__module__}.{calculator.__qualname__}.{applier.__qualname__}" try: registered = NodeRegistry.get_calculator(identity) @@ -113,6 +81,54 @@ def custom_step( return step +def _validate_custom_classes(calculator: type, applier: type) -> None: + """Require project-owned top-level implementations of the fit/apply pair.""" + if ( + not isinstance(calculator, type) + or not isinstance(applier, type) + or not calculator.__module__.startswith(_PREFIX) + or calculator.__module__ != applier.__module__ + or "" in calculator.__qualname__ + or "" in applier.__qualname__ + ): + raise ValueError("Custom classes must be top-level definitions in preprocessing.py.") + if not callable(getattr(calculator, "fit", None)) or not callable( + getattr(applier, "apply", None) + ): + raise ValueError("Custom preprocessing needs calculator.fit and applier.apply.") + + +def _validate_pre_split(pre_split: dict[str, Any]) -> None: + """Require an explicit filter-only declaration with valid required columns.""" + columns = pre_split.get("required_columns") if type(pre_split) is dict else None + if ( + type(pre_split) is not dict + or set(pre_split) != {"effect", "required_columns", "learns_from_data"} + or pre_split["effect"] != "filter" + or pre_split["learns_from_data"] is not False + or not _valid_required_columns(columns) + ): + raise ValueError( + "Custom pre_split declaration requires effect='filter', distinct simple " + "required_columns, and learns_from_data=False; use ordinary custom " + "preprocessing for value changes." + ) + + +def _valid_required_columns(columns: Any) -> bool: + """Recognize distinct simple column identifiers outside the reserved namespace.""" + if type(columns) is not list or not columns: + return False + if any( + type(column) is not str + or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", column) + or column.casefold().startswith("__skyulf_") + for column in columns + ): + return False + return len({column.casefold() for column in columns}) == len(columns) + + def is_registered_project_step(identity: str) -> bool: """Recognize only an exact class pair registered from isolated project source.""" if not isinstance(identity, str) or not identity.startswith(_PREFIX): diff --git a/skyulf-core/skyulf/inference/spark.py b/skyulf-core/skyulf/inference/spark.py index aa5df3bed..d6f054f2a 100644 --- a/skyulf-core/skyulf/inference/spark.py +++ b/skyulf-core/skyulf/inference/spark.py @@ -49,6 +49,25 @@ def predict_spark( the caller's session separately; this function never changes that setting. Estimator pickle payloads must come from a trusted producer. """ + _validate_execution(frame_spec, options, mode) + _validate_bundle(bundle, options) + manifest = bundle.manifest + if manifest.input_stage != "raw": + raise ValueError(f"{mode} currently requires a raw input_stage bundle.") + native = _native(frame) + if native.isStreaming: + raise UnsupportedExecutionError( + "inference", "predict", "spark", "Streaming inference is not supported." + ) + _validate_names_and_keys(native, manifest, frame_spec) + selected = _select_input(native, manifest, frame_spec, mode) + if mode == "python_pipeline": + return _predict_python_pipeline(native, selected, bundle, frame_spec, options) + return _predict_native_features(native, selected, bundle, frame_spec, options) + + +def _validate_execution(frame_spec: FrameSpec, options: ExecutionOptions, mode: str) -> None: + """Validate the requested Spark inference context before inspecting bundle payloads.""" if not isinstance(frame_spec, FrameSpec): raise TypeError("frame_spec must be FrameSpec.") if not isinstance(options, ExecutionOptions) or options.engine != "spark": @@ -62,16 +81,10 @@ def predict_spark( "spark", "Only mode='native_features' or mode='python_pipeline' is implemented.", ) - _validate_bundle(bundle, options) - manifest = bundle.manifest - if manifest.input_stage != "raw": - raise ValueError(f"{mode} currently requires a raw input_stage bundle.") - native = _native(frame) - if native.isStreaming: - raise UnsupportedExecutionError( - "inference", "predict", "spark", "Streaming inference is not supported." - ) - _validate_names_and_keys(native, manifest, frame_spec) + + +def _select_input(native: Any, manifest: BundleManifest, frame_spec: FrameSpec, mode: str) -> Any: + """Validate model input positions before projecting worker keys and raw features.""" input_names = {column.name for column in manifest.input_schema} raw = native.select(*[_column(native, name) for name in native.columns if name in input_names]) _validate_frame(raw, manifest.input_schema, "bundle input") @@ -81,24 +94,45 @@ def predict_spark( if mode == "python_pipeline" else tuple(frame_spec.record_key_columns) + tuple(raw.columns) ) - selected = native.select(*[_column(native, name) for name in selected_names]) - if mode == "python_pipeline": - _validate_python_input_transport(native, manifest) - engineer = FeatureEngineer.from_state( - bundle.feature_state, - execution_options=ExecutionOptions("pandas", state_max_bytes=options.state_max_bytes), - ) - _validate_python_pipeline(engineer) - _validate_keys(native, frame_spec) - worker = _python_pipeline_prediction_iterator( - bundle.feature_state, - bundle.model_payload, - manifest, - frame_spec.record_key_columns, - options.python_batch_rows, - options.state_max_bytes, - ) - return selected.mapInPandas(worker, schema=_prediction_schema(native, manifest, frame_spec)) + return native.select(*[_column(native, name) for name in selected_names]) + + +def _predict_python_pipeline( + native: Any, + selected: Any, + bundle: InferenceBundle, + frame_spec: FrameSpec, + options: ExecutionOptions, +) -> Any: + """Validate worker-local FE and key transport before distributing frozen payloads.""" + manifest = bundle.manifest + _validate_python_input_transport(native, manifest) + engineer = FeatureEngineer.from_state( + bundle.feature_state, + execution_options=ExecutionOptions("pandas", state_max_bytes=options.state_max_bytes), + ) + _validate_python_pipeline(engineer) + _validate_keys(native, frame_spec) + worker = _python_pipeline_prediction_iterator( + bundle.feature_state, + bundle.model_payload, + manifest, + frame_spec.record_key_columns, + options.python_batch_rows, + options.state_max_bytes, + ) + return selected.mapInPandas(worker, schema=_prediction_schema(native, manifest, frame_spec)) + + +def _predict_native_features( + native: Any, + selected: Any, + bundle: InferenceBundle, + frame_spec: FrameSpec, + options: ExecutionOptions, +) -> Any: + """Preview native FE schemas, transform rows and distribute model prediction.""" + manifest = bundle.manifest engineer = FeatureEngineer.from_state( bundle.feature_state, execution_options=options, frame_spec=frame_spec ) @@ -272,6 +306,11 @@ def names(columns: tuple[str, ...]) -> set[str]: raise ValueError("Input and prediction output columns collide.") if len(raw) != len(manifest.input_schema) or len(features) != len(manifest.feature_order): raise ValueError("Duplicate Spark feature names in bundle schema.") + _validate_key_types(frame, spec) + + +def _validate_key_types(frame: Any, spec: FrameSpec) -> None: + """Require all declared record keys and primitive Arrow-compatible key types.""" missing = set(spec.record_key_columns).difference(frame.columns) if missing: raise ValueError(f"Missing Spark record_key_columns: {sorted(missing)}") diff --git a/skyulf-core/skyulf/integrations/databricks/_contracts.py b/skyulf-core/skyulf/integrations/databricks/_contracts.py index b8345faff..79d2b50b6 100644 --- a/skyulf-core/skyulf/integrations/databricks/_contracts.py +++ b/skyulf-core/skyulf/integrations/databricks/_contracts.py @@ -64,40 +64,9 @@ class BatchSpec: def __post_init__(self) -> None: """Reject ambiguity before any Spark action or table modification.""" - for name in ("period_start", "period_end", "as_of"): - value = getattr(self, name) - if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: - raise ValueError(f"{name} must be timezone-aware.") - # Reject nonexistent local times; fold explicitly resolves ambiguous times. - if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( - tzinfo=None - ): - raise ValueError(f"{name} is not a valid local instant.") - if self.period_start_utc >= self.period_end_utc: - raise ValueError("period_start must precede period_end.") - table_name(self.output_table) - column_name(self.period_column) - if type(self.record_key_columns) is not tuple or not self.record_key_columns: - raise ValueError("record_key_columns must be a nonempty tuple.") - for key in self.record_key_columns: - column_name(key) - names = [key.lower() for key in self.record_key_columns] - if len(set(names)) != len(names) or self.period_column.lower() in names: - raise ValueError("record_key_columns and period_column must be distinct.") - if any( - name in PREDICTION_METADATA_COLUMNS for name in (*names, self.period_column.lower()) - ): - raise ValueError( - "record_key_columns and period_column collide with prediction metadata." - ) - for name in ("model_name", "code_version", "run_id"): - value = getattr(self, name) - if type(value) is not str or not value.strip() or len(value) > 512: - raise ValueError(f"{name} must be a nonempty string of at most 512 characters.") - if type(self.model_version) is not str or not re.fullmatch( - r"[1-9][0-9]*", self.model_version - ): - raise ValueError("model_version must be a concrete positive version, not an alias.") + _validate_batch_period(self) + _validate_batch_columns(self) + _validate_batch_model_identity(self) for name in ("source_version", "expected_target_version"): value = getattr(self, name) if type(value) is not int or value < 0: @@ -143,3 +112,43 @@ class BatchResult: commit_version: int manifest: dict[str, Any] replayed: bool = False + + +def _validate_batch_period(spec: BatchSpec) -> None: + """Validate aware period instants and their chronological order.""" + for name in ("period_start", "period_end", "as_of"): + value = getattr(spec, name) + if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware.") + # Reject nonexistent local times; fold explicitly resolves ambiguous times. + if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( + tzinfo=None + ): + raise ValueError(f"{name} is not a valid local instant.") + if spec.period_start_utc >= spec.period_end_utc: + raise ValueError("period_start must precede period_end.") + + +def _validate_batch_columns(spec: BatchSpec) -> None: + """Validate target identifiers and distinct control columns.""" + table_name(spec.output_table) + column_name(spec.period_column) + if type(spec.record_key_columns) is not tuple or not spec.record_key_columns: + raise ValueError("record_key_columns must be a nonempty tuple.") + for key in spec.record_key_columns: + column_name(key) + names = [key.lower() for key in spec.record_key_columns] + if len(set(names)) != len(names) or spec.period_column.lower() in names: + raise ValueError("record_key_columns and period_column must be distinct.") + if any(name in PREDICTION_METADATA_COLUMNS for name in (*names, spec.period_column.lower())): + raise ValueError("record_key_columns and period_column collide with prediction metadata.") + + +def _validate_batch_model_identity(spec: BatchSpec) -> None: + """Validate bounded model identity strings and the concrete model version.""" + for name in ("model_name", "code_version", "run_id"): + value = getattr(spec, name) + if type(value) is not str or not value.strip() or len(value) > 512: + raise ValueError(f"{name} must be a nonempty string of at most 512 characters.") + if type(spec.model_version) is not str or not re.fullmatch(r"[1-9][0-9]*", spec.model_version): + raise ValueError("model_version must be a concrete positive version, not an alias.") diff --git a/skyulf-core/skyulf/integrations/databricks/_lifecycle_state.py b/skyulf-core/skyulf/integrations/databricks/_lifecycle_state.py index 0670d7589..8978e3f91 100644 --- a/skyulf-core/skyulf/integrations/databricks/_lifecycle_state.py +++ b/skyulf-core/skyulf/integrations/databricks/_lifecycle_state.py @@ -108,6 +108,13 @@ def bind(self, reference: dict[str, str]) -> None: self.run_id = reference["run_id"] self.request_digest = reference["request_sha256"] self.request = self.read("lifecycle/request.json") + self._validate_bound_request() + receipt = self.receipt(reference["phase"]) + if evidence_digest(receipt) != reference["receipt_sha256"]: + raise ValueError("Lifecycle predecessor receipt digest differs from its reference.") + + def _validate_bound_request(self) -> None: + """Verify the loaded request identity and saved integrity tag.""" if ( self.request.get("version") != 1 or self.request.get("context") != self.context.identity() @@ -116,9 +123,6 @@ def bind(self, reference: dict[str, str]) -> None: or self.tags().get("skyulf.lifecycle.request") != self.request_digest ): raise ValueError("Lifecycle invocation or pinned request differs from its reference.") - receipt = self.receipt(reference["phase"]) - if evidence_digest(receipt) != reference["receipt_sha256"]: - raise ValueError("Lifecycle predecessor receipt digest differs from its reference.") def receipt(self, phase: str) -> dict[str, Any]: """Verify the saved receipt and its entire predecessor chain before reuse.""" @@ -136,6 +140,11 @@ def receipt(self, phase: str) -> dict[str, Any]: raise ValueError( "Lifecycle predecessor identity or digest differs from saved evidence." ) + self._validate_predecessor_chain(phase, value) + return value + + def _validate_predecessor_chain(self, phase: str, value: dict[str, Any]) -> None: + """Recursively verify the expected predecessor before reusing a receipt.""" previous = value.get("predecessor") expected = _PREDECESSORS.get(phase) if expected is None: @@ -147,7 +156,6 @@ def receipt(self, phase: str) -> dict[str, Any]: or previous != self.reference(self.receipt(expected)) ): raise ValueError("Lifecycle predecessor identity differs from saved evidence.") - return value def reference(self, receipt: dict[str, Any]) -> dict[str, str]: """Expose only durable identity and digest strings to task values.""" diff --git a/skyulf-core/skyulf/integrations/databricks/batch.py b/skyulf-core/skyulf/integrations/databricks/batch.py index e73d68f57..d34242152 100644 --- a/skyulf-core/skyulf/integrations/databricks/batch.py +++ b/skyulf-core/skyulf/integrations/databricks/batch.py @@ -36,22 +36,7 @@ def run_batch( Output stays distributed when serverless rejects persistence; classic Spark caches it through receipt validation and then releases the cached frame. """ - if not isinstance(options, ExecutionOptions) or options.engine != "spark": - raise ValueError("run_batch requires ExecutionOptions(engine='spark').") - if not isinstance(spec, BatchSpec): - raise TypeError("spec must be BatchSpec.") - if spec.mode == "local_pipeline": - raise ValueError("run_batch requires a Spark inference mode.") - admission = validate_admission(spark, admission) - table_name(source) - _validate_bundle(bundle, options) - if bundle.semantic_digest != spec.model_digest: - raise ValueError("Bundle digest differs from the selected model identity.") - runtime_version = version("skyulf-core") - if spec.code_version != runtime_version: - raise ValueError("code_version differs from the installed skyulf-core runtime.") - if bundle.input_stage != "raw": - raise ValueError("Spark batch inference requires a raw bundle.") + admission = _validate_batch_request(spark, spec, source, bundle, options, admission) source_id = table_identity(spark, source) if source_id == table_identity(spark, spec.output_table): raise ValueError("Batch source and output table must be different.") @@ -67,23 +52,7 @@ def run_batch( frame = spark.read.format("delta").option("versionAsOf", spec.source_version).table(source) if table_identity(spark, source) != source_id: raise ValueError("Source table was replaced while pinning the snapshot.") - period = frame[spec.period_column] - if frame.schema[spec.period_column].dataType.typeName() != "timestamp": - raise ValueError("period_column requires Spark timestamp, not a string/date/timestamp_ntz.") - if frame.where(period.isNull()).limit(1).count(): - raise ValueError("Source period_column contains null timestamps.") - selected = frame.where( - (period >= functions.lit(spec.period_start_utc)) - & (period < functions.lit(spec.period_end_utc)) - ) - input_count = selected.count() - if not input_count and not spec.allow_empty: - raise ValueError("Empty period replacement requires allow_empty=True.") - output_names = {column.name.lower() for column in bundle.manifest.output_schema} - if spec.period_column.lower() in output_names: - raise ValueError("period_column collides with a model output column.") - if output_names.intersection(PREDICTION_METADATA_COLUMNS): - raise ValueError("Model output column collides with prediction metadata.") + selected, input_count = _select_batch_period(frame, spec, bundle, functions) predictions = predict_spark( selected, bundle, @@ -96,27 +65,8 @@ def run_batch( on=list(spec.record_key_columns), how="inner", ) - for name, value in ( - ("run_id", spec.run_id), - ("model_name", spec.model_name), - ("model_version", spec.model_version), - ): - output = output.withColumn(name, functions.lit(value)) - target = spark.table(spec.output_table) - if {f.name: f.dataType for f in output.schema} != {f.name: f.dataType for f in target.schema}: - raise ValueError("Output schema must match the precreated Delta target exactly.") - output = output.select(*target.columns) - persisted = False - try: - output = output.persist() - except Exception as exc: # noqa: BLE001 - Spark Connect wraps structured runtime errors - condition = getattr(exc, "getCondition", None) - if not callable(condition): - condition = getattr(exc, "getErrorClass", None) - if not callable(condition) or condition() != "NOT_SUPPORTED_WITH_SERVERLESS": - raise - else: - persisted = True + output = _complete_batch_output(spark, output, spec, functions) + output, persisted = _persist_batch_output(output) try: output_count = output.count() if input_count != output_count: @@ -162,3 +112,86 @@ def _manifest( source_committed_us=committed_us, source_temporal_contract="delta_snapshot_committed_by_as_of", ) + + +def _validate_batch_request( + spark: Any, + spec: BatchSpec, + source: str, + bundle: InferenceBundle, + options: ExecutionOptions, + admission: PublishAdmission | None, +) -> PublishAdmission: + """Validate execution, admission and artifact identity before reading tables.""" + if not isinstance(options, ExecutionOptions) or options.engine != "spark": + raise ValueError("run_batch requires ExecutionOptions(engine='spark').") + if not isinstance(spec, BatchSpec): + raise TypeError("spec must be BatchSpec.") + if spec.mode == "local_pipeline": + raise ValueError("run_batch requires a Spark inference mode.") + admission = validate_admission(spark, admission) + table_name(source) + _validate_bundle(bundle, options) + if bundle.semantic_digest != spec.model_digest: + raise ValueError("Bundle digest differs from the selected model identity.") + runtime_version = version("skyulf-core") + if spec.code_version != runtime_version: + raise ValueError("code_version differs from the installed skyulf-core runtime.") + if bundle.input_stage != "raw": + raise ValueError("Spark batch inference requires a raw bundle.") + return admission + + +def _select_batch_period( + frame: Any, spec: BatchSpec, bundle: InferenceBundle, functions: Any +) -> tuple[Any, int]: + """Select the bounded period and validate row count and output names.""" + period = frame[spec.period_column] + if frame.schema[spec.period_column].dataType.typeName() != "timestamp": + raise ValueError("period_column requires Spark timestamp, not a string/date/timestamp_ntz.") + if frame.where(period.isNull()).limit(1).count(): + raise ValueError("Source period_column contains null timestamps.") + selected = frame.where( + (period >= functions.lit(spec.period_start_utc)) + & (period < functions.lit(spec.period_end_utc)) + ) + input_count = selected.count() + if not input_count and not spec.allow_empty: + raise ValueError("Empty period replacement requires allow_empty=True.") + output_names = {column.name.lower() for column in bundle.manifest.output_schema} + if spec.period_column.lower() in output_names: + raise ValueError("period_column collides with a model output column.") + if output_names.intersection(PREDICTION_METADATA_COLUMNS): + raise ValueError("Model output column collides with prediction metadata.") + return selected, input_count + + +def _persist_batch_output(output: Any) -> tuple[Any, bool]: + """Persist classic Spark output while accepting only the serverless limitation.""" + persisted = False + try: + output = output.persist() + except Exception as exc: # noqa: BLE001 - Spark Connect wraps structured runtime errors + condition = getattr(exc, "getCondition", None) + if not callable(condition): + condition = getattr(exc, "getErrorClass", None) + if not callable(condition) or condition() != "NOT_SUPPORTED_WITH_SERVERLESS": + raise + else: + persisted = True + return output, persisted + + +def _complete_batch_output(spark: Any, output: Any, spec: BatchSpec, functions: Any) -> Any: + """Attach concrete model metadata and check the precreated Delta schema.""" + for name, value in ( + ("run_id", spec.run_id), + ("model_name", spec.model_name), + ("model_version", spec.model_version), + ): + output = output.withColumn(name, functions.lit(value)) + target = spark.table(spec.output_table) + if {f.name: f.dataType for f in output.schema} != {f.name: f.dataType for f in target.schema}: + raise ValueError("Output schema must match the precreated Delta target exactly.") + output = output.select(*target.columns) + return output diff --git a/skyulf-core/skyulf/integrations/databricks/delta_admission.py b/skyulf-core/skyulf/integrations/databricks/delta_admission.py index 139dd0479..0b7e455d0 100644 --- a/skyulf-core/skyulf/integrations/databricks/delta_admission.py +++ b/skyulf-core/skyulf/integrations/databricks/delta_admission.py @@ -55,16 +55,7 @@ def _state(self, target_id: str) -> str | None: if self._identity() != self._control_id: raise BatchConflictError("Control table identity changed during admission.") frame = self._spark.table(self._table) - fields = {field.name: field for field in frame.schema} - if ( - len(frame.schema) != 2 - or set(fields) != {"target_id", "owner"} - or any(field.dataType.typeName() != "string" for field in fields.values()) - or not fields["owner"].nullable - ): - raise ValueError( - "Control table requires only target_id STRING and nullable owner STRING." - ) + _validate_control_schema(frame) rows = frame.limit(2).collect() if len(rows) != 1 or rows[0]["target_id"] != target_id: raise ValueError("Control table must contain exactly one row bound to this target ID.") @@ -124,3 +115,15 @@ def hold(self, table_id: str) -> Iterator[None]: # A new publisher may acquire immediately after this release commits. if self._state(table_id) == token: raise BatchConflictError("Admission release could not be verified.") + + +def _validate_control_schema(frame: Any) -> None: + """Require the exact nullable ownership schema before reading control rows.""" + fields = {field.name: field for field in frame.schema} + if ( + len(frame.schema) != 2 + or set(fields) != {"target_id", "owner"} + or any(field.dataType.typeName() != "string" for field in fields.values()) + or not fields["owner"].nullable + ): + raise ValueError("Control table requires only target_id STRING and nullable owner STRING.") diff --git a/skyulf-core/skyulf/integrations/databricks/job_output.py b/skyulf-core/skyulf/integrations/databricks/job_output.py index 745d7641c..07148a9a8 100644 --- a/skyulf-core/skyulf/integrations/databricks/job_output.py +++ b/skyulf-core/skyulf/integrations/databricks/job_output.py @@ -137,6 +137,70 @@ def render_lifecycle_output(phase: str, payload: dict[str, Any]) -> str: if isinstance(value, (str, int, float, bool)) and not key.endswith(("sha256", "digest")) ] sections = [f"

{_text(titles.get(phase, phase))}

", _table(("Result", "Value"), rows)] + _append_training_output(sections, payload) + candidate = payload.get("candidate", payload) + if "candidate" in payload: + sections.append( + f"

Candidate: {_text(candidate.get('model_name', ''))} " + f"v{_text(candidate.get('model_version', ''))}

" + ) + sections.extend(_comparison_summary(candidate)) + receipt = payload.get("alias_change") or payload.get("result") or {} + if phase == "operator" and receipt.get("model_name"): + sections.append(f"

Model: {_text(receipt['model_name'])}

") + sections.extend(_receipt_summary(receipt)) + _append_lifecycle_actions(sections, phase, payload) + raw = json.dumps(payload, indent=2, default=str, allow_nan=False) + sections.append( + f"
Technical details (JSON)
{_text(raw)}
" + ) + return '
' + "".join(sections) + "
" + + +def render_bundle_output(payload: dict[str, Any]) -> str: + """Present lifecycle, comparison, scoring and next steps with raw JSON in a disclosure. + + The report describes only this task's completed work. A handoff request + does not imply success of the separate score job. No-op manifests describe + the previous prediction write, not the model selected by the current run. + """ + action = payload["action"] + result = payload["result"] + candidate = result.get("candidate", result) + receipt = result.get("alias_change") or result + sections = [f"

{_text(action.replace('_', ' ').title())} completed

"] + sections.extend(_receipt_summary(receipt)) + name = candidate.get("model_name") or receipt.get("model_name") + if name: + sections.append(f"

Model: {_text(name)}

") + if action.startswith("train"): + sections.append( + f"

Candidate version: {_text(candidate.get('model_version'))}

" + ) + sections.extend(_comparison_summary(candidate)) + if action == "score": + _append_scoring_output(sections, result) + elif payload["score_requested"]: + sections.append("

Scoring requested. Check the child score run for its result.

") + else: + sections.append("

This action did not request scoring.

") + _append_operator_options(sections, payload, receipt) + raw = json.dumps(payload, indent=2, default=str, allow_nan=False) + sections.append( + f"
Technical details (JSON)
{_text(raw)}
" + ) + return ( + '
' + "" + + "".join(sections) + + "
" + ) + + +def _append_training_output(sections: list[str], payload: dict[str, Any]) -> None: + """Render measured training metrics, tuning evidence and optional explanations.""" metrics = payload.get("metrics") if isinstance(metrics, dict): sections.append(_table(("Metric", "Value"), list(metrics.items()))) @@ -167,17 +231,10 @@ def render_lifecycle_output(phase: str, payload: dict[str, Any]) -> str: if isinstance(explanation, dict): sections.append("

Model explanations

") sections.append(_table(("Result", "Value"), list(explanation.items()))) - candidate = payload.get("candidate", payload) - if "candidate" in payload: - sections.append( - f"

Candidate: {_text(candidate.get('model_name', ''))} " - f"v{_text(candidate.get('model_version', ''))}

" - ) - sections.extend(_comparison_summary(candidate)) - receipt = payload.get("alias_change") or payload.get("result") or {} - if phase == "operator" and receipt.get("model_name"): - sections.append(f"

Model: {_text(receipt['model_name'])}

") - sections.extend(_receipt_summary(receipt)) + + +def _append_lifecycle_actions(sections: list[str], phase: str, payload: dict[str, Any]) -> None: + """Explain unchanged aliases and point operators to the final report.""" if phase in {"decide", "compare_decide"} and not payload.get("alias_change"): sections.append( "

Awaiting manual review. Champion is unchanged.

" @@ -189,72 +246,49 @@ def render_lifecycle_output(phase: str, payload: dict[str, Any]) -> str: "

Open finalize_and_report for the final decision " "and operator actions.

" ) - raw = json.dumps(payload, indent=2, default=str, allow_nan=False) - sections.append( - f"
Technical details (JSON)
{_text(raw)}
" - ) - return '
' + "".join(sections) + "
" - -def render_bundle_output(payload: dict[str, Any]) -> str: - """Present lifecycle, comparison, scoring and next steps with raw JSON in a disclosure. - The report describes only this task's completed work. A handoff request - does not imply success of the separate score job. No-op manifests describe - the previous prediction write, not the model selected by the current run. - """ - action = payload["action"] - result = payload["result"] - candidate = result.get("candidate", result) - receipt = result.get("alias_change") or result - sections = [f"

{_text(action.replace('_', ' ').title())} completed

"] - sections.extend(_receipt_summary(receipt)) - name = candidate.get("model_name") or receipt.get("model_name") - if name: - sections.append(f"

Model: {_text(name)}

") - if action.startswith("train"): +def _append_scoring_output(sections: list[str], result: dict[str, Any]) -> None: + """Distinguish this run's scoring result from a previous no-op manifest.""" + if result.get("selected_model_version"): sections.append( - f"

Candidate version: {_text(candidate.get('model_version'))}

" + "

Selected model for this run: " + f"{_text(result.get('selected_model_name'))} " + f"v{_text(result['selected_model_version'])}

" ) - sections.extend(_comparison_summary(candidate)) - if action == "score": - if result.get("selected_model_version"): - sections.append( - "

Selected model for this run: " - f"{_text(result.get('selected_model_name'))} " - f"v{_text(result['selected_model_version'])}

" - ) - noop = result.get("noop", False) - sections.append( - "

No new predictions written.

" - if noop - else "

Prediction write completed.

" + noop = result.get("noop", False) + sections.append( + "

No new predictions written.

" + if noop + else "

Prediction write completed.

" + ) + sections.append( + _table( + ("Result", "Value"), + [ + (label, result[key]) + for key, label in ( + ("input_count", "Input rows"), + ("output_count", "Output rows"), + ("commit_version", "Prediction table Delta version"), + ) + if key in result + ], ) + ) + manifest = result.get("manifest", {}) + if manifest: + label = "Model recorded by the previous write" if noop else "Prediction model" sections.append( - _table( - ("Result", "Value"), - [ - (label, result[key]) - for key, label in ( - ("input_count", "Input rows"), - ("output_count", "Output rows"), - ("commit_version", "Prediction table Delta version"), - ) - if key in result - ], - ) + f"

{label}: {_text(manifest.get('model_name'))} " + f"v{_text(manifest.get('model_version'))}

" ) - manifest = result.get("manifest", {}) - if manifest: - label = "Model recorded by the previous write" if noop else "Prediction model" - sections.append( - f"

{label}: {_text(manifest.get('model_name'))} " - f"v{_text(manifest.get('model_version'))}

" - ) - elif payload["score_requested"]: - sections.append("

Scoring requested. Check the child score run for its result.

") - else: - sections.append("

This action did not request scoring.

") + + +def _append_operator_options( + sections: list[str], payload: dict[str, Any], receipt: dict[str, Any] +) -> None: + """Render explicit next actions and the guarded rollback target.""" for next_action, parameters in payload.get("next_actions", {}).items(): rollback = next_action == "rollback" if rollback: @@ -290,15 +324,3 @@ def render_bundle_output(payload: dict[str, Any]) -> str: sections.append(_table(("Parameter", "Value"), rows)) if rollback: sections.append("
") - raw = json.dumps(payload, indent=2, default=str, allow_nan=False) - sections.append( - f"
Technical details (JSON)
{_text(raw)}
" - ) - return ( - '
' - "" - + "".join(sections) - + "
" - ) diff --git a/skyulf-core/skyulf/integrations/databricks/job_runtime.py b/skyulf-core/skyulf/integrations/databricks/job_runtime.py index 98485c194..12a0b48b6 100644 --- a/skyulf-core/skyulf/integrations/databricks/job_runtime.py +++ b/skyulf-core/skyulf/integrations/databricks/job_runtime.py @@ -61,22 +61,7 @@ def _operator_options(action: str, values: dict[str, str]) -> dict[str, Any]: ) options: dict[str, Any] = {"expected_champion_version": expected} if action == "rollback": - try: - payload = json.loads(values.get("promotion_receipt_json", "")) - if not isinstance(payload, dict) or any( - value is not None and not isinstance(value, str) for value in payload.values() - ): - raise ValueError - receipt = AliasChangeReceipt(**payload) - if receipt.kind != "promotion" or receipt.alias != "champion": - raise ValueError - if receipt.new_version != expected or receipt.prior_version is None: - raise ValueError - _version(receipt.prior_version) - except (TypeError, ValueError) as exc: - raise ValueError( - "Rollback needs a complete promotion_receipt_json matching the expected champion." - ) from exc + receipt = _rollback_receipt(values, expected) options["promotion_receipt"] = receipt return options options["candidate_version"] = _version(values.get("candidate_version", "")) @@ -92,6 +77,32 @@ def _operator_options(action: str, values: dict[str, str]) -> dict[str, Any]: return options +def _rollback_receipt(values: dict[str, str], expected: str | None) -> AliasChangeReceipt: + """Parse a complete promotion receipt and preserve a single operator-facing failure.""" + try: + payload = json.loads(values.get("promotion_receipt_json", "")) + if not isinstance(payload, dict) or any( + value is not None and not isinstance(value, str) for value in payload.values() + ): + raise ValueError + receipt = AliasChangeReceipt(**payload) + _validate_rollback_receipt(receipt, expected) + except (TypeError, ValueError) as exc: + raise ValueError( + "Rollback needs a complete promotion_receipt_json matching the expected champion." + ) from exc + return receipt + + +def _validate_rollback_receipt(receipt: AliasChangeReceipt, expected: str | None) -> None: + """Require a champion promotion matching both sides of the rollback guard.""" + if receipt.kind != "promotion" or receipt.alias != "champion": + raise ValueError + if receipt.new_version != expected or receipt.prior_version is None: + raise ValueError + _version(receipt.prior_version) + + def run_bundle_action( spark: Any, config: dict[str, Any], @@ -114,26 +125,8 @@ def run_bundle_action( _, policy = _workflow_policies(config) if config.get("score_handoff") not in {"disabled", "after_alias_change"}: raise ValueError("score_handoff must be disabled or after_alias_change.") - for key in _OPERATOR_FIELDS | { - "lifecycle_action", - "task_role", - "action", - "score_model_version", - }: - if key in parameters and not isinstance(parameters[key], str): - raise ValueError("Job parameters must be strings.") - if parameters.get("task_role") or parameters.get("action"): - raise ValueError("Notebook role and score action cannot be overridden by job parameters.") - if task_role == "score": - if parameters.get("lifecycle_action"): - raise ValueError("Score job refuses lifecycle actions.") - action = "score" - elif task_role == "lifecycle": - action = parameters.get("lifecycle_action", "") - if action not in {"train", "approve", "reject", "rollback"}: - raise ValueError("Lifecycle action must be train, approve, reject or rollback.") - else: - raise ValueError("Notebook task_role must be lifecycle or score.") + _validate_job_parameters(parameters) + action = _role_action(task_role, parameters) override = parameters.get("score_model_version", "") if override: if action != "score": @@ -156,6 +149,35 @@ def run_bundle_action( return _bundle_result(config, action, result) +def _validate_job_parameters(parameters: dict[str, str]) -> None: + """Reject malformed or role-overriding job inputs before selecting an action.""" + for key in _OPERATOR_FIELDS | { + "lifecycle_action", + "task_role", + "action", + "score_model_version", + }: + if key in parameters and not isinstance(parameters[key], str): + raise ValueError("Job parameters must be strings.") + if parameters.get("task_role") or parameters.get("action"): + raise ValueError("Notebook role and score action cannot be overridden by job parameters.") + + +def _role_action(task_role: str, parameters: dict[str, str]) -> str: + """Map a deployed notebook role to its allowed requested action.""" + if task_role == "score": + if parameters.get("lifecycle_action"): + raise ValueError("Score job refuses lifecycle actions.") + action = "score" + elif task_role == "lifecycle": + action = parameters.get("lifecycle_action", "") + if action not in {"train", "approve", "reject", "rollback"}: + raise ValueError("Lifecycle action must be train, approve, reject or rollback.") + else: + raise ValueError("Notebook task_role must be lifecycle or score.") + return action + + def _read_notebook_config(values: dict[str, str]) -> dict[str, Any]: """Load and bind the project once at the notebook's configuration boundary.""" config = json.loads(Path(values["config_path"]).read_text(encoding="utf-8")) diff --git a/skyulf-core/skyulf/integrations/databricks/lifecycle_tasks.py b/skyulf-core/skyulf/integrations/databricks/lifecycle_tasks.py index 9afe5ccd6..c99ae443c 100644 --- a/skyulf-core/skyulf/integrations/databricks/lifecycle_tasks.py +++ b/skyulf-core/skyulf/integrations/databricks/lifecycle_tasks.py @@ -58,6 +58,74 @@ def _spec(payload: dict[str, Any], source: str | None) -> training.LocalTraining return training.LocalTrainingSpec.from_payload(payload) +def _prepare_training_request( + spark: Any, + request: dict[str, Any], + config: dict[str, Any], + options: dict[str, Any], + policy: str, + now: datetime | None, +) -> None: + """Pin source, champion and effective recipe before creating a lifecycle run.""" + if options: + raise ValueError("Training cannot accept operator options.") + spec, cv, champion = workflow._prepare_training(spark, config, policy=policy, now=now) + if config.get("champion_version") is not None and str(config["champion_version"]) != champion: + raise ValueError("champion_version does not match the current champion.") + effective = training._candidate_config( + spec, + config["pipeline"], + engine=config["engine"], + cv=cv, + metric=config["metric"], + min_improvement=config["min_improvement"], + champion_version=champion, + quality_threshold=config.get("quality_threshold"), + quality_gates=config.get("quality_gates"), + risk_category=config.get("risk_category"), + ) + request.update( + spec=training._training_spec_payload(spec, config["engine"]), + champion_version=champion, + effective_config=effective, + ) + + +def _prepared_output( + request: dict[str, Any], + config: dict[str, Any], + action: str, + options: dict[str, Any], +) -> dict[str, Any]: + """Describe the pinned training source or the selected operator request.""" + output = { + "action": action, + "training_requested": action == "train", + "model_name": config["model_name"], + } + if action == "train": + pinned = request["spec"] + output.update( + source_table=pinned["table"], + source_version=pinned["version"], + engine=pinned["engine"], + split_strategy=pinned["split_strategy"], + expected_champion_version=request["champion_version"], + ) + output |= { + field: pinned[field] + for field in ("start", "holdout_start", "cutoff", "result_cutoff") + if pinned[field] is not None + } + else: + output |= { + field: options[field] + for field in ("candidate_version", "expected_champion_version") + if field in options + } + return output + + def _prepare( spark: Any, store: _PhaseStore, @@ -83,31 +151,7 @@ def _prepare( "operator_options": options, } if action == "train": - if options: - raise ValueError("Training cannot accept operator options.") - spec, cv, champion = workflow._prepare_training(spark, config, policy=policy, now=now) - if ( - config.get("champion_version") is not None - and str(config["champion_version"]) != champion - ): - raise ValueError("champion_version does not match the current champion.") - effective = training._candidate_config( - spec, - config["pipeline"], - engine=config["engine"], - cv=cv, - metric=config["metric"], - min_improvement=config["min_improvement"], - champion_version=champion, - quality_threshold=config.get("quality_threshold"), - quality_gates=config.get("quality_gates"), - risk_category=config.get("risk_category"), - ) - request.update( - spec=training._training_spec_payload(spec, config["engine"]), - champion_version=champion, - effective_config=effective, - ) + _prepare_training_request(spark, request, config, options, policy, now) # JSON normalization also detaches all caller-owned editable dictionaries. request = json.loads(json.dumps(request, allow_nan=False)) experiment = _get_or_create_experiment(store.client, experiment_name) @@ -138,31 +182,7 @@ def _prepare( store.log("lifecycle/request.json", request) store.client.set_tag(store.run_id, "skyulf.lifecycle.request", store.request_digest) store.begin("prepare") - output = { - "action": action, - "training_requested": action == "train", - "model_name": config["model_name"], - } - if action == "train": - pinned = request["spec"] - output.update( - source_table=pinned["table"], - source_version=pinned["version"], - engine=pinned["engine"], - split_strategy=pinned["split_strategy"], - expected_champion_version=request["champion_version"], - ) - output |= { - field: pinned[field] - for field in ("start", "holdout_start", "cutoff", "result_cutoff") - if pinned[field] is not None - } - else: - output |= { - field: options[field] - for field in ("candidate_version", "expected_champion_version") - if field in options - } + output = _prepared_output(request, config, action, options) return store.complete("prepare", output, None) except BaseException: with suppress(Exception): @@ -211,6 +231,20 @@ def _train(spark: Any, store: _PhaseStore) -> dict[str, Any]: } +def _validate_pinned_spec(fitted_spec: dict[str, Any], pinned_spec: dict[str, Any]) -> None: + """Allow only membership evidence to enrich the original source specification.""" + enriched = { + "holdout_key_sha256", + "sample_key_sha256", + "survivor_key_sha256", + "training_evidence_sha256", + } + if {key: value for key, value in fitted_spec.items() if key not in enriched} != { + key: value for key, value in pinned_spec.items() if key not in enriched + }: + raise ValueError("Saved training source differs from pinned invocation.") + + def _load_training_evidence(store: _PhaseStore) -> _ReplayEvidence: """Verify saved fit, invocation and filter evidence before any source replay.""" fitted = store.receipt("train")["output"] @@ -234,16 +268,7 @@ def _load_training_evidence(store: _PhaseStore) -> _ReplayEvidence: if store.read("candidate_training_spec.json") != fitted["spec"]: raise ValueError("Saved candidate training spec differs from phase receipt.") spec = _spec(fitted["spec"], source) - enriched = { - "holdout_key_sha256", - "sample_key_sha256", - "survivor_key_sha256", - "training_evidence_sha256", - } - if {key: value for key, value in fitted["spec"].items() if key not in enriched} != { - key: value for key, value in store.request["spec"].items() if key not in enriched - }: - raise ValueError("Saved training source differs from pinned invocation.") + _validate_pinned_spec(fitted["spec"], store.request["spec"]) evidence = store.read("training_filter_evidence.json") validate_training_evidence(evidence, spec, project_source_sha256=source_sha) return _ReplayEvidence(artifact, spec, fitted, evidence) @@ -584,6 +609,53 @@ def _execute_phase( raise +def _validate_phase_inputs( + phase: str, + task_states: dict[str, str] | None, + config: dict[str, Any] | None, + action: str | None, + experiment_name: str | None, + operator_options: dict[str, Any] | None, + now: datetime | None, +) -> None: + """Reject inputs that do not belong to the selected fixed phase.""" + if phase not in {"prepare", "complete", *_PREDECESSORS, *_GROUPED_PHASES}: + raise ValueError("Unsupported fixed lifecycle phase.") + if phase != "complete" and task_states is not None: + raise ValueError("Task states are accepted only by complete.") + if phase != "prepare" and any( + value is not None for value in (config, action, experiment_name, operator_options, now) + ): + raise ValueError("Downstream lifecycle phases must use only the pinned invocation.") + + +def _run_prepare_phase( + spark: Any, + store: _PhaseStore, + reference: dict[str, str] | None, + config: dict[str, Any] | None, + action: str | None, + experiment_name: str | None, + operator_options: dict[str, Any] | None, + now: datetime | None, + tracking_uri: str, +) -> LifecyclePhaseResult: + """Validate prepare inputs before persisting the pinned invocation.""" + if reference is not None or config is None or action is None or not experiment_name: + raise ValueError("Prepare requires config, action and experiment with no predecessor.") + if config.get("tracking_uri", "databricks") != tracking_uri: + raise ValueError("Tracking URI differs from invocation configuration.") + return _prepare( + spark, + store, + {**config, "tracking_uri": tracking_uri}, + action, + experiment_name, + operator_options or {}, + now, + ) + + def run_lifecycle_phase( spark: Any, *, @@ -609,14 +681,9 @@ def run_lifecycle_phase( lifecycle job's existing serialization and never runs scoring. """ context.validate() - if phase not in {"prepare", "complete", *_PREDECESSORS, *_GROUPED_PHASES}: - raise ValueError("Unsupported fixed lifecycle phase.") - if phase != "complete" and task_states is not None: - raise ValueError("Task states are accepted only by complete.") - if phase != "prepare" and any( - value is not None for value in (config, action, experiment_name, operator_options, now) - ): - raise ValueError("Downstream lifecycle phases must use only the pinned invocation.") + _validate_phase_inputs( + phase, task_states, config, action, experiment_name, operator_options, now + ) if phase in _GROUPED_PHASES: for internal_phase in _GROUPED_PHASES[phase]: completed = run_lifecycle_phase( @@ -630,18 +697,16 @@ def run_lifecycle_phase( return completed store = _PhaseStore(tracking_uri, context) if phase == "prepare": - if reference is not None or config is None or action is None or not experiment_name: - raise ValueError("Prepare requires config, action and experiment with no predecessor.") - if config.get("tracking_uri", "databricks") != tracking_uri: - raise ValueError("Tracking URI differs from invocation configuration.") - return _prepare( + return _run_prepare_phase( spark, store, - {**config, "tracking_uri": tracking_uri}, + reference, + config, action, experiment_name, - operator_options or {}, + operator_options, now, + tracking_uri, ) if reference is None: raise ValueError("Lifecycle phase requires its predecessor reference.") diff --git a/skyulf-core/skyulf/integrations/databricks/local_approval.py b/skyulf-core/skyulf/integrations/databricks/local_approval.py index f94512432..dacf9857b 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_approval.py +++ b/skyulf-core/skyulf/integrations/databricks/local_approval.py @@ -68,17 +68,7 @@ def resolve_candidate_comparison_digest( event = _read_event(raw) except (TypeError, ValueError) as exc: raise AliasConflictError("Saved comparison receipt is malformed.") from exc - kinds = {"initial", "promotion"} if replay else {"challenger"} - if action == "approve" and isinstance(event, dict) and event.get("k") == "rejection": - raise AliasConflictError("Candidate was explicitly rejected.") - if action == "reject": - kinds.add("rejection") - if not isinstance(event, dict) or event.get("s") != "committed" or event.get("k") not in kinds: - raise AliasConflictError("Candidate has no committed comparison for this action.") - digest = event.get("h") - if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest): - raise AliasConflictError("Saved comparison receipt has no valid digest.") - return digest + return _comparison_receipt_digest(event, action, replay) def _completed_approval( @@ -206,20 +196,7 @@ def approve_local_candidate( report, spec, engine, filter_evidence = _load_evidence( client, name, candidate_version, comparison_sha256, registry_uri=registry_uri ) - if report.champion_version != expected_champion_version: - raise ValueError("Expected champion differs from the saved comparison.") - validate_quality_policy( - config.get("metric", ""), config.get("quality_threshold"), config.get("quality_gates") - ) - if ( - any( - config.get(field) != getattr(report, field) - for field in ("metric", "min_improvement", "quality_threshold") - ) - or (config.get("quality_gates") or None) != report.quality_gates - or report.quality_threshold is None - ): - raise ValueError("Approval policy must match the saved, absolute-quality-gated comparison.") + _validate_approval_policy(config, report, expected_champion_version) candidate = resolve_model( name, version=candidate_version, tracking_uri=tracking_uri, registry_uri=registry_uri ) @@ -261,3 +238,43 @@ def approve_local_candidate( return promote_candidate( report, native, expected_champion_version=expected_champion_version, **options ) + + +def _comparison_receipt_digest(event: Any, action: str, replay: bool) -> str: + """Validate the committed receipt kind and return its concrete comparison digest.""" + kinds = {"initial", "promotion"} if replay else {"challenger"} + if action == "approve" and isinstance(event, dict) and event.get("k") == "rejection": + raise AliasConflictError("Candidate was explicitly rejected.") + if action == "reject": + kinds.add("rejection") + if not isinstance(event, dict) or event.get("s") != "committed" or event.get("k") not in kinds: + raise AliasConflictError("Candidate has no committed comparison for this action.") + return _receipt_evidence_digest(event) + + +def _receipt_evidence_digest(event: dict[str, Any]) -> str: + """Require a concrete comparison digest from a validated committed receipt.""" + digest = event.get("h") + if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest): + raise AliasConflictError("Saved comparison receipt has no valid digest.") + return digest + + +def _validate_approval_policy( + config: dict[str, Any], report: ModelComparisonReport, expected_champion_version: str | None +) -> None: + """Bind current approval settings to the saved champion and absolute quality policy.""" + if report.champion_version != expected_champion_version: + raise ValueError("Expected champion differs from the saved comparison.") + validate_quality_policy( + config.get("metric", ""), config.get("quality_threshold"), config.get("quality_gates") + ) + if ( + any( + config.get(field) != getattr(report, field) + for field in ("metric", "min_improvement", "quality_threshold") + ) + or (config.get("quality_gates") or None) != report.quality_gates + or report.quality_threshold is None + ): + raise ValueError("Approval policy must match the saved, absolute-quality-gated comparison.") diff --git a/skyulf-core/skyulf/integrations/databricks/local_batch.py b/skyulf-core/skyulf/integrations/databricks/local_batch.py index 49e891a2f..6c46d9c96 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_batch.py +++ b/skyulf-core/skyulf/integrations/databricks/local_batch.py @@ -48,23 +48,8 @@ def __post_init__(self) -> None: table_name(self.table) if type(self.version) is not int or self.version < 0: raise ValueError("version must be a nonnegative Delta snapshot version.") - for name in ("period_start", "period_end"): - value = getattr(self, name) - if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: - raise ValueError(f"{name} must be timezone-aware.") - if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( - tzinfo=None - ): - raise ValueError(f"{name} is not a valid local instant.") - if self.period_start.astimezone(UTC) >= self.period_end.astimezone(UTC): - raise ValueError("period_start must precede period_end.") - for name in (*self.record_key_columns, *self.input_columns, self.period_column): - column_name(name) - if not self.record_key_columns or not self.input_columns: - raise ValueError("record_key_columns and input_columns must be nonempty.") - names = [*self.record_key_columns, *self.input_columns, self.period_column] - if len({name.lower() for name in names}) != len(names): - raise ValueError("Row keys, input columns and period column must be distinct.") + _validate_source_period(self) + _validate_source_columns(self) if type(self.max_rows) is not int or self.max_rows <= 0: raise ValueError("max_rows must be positive.") if type(self.max_bytes) is not int or self.max_bytes <= 0: @@ -108,16 +93,7 @@ def fit_local_workflow( raise ValueError("max_rows must be positive.") if type(max_bytes) is not int or max_bytes <= 0: raise ValueError("max_bytes must be positive.") - frames = (data.train, data.test, data.validation) - if any( - frame is not None and not isinstance(frame, pd.DataFrame | pl.DataFrame) for frame in frames - ): - raise TypeError("Training splits must be pandas or Polars DataFrames.") - present = [frame for frame in frames if isinstance(frame, pd.DataFrame | pl.DataFrame)] - if sum(len(frame) for frame in present) > max_rows: - raise ValueError("Training input exceeds max_rows.") - if sum(_frame_bytes(frame) for frame in present) > max_bytes: - raise ValueError("Training input exceeds max_bytes.") + _validate_training_frames(data, max_rows, max_bytes) pipeline = SkyulfPipeline(config) pipeline.fit(data, target_column=target_column) save_local_pipeline(pipeline, artifact_path) @@ -162,20 +138,7 @@ def score_local_source( spark: Any, spec: LocalSourceSpec, prepared: PreparedLocalWorkflow ) -> LocalScoreResult: """Score one pinned period without refitting FE or writing a Delta table.""" - if not isinstance(prepared, PreparedLocalWorkflow): - raise TypeError("prepared must be a PreparedLocalWorkflow.") - source = prepared.config.source - if source.kind != "uc_table" or source.table != spec.table or source.version != spec.version: - raise ValueError("Prepared source must match the pinned Delta table and version.") - if spec.max_rows > source.max_rows or spec.max_bytes > source.max_bytes: - raise ValueError("Source budget exceeds the prepared workflow budget.") - expected = ( - prepared.artifact.manifest.input_columns - if isinstance(prepared.artifact, LocalPipelineArtifact) - else tuple(column.name for column in prepared.artifact.manifest.input_schema) - ) - if spec.input_columns != expected: - raise ValueError("Source inputs must match the saved model's raw column order.") + _validate_scoring_source(spec, prepared) frame = read_local_source(spark, spec) predictions = ( pd.DataFrame(columns=pd.Index(prepared.preflight.output_columns)) @@ -204,3 +167,60 @@ def score_local_source( "row_count": len(result), } return LocalScoreResult(result, diagnostics) + + +def _validate_source_period(spec: LocalSourceSpec) -> None: + """Validate period instants and ordering before column and budget checks.""" + for name in ("period_start", "period_end"): + value = getattr(spec, name) + if type(value) is not datetime or value.tzinfo is None or value.utcoffset() is None: + raise ValueError(f"{name} must be timezone-aware.") + if value.astimezone(UTC).astimezone(value.tzinfo).replace(tzinfo=None) != value.replace( + tzinfo=None + ): + raise ValueError(f"{name} is not a valid local instant.") + if spec.period_start.astimezone(UTC) >= spec.period_end.astimezone(UTC): + raise ValueError("period_start must precede period_end.") + + +def _validate_training_frames(data: SplitDataset, max_rows: int, max_bytes: int) -> None: + """Check supported split frames and aggregate read budgets before fitting.""" + frames = (data.train, data.test, data.validation) + if any( + frame is not None and not isinstance(frame, pd.DataFrame | pl.DataFrame) for frame in frames + ): + raise TypeError("Training splits must be pandas or Polars DataFrames.") + present = [frame for frame in frames if isinstance(frame, pd.DataFrame | pl.DataFrame)] + if sum(len(frame) for frame in present) > max_rows: + raise ValueError("Training input exceeds max_rows.") + if sum(_frame_bytes(frame) for frame in present) > max_bytes: + raise ValueError("Training input exceeds max_bytes.") + + +def _validate_scoring_source(spec: LocalSourceSpec, prepared: PreparedLocalWorkflow) -> None: + """Bind scoring to the prepared source, budgets and raw input column order.""" + if not isinstance(prepared, PreparedLocalWorkflow): + raise TypeError("prepared must be a PreparedLocalWorkflow.") + source = prepared.config.source + if source.kind != "uc_table" or source.table != spec.table or source.version != spec.version: + raise ValueError("Prepared source must match the pinned Delta table and version.") + if spec.max_rows > source.max_rows or spec.max_bytes > source.max_bytes: + raise ValueError("Source budget exceeds the prepared workflow budget.") + expected = ( + prepared.artifact.manifest.input_columns + if isinstance(prepared.artifact, LocalPipelineArtifact) + else tuple(column.name for column in prepared.artifact.manifest.input_schema) + ) + if spec.input_columns != expected: + raise ValueError("Source inputs must match the saved model's raw column order.") + + +def _validate_source_columns(spec: LocalSourceSpec) -> None: + """Require valid, nonempty and distinct row keys, inputs and period column.""" + for name in (*spec.record_key_columns, *spec.input_columns, spec.period_column): + column_name(name) + if not spec.record_key_columns or not spec.input_columns: + raise ValueError("record_key_columns and input_columns must be nonempty.") + names = [*spec.record_key_columns, *spec.input_columns, spec.period_column] + if len({name.lower() for name in names}) != len(names): + raise ValueError("Row keys, input columns and period column must be distinct.") diff --git a/skyulf-core/skyulf/integrations/databricks/local_cv.py b/skyulf-core/skyulf/integrations/databricks/local_cv.py index 552894496..8153eaff6 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_cv.py +++ b/skyulf-core/skyulf/integrations/databricks/local_cv.py @@ -51,20 +51,7 @@ def __post_init__(self) -> None: raise ValueError("cv_inner_folds must be an integer from 2 to 20, or null.") if type(self.random_state) is not int or not 0 <= self.random_state < 2**32: raise ValueError("cv_random_state must be an integer from 0 to 2**32 - 1.") - if self.method not in ( - "k_fold", - "stratified_k_fold", - "time_series_split", - "shuffle_split", - "nested_cv", - ): - raise ValueError( - "cv_type must be k_fold, stratified_k_fold, time_series_split, shuffle_split or nested_cv." - ) - if self.method == "time_series_split" and self.shuffle: - raise ValueError("Time-series CV requires cv_shuffle=false.") - if self.method == "shuffle_split" and not self.shuffle: - raise ValueError("Shuffle-split CV requires cv_shuffle=true.") + _validate_cv_method(self) @classmethod def from_workflow(cls, config: dict[str, Any]) -> "LocalCVSpec": @@ -80,24 +67,7 @@ def validate_pipeline( ) if not self.enabled: return - if ( - self.method == "nested_cv" - and self.inner_folds is not None - and config.get("modeling", {}).get("type") != "hyperparameter_tuner" - ): - raise ValueError("Explicit cv_inner_folds requires a nested tuning pipeline.") - calculator = NodeRegistry.get_calculator(base_model_config(config)["type"])() - if not isinstance(calculator, BaseModelCalculator) or calculator.problem_type not in ( - "classification", - "regression", - ): - raise ValueError("Bundle CV requires a registered classification or regression model.") - if self.method == "stratified_k_fold" and calculator.problem_type != "classification": - raise ValueError("Stratified CV requires a classification model.") - if self.method == "time_series_split" and not event_column: - raise ValueError( - "Time-series CV requires window selection with an explicit event_column." - ) + _validate_cv_model(self, config, event_column) steps = config.get("preprocessing", []) if any(step.get("transformer") in SPLITTER_STEP_TYPES for step in steps): raise ValueError("Bundle CV owns the split; remove preprocessing splitter nodes.") @@ -122,17 +92,7 @@ def _validate_fold_membership( raise ValueError( "Stratified CV requires at least cv_folds rows per class and two classes." ) - times = None - if spec.method == "time_series_split": - if event_column is None or event_column not in frame.columns: - raise ValueError("Time-series CV requires its event_column in the training payload.") - values = frame[event_column] - times = values.to_pandas() if isinstance(values, pl.Series) else values - if not isinstance(times.dtype, pd.DatetimeTZDtype) or times.isna().any(): - raise ValueError( - "CV event_column must contain normalized nonnull timezone-aware timestamps." - ) - times = times.sort_values(kind="stable").reset_index(drop=True) + times = _cv_event_times(frame, spec, event_column) splitter = _build_splitter( cv_type=spec.method, n_folds=spec.folds, @@ -210,3 +170,59 @@ def evaluate_training_cv( result["cv_config"]["time_column"] = event_column result["fold_refit"] = adapter.summary(train_rows=len(frame)) return result + + +def _validate_cv_method(spec: LocalCVSpec) -> None: + """Validate supported split methods and their shuffle requirements.""" + if spec.method not in ( + "k_fold", + "stratified_k_fold", + "time_series_split", + "shuffle_split", + "nested_cv", + ): + raise ValueError( + "cv_type must be k_fold, stratified_k_fold, time_series_split, shuffle_split or nested_cv." + ) + if spec.method == "time_series_split" and spec.shuffle: + raise ValueError("Time-series CV requires cv_shuffle=false.") + if spec.method == "shuffle_split" and not spec.shuffle: + raise ValueError("Shuffle-split CV requires cv_shuffle=true.") + + +def _validate_cv_model(spec: LocalCVSpec, config: dict[str, Any], event_column: str | None) -> None: + """Require a compatible supervised model and temporal metadata for the selected CV.""" + if ( + spec.method == "nested_cv" + and spec.inner_folds is not None + and config.get("modeling", {}).get("type") != "hyperparameter_tuner" + ): + raise ValueError("Explicit cv_inner_folds requires a nested tuning pipeline.") + calculator = NodeRegistry.get_calculator(base_model_config(config)["type"])() + if not isinstance(calculator, BaseModelCalculator) or calculator.problem_type not in ( + "classification", + "regression", + ): + raise ValueError("Bundle CV requires a registered classification or regression model.") + if spec.method == "stratified_k_fold" and calculator.problem_type != "classification": + raise ValueError("Stratified CV requires a classification model.") + if spec.method == "time_series_split" and not event_column: + raise ValueError("Time-series CV requires window selection with an explicit event_column.") + + +def _cv_event_times( + frame: pd.DataFrame | pl.DataFrame, spec: LocalCVSpec, event_column: str | None +) -> pd.Series | None: + """Normalize event ordering for fold boundary checks without altering the frame.""" + times = None + if spec.method == "time_series_split": + if event_column is None or event_column not in frame.columns: + raise ValueError("Time-series CV requires its event_column in the training payload.") + values = frame[event_column] + times = values.to_pandas() if isinstance(values, pl.Series) else values + if not isinstance(times.dtype, pd.DatetimeTZDtype) or times.isna().any(): + raise ValueError( + "CV event_column must contain normalized nonnull timezone-aware timestamps." + ) + times = times.sort_values(kind="stable").reset_index(drop=True) + return times diff --git a/skyulf-core/skyulf/integrations/databricks/local_ensemble.py b/skyulf-core/skyulf/integrations/databricks/local_ensemble.py index 13de0d7b5..48d0a3c97 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_ensemble.py +++ b/skyulf-core/skyulf/integrations/databricks/local_ensemble.py @@ -84,6 +84,12 @@ def _voting(params: dict[str, Any], members: list[str], calculator: Any) -> None if set(weights) - set(members): raise ValueError("weights must name only selected base_estimators.") weights = [weights.get(name, 1) for name in members] + _validate_weights(weights, members) + params["weights"] = weights + + +def _validate_weights(weights: Any, members: list[str]) -> None: + """Require one finite nonnegative weight per selected learner and a positive total.""" if ( not isinstance(weights, list) or len(weights) != len(members) @@ -96,7 +102,6 @@ def _voting(params: dict[str, Any], members: list[str], calculator: Any) -> None raise ValueError( "weights need one finite nonnegative value per model and a positive total." ) - params["weights"] = weights def _stacking(params: dict[str, Any], calculator: Any) -> None: @@ -172,6 +177,13 @@ def merge_ensemble_fixed_space( f"final_estimator__{key}": value for key, value in params.get("final_estimator_params", {}).items() } + _merge_member_axes(space, params, fixed, automatic) + + +def _merge_member_axes( + space: dict[str, list[Any]], params: dict[str, Any], fixed: dict[str, Any], automatic: bool +) -> None: + """Check fixed nested overrides before adding scalar search axes.""" for name, value in fixed.items(): if name in params and params[name] != value: raise ValueError(f"Fixed base parameter conflicts with nested parameter: {name}.") diff --git a/skyulf-core/skyulf/integrations/databricks/local_incremental.py b/skyulf-core/skyulf/integrations/databricks/local_incremental.py index e801f15fa..4e5aa494c 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_incremental.py +++ b/skyulf-core/skyulf/integrations/databricks/local_incremental.py @@ -18,7 +18,7 @@ from .delta import DeltaPublishError, history, table_identity from .local_batch import _frame_bytes from .local_publish import _check_target, _scalar -from .local_sdk import PreparedLocalWorkflow +from .local_sdk import LocalWorkflowConfig, PreparedLocalWorkflow @dataclass(frozen=True, slots=True) @@ -75,39 +75,10 @@ def _validate_prepared( if not isinstance(prepared, PreparedLocalWorkflow): raise TypeError("prepared must be a PreparedLocalWorkflow.") config = prepared.config - if ( - config.runtime != "databricks" - or config.source.kind != "uc_table" - or config.source.read_mode != "incremental" - or config.source.version is not None - or config.sink.kind != "uc_delta" - or not config.source.table - or not config.sink.table - or config.source.table == config.sink.table - ): - raise ValueError("Incremental scoring requires unpinned UC source and UC Delta sink.") - if ( - config.model.kind != "local_pipeline" - or not config.model.name - or not config.model.version - or not prepared.preflight.ready - or not isinstance(prepared.artifact, LocalPipelineArtifact) - or prepared.preflight.model_version != config.model.version - or prepared.preflight.model_digest != prepared.artifact.manifest.pipeline_sha256 - ): - raise ValueError("Incremental scoring requires a pinned, ready local pipeline model.") - if type(record_key_columns) is not tuple or not record_key_columns: - raise ValueError("record_key_columns must be a nonempty tuple.") - for name in record_key_columns: - column_name(name) - if period_column is not None: - column_name(period_column) - names = (*record_key_columns, *((period_column,) if period_column is not None else ())) - if len({name.lower() for name in names}) != len(names): - raise ValueError("record_key_columns and period_column must be distinct.") - if any(name.lower() in PREDICTION_METADATA_COLUMNS for name in names): - raise ValueError("record_key_columns and period_column collide with prediction metadata.") - inputs = prepared.artifact.manifest.input_columns + _validate_incremental_source(config) + artifact = _validate_incremental_model(prepared, config) + _validate_incremental_keys(record_key_columns, period_column) + inputs = artifact.manifest.input_columns if any(key in inputs for key in record_key_columns) or ( period_column is not None and period_column in inputs ): @@ -168,18 +139,10 @@ def run_incremental_local_batch( config = prepared.config source_table = config.source.table target_table = config.sink.table - assert source_table is not None and target_table is not None - source_id = table_identity(spark, source_table) - target_id = table_identity(spark, target_table) - if source_id == target_id: - raise ValueError("Source and prediction target must be different Delta tables.") - detail = spark.sql(f"DESCRIBE DETAIL {table_name(source_table)}").first() - properties = detail["properties"] or {} - if not any( - key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" - for key, value in properties.items() - ): - raise ValueError("Source Delta Change Data Feed must be enabled before scoring.") + source_table, target_table, source_id, target_id = _incremental_table_ids( + spark, source_table, target_table + ) + _require_incremental_change_feed(spark, source_table) functions = importlib.import_module("pyspark.sql.functions") with admission.hold(target_id): @@ -190,22 +153,7 @@ def run_incremental_local_batch( raise BatchConflictError("Source or target table identity changed during admission.") target_latest = _latest(spark, target_table) previous = _last_receipt(target_latest, source_id, target_id) - if previous is None: - older_receipt = ( - history(spark, target_table) - .where( - functions.get_json_object("userMetadata", "$.skyulf_mode") - == "incremental_append" - ) - .limit(1) - .count() - ) - if older_receipt: - raise BatchConflictError("Target changed outside the incremental receipt protocol.") - if spark.table(target_table).limit(1).count(): - raise BatchConflictError( - "Incremental bootstrap requires an empty target with no prior predictions." - ) + _check_incremental_bootstrap(spark, target_table, previous, functions) prior_version = int(previous["source_end_version"]) if previous else None upper_version = int(_latest(spark, source_table)["version"]) if prior_version is not None and upper_version < prior_version: @@ -222,26 +170,9 @@ def run_incremental_local_batch( config.model.name, config.model.version, ) - if prior_version is None: - selected = ( - spark.read.format("delta").option("versionAsOf", upper_version).table(source_table) - ) - else: - selected = ( - spark.read.format("delta") - .option("readChangeFeed", "true") - .option("startingVersion", prior_version + 1) - .option("endingVersion", upper_version) - .table(source_table) - ) - if selected.where(functions.col("_change_type") != "insert").limit(1).count(): - raise ValueError("Source updates and deletes require an explicit rescore policy.") - selected = selected.where(functions.col("_change_type") == "insert") - if period_column is not None: - if selected.schema[period_column].dataType.typeName() != "timestamp": - raise ValueError("Source event time must be a Spark timestamp.") - if selected.where(functions.col(period_column).isNull()).limit(1).count(): - raise ValueError("Source event time must not be null.") + selected = _select_incremental_rows( + spark, source_table, prior_version, upper_version, period_column, functions + ) frame = _bounded_frame( selected, (*record_key_columns, *inputs), @@ -265,35 +196,9 @@ def run_incremental_local_batch( output_names = _check_target( spark, selected, target, record_key_columns, period_column, prepared ) - predicted = prepared.predict(frame.loc[:, list(inputs)]) - if list(predicted.columns) != list(output_names) or len(predicted) != len(frame): - raise ValueError( - "Local prediction schema or row count differs from the model contract." - ) - bridge_frame = pd.concat( - [ - frame.loc[:, list(record_key_columns)].reset_index(drop=True), - predicted.reset_index(drop=True), - ], - axis=1, + bridge = _incremental_prediction_bridge( + spark, prepared, frame, inputs, output_names, record_key_columns, target ) - if _frame_bytes(bridge_frame) > config.source.max_bytes: - raise ValueError("Prediction result exceeds max_bytes.") - bridge_columns = (*record_key_columns, *output_names) - bridge = spark.createDataFrame( - [ - tuple(_scalar(value) for value in row) - for row in bridge_frame.itertuples(index=False, name=None) - ], - schema=target.select(*bridge_columns).schema, - ) - if ( - bridge.select(*record_key_columns) - .join(target.select(*record_key_columns), on=list(record_key_columns), how="left_semi") - .limit(1) - .count() - ): - raise BatchConflictError("Source key already has a published prediction.") output = ( bridge.join( selected.select(*record_key_columns, period_column), @@ -303,58 +208,22 @@ def run_incremental_local_batch( if period_column is not None else bridge ) - run_input = { - "skyulf_mode": "incremental_append", - "source_table_id": source_id, - "target_table_id": target_id, - "source_start_version": prior_version + 1 if prior_version is not None else None, - "source_end_version": upper_version, - "model_name": config.model.name, - "model_version": config.model.version, - "model_digest": prepared.preflight.model_digest, - "code_version": version("skyulf-core"), - "input_count": len(frame), - "output_count": len(frame), - } - digest = hashlib.sha256( - json.dumps(run_input, sort_keys=True, separators=(",", ":")).encode() - ).hexdigest() - manifest = {**run_input, "run_id": digest, "request_digest": digest} - for name, value in ( - ("run_id", digest), - ("model_name", config.model.name), - ("model_version", config.model.version), - ): - output = output.withColumn(name, functions.lit(value)) - if {field.name: field.dataType for field in output.schema} != { - field.name: field.dataType for field in target.schema - }: - raise ValueError("Prediction output schema must match the Delta target exactly.") - output = output.select(*target.columns) - if output.count() != len(frame): - raise ValueError("Prediction keys do not match source rows.") - if table_identity(spark, source_table) != source_id: - raise BatchConflictError("Source table identity changed while scoring.") - if int(_latest(spark, target_table)["version"]) != int(target_latest["version"]): - raise BatchConflictError("Target changed while scoring; retry from the latest receipt.") - try: - ( - output.write.format("delta") - .mode("append") - .option("mergeSchema", "false") - .option("txnAppId", f"skyulf-incremental:{source_id}:{target_id}") - .option("txnVersion", upper_version) - .option("userMetadata", json.dumps(manifest, sort_keys=True)) - .saveAsTable(target_table) - ) - except Exception as exc: # noqa: BLE001 - preserve Delta's structured cause - if "Concurrent" in type(exc).__name__ or "DELTA_CONCURRENT" in str(exc): - raise BatchConflictError("Delta rejected a concurrent incremental write.") from exc - raise DeltaPublishError("Incremental Delta write failed.") from exc - committed = _latest(spark, target_table) - recorded = _last_receipt(committed, source_id, target_id) - if recorded is None or recorded.get("request_digest") != digest: - raise DeltaPublishError("Delta returned without a verifiable incremental receipt.") + run_input, digest, manifest = _incremental_manifest( + prepared, source_id, target_id, prior_version, upper_version, frame + ) + output = _complete_incremental_output(output, target, config, digest, functions, frame) + committed, recorded = _commit_increment( + spark, + source_table, + source_id, + target_table, + target_id, + target_latest, + output, + upper_version, + manifest, + digest, + ) return IncrementalBatchResult( run_input["source_start_version"], upper_version, @@ -366,3 +235,261 @@ def run_incremental_local_batch( config.model.name, config.model.version, ) + + +def _validate_incremental_source(config: LocalWorkflowConfig) -> None: + """Require an unpinned incremental UC source and a separate UC Delta sink.""" + if ( + config.runtime != "databricks" + or config.source.kind != "uc_table" + or config.source.read_mode != "incremental" + or config.source.version is not None + or config.sink.kind != "uc_delta" + or not config.source.table + or not config.sink.table + or config.source.table == config.sink.table + ): + raise ValueError("Incremental scoring requires unpinned UC source and UC Delta sink.") + + +def _validate_incremental_model( + prepared: PreparedLocalWorkflow, config: LocalWorkflowConfig +) -> LocalPipelineArtifact: + """Require pinned ready model evidence matching the loaded local artifact.""" + if ( + config.model.kind != "local_pipeline" + or not config.model.name + or not config.model.version + or not prepared.preflight.ready + or not isinstance(prepared.artifact, LocalPipelineArtifact) + or prepared.preflight.model_version != config.model.version + or prepared.preflight.model_digest != prepared.artifact.manifest.pipeline_sha256 + ): + raise ValueError("Incremental scoring requires a pinned, ready local pipeline model.") + return prepared.artifact + + +def _validate_incremental_keys( + record_key_columns: tuple[str, ...], period_column: str | None +) -> None: + """Validate distinct control columns before checking the model input schema.""" + if type(record_key_columns) is not tuple or not record_key_columns: + raise ValueError("record_key_columns must be a nonempty tuple.") + for name in record_key_columns: + column_name(name) + if period_column is not None: + column_name(period_column) + names = (*record_key_columns, *((period_column,) if period_column is not None else ())) + if len({name.lower() for name in names}) != len(names): + raise ValueError("record_key_columns and period_column must be distinct.") + if any(name.lower() in PREDICTION_METADATA_COLUMNS for name in names): + raise ValueError("record_key_columns and period_column collide with prediction metadata.") + + +def _require_incremental_change_feed(spark: Any, source_table: str) -> None: + """Require source change data feed before entering publication admission.""" + detail = spark.sql(f"DESCRIBE DETAIL {table_name(source_table)}").first() + properties = detail["properties"] or {} + if not any( + key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" + for key, value in properties.items() + ): + raise ValueError("Source Delta Change Data Feed must be enabled before scoring.") + + +def _check_incremental_bootstrap( + spark: Any, target_table: str, previous: dict[str, Any] | None, functions: Any +) -> None: + """Reject an unreceipted nonempty or previously managed target.""" + if previous is None: + older_receipt = ( + history(spark, target_table) + .where( + functions.get_json_object("userMetadata", "$.skyulf_mode") == "incremental_append" + ) + .limit(1) + .count() + ) + if older_receipt: + raise BatchConflictError("Target changed outside the incremental receipt protocol.") + if spark.table(target_table).limit(1).count(): + raise BatchConflictError( + "Incremental bootstrap requires an empty target with no prior predictions." + ) + + +def _select_incremental_rows( + spark: Any, + source_table: str, + prior_version: int | None, + upper_version: int, + period_column: str | None, + functions: Any, +) -> Any: + """Read one snapshot or insert-only change window and validate event time.""" + if prior_version is None: + selected = ( + spark.read.format("delta").option("versionAsOf", upper_version).table(source_table) + ) + else: + selected = ( + spark.read.format("delta") + .option("readChangeFeed", "true") + .option("startingVersion", prior_version + 1) + .option("endingVersion", upper_version) + .table(source_table) + ) + if selected.where(functions.col("_change_type") != "insert").limit(1).count(): + raise ValueError("Source updates and deletes require an explicit rescore policy.") + selected = selected.where(functions.col("_change_type") == "insert") + if period_column is not None: + if selected.schema[period_column].dataType.typeName() != "timestamp": + raise ValueError("Source event time must be a Spark timestamp.") + if selected.where(functions.col(period_column).isNull()).limit(1).count(): + raise ValueError("Source event time must not be null.") + return selected + + +def _incremental_prediction_bridge( + spark: Any, + prepared: PreparedLocalWorkflow, + frame: pd.DataFrame, + inputs: tuple[str, ...], + output_names: tuple[str, ...], + record_key_columns: tuple[str, ...], + target: Any, +) -> Any: + """Score bounded rows, preserve keys and reject already published predictions.""" + predicted = prepared.predict(frame.loc[:, list(inputs)]) + if list(predicted.columns) != list(output_names) or len(predicted) != len(frame): + raise ValueError("Local prediction schema or row count differs from the model contract.") + bridge_frame = pd.concat( + [ + frame.loc[:, list(record_key_columns)].reset_index(drop=True), + predicted.reset_index(drop=True), + ], + axis=1, + ) + if _frame_bytes(bridge_frame) > prepared.config.source.max_bytes: + raise ValueError("Prediction result exceeds max_bytes.") + bridge_columns = (*record_key_columns, *output_names) + bridge = spark.createDataFrame( + [ + tuple(_scalar(value) for value in row) + for row in bridge_frame.itertuples(index=False, name=None) + ], + schema=target.select(*bridge_columns).schema, + ) + if ( + bridge.select(*record_key_columns) + .join(target.select(*record_key_columns), on=list(record_key_columns), how="left_semi") + .limit(1) + .count() + ): + raise BatchConflictError("Source key already has a published prediction.") + return bridge + + +def _incremental_manifest( + prepared: PreparedLocalWorkflow, + source_id: str, + target_id: str, + prior_version: int | None, + upper_version: int, + frame: pd.DataFrame, +) -> tuple[dict[str, Any], str, dict[str, Any]]: + """Fingerprint the exact increment, concrete model and prediction row count.""" + config = prepared.config + run_input = { + "skyulf_mode": "incremental_append", + "source_table_id": source_id, + "target_table_id": target_id, + "source_start_version": prior_version + 1 if prior_version is not None else None, + "source_end_version": upper_version, + "model_name": config.model.name, + "model_version": config.model.version, + "model_digest": prepared.preflight.model_digest, + "code_version": version("skyulf-core"), + "input_count": len(frame), + "output_count": len(frame), + } + digest = hashlib.sha256( + json.dumps(run_input, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + manifest = {**run_input, "run_id": digest, "request_digest": digest} + return run_input, digest, manifest + + +def _complete_incremental_output( + output: Any, + target: Any, + config: LocalWorkflowConfig, + digest: str, + functions: Any, + frame: pd.DataFrame, +) -> Any: + """Attach model identity and validate final prediction schema and row membership.""" + for name, value in ( + ("run_id", digest), + ("model_name", config.model.name), + ("model_version", config.model.version), + ): + output = output.withColumn(name, functions.lit(value)) + if {field.name: field.dataType for field in output.schema} != { + field.name: field.dataType for field in target.schema + }: + raise ValueError("Prediction output schema must match the Delta target exactly.") + output = output.select(*target.columns) + if output.count() != len(frame): + raise ValueError("Prediction keys do not match source rows.") + return output + + +def _commit_increment( + spark: Any, + source_table: str, + source_id: str, + target_table: str, + target_id: str, + target_latest: Any, + output: Any, + upper_version: int, + manifest: dict[str, Any], + digest: str, +) -> tuple[Any, dict[str, Any]]: + """Recheck source and target, append once and verify the persisted receipt.""" + if table_identity(spark, source_table) != source_id: + raise BatchConflictError("Source table identity changed while scoring.") + if int(_latest(spark, target_table)["version"]) != int(target_latest["version"]): + raise BatchConflictError("Target changed while scoring; retry from the latest receipt.") + try: + ( + output.write.format("delta") + .mode("append") + .option("mergeSchema", "false") + .option("txnAppId", f"skyulf-incremental:{source_id}:{target_id}") + .option("txnVersion", upper_version) + .option("userMetadata", json.dumps(manifest, sort_keys=True)) + .saveAsTable(target_table) + ) + except Exception as exc: # noqa: BLE001 - preserve Delta's structured cause + if "Concurrent" in type(exc).__name__ or "DELTA_CONCURRENT" in str(exc): + raise BatchConflictError("Delta rejected a concurrent incremental write.") from exc + raise DeltaPublishError("Incremental Delta write failed.") from exc + committed = _latest(spark, target_table) + recorded = _last_receipt(committed, source_id, target_id) + if recorded is None or recorded.get("request_digest") != digest: + raise DeltaPublishError("Delta returned without a verifiable incremental receipt.") + return committed, recorded + + +def _incremental_table_ids( + spark: Any, source_table: str | None, target_table: str | None +) -> tuple[str, str, str, str]: + """Resolve immutable table identities and reject source-target aliasing.""" + assert source_table is not None and target_table is not None + source_id = table_identity(spark, source_table) + target_id = table_identity(spark, target_table) + if source_id == target_id: + raise ValueError("Source and prediction target must be different Delta tables.") + return source_table, target_table, source_id, target_id diff --git a/skyulf-core/skyulf/integrations/databricks/local_pre_split.py b/skyulf-core/skyulf/integrations/databricks/local_pre_split.py index b3f61c93c..ae4d3dd93 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_pre_split.py +++ b/skyulf-core/skyulf/integrations/databricks/local_pre_split.py @@ -5,13 +5,23 @@ from collections.abc import Callable from copy import deepcopy from decimal import Decimal, InvalidOperation -from typing import Any +from typing import Any, TypeGuard from ...inference.project_code import is_registered_project_step from ...preprocessing.casting import TYPE_ALIASES from ._contracts import column_name +def _distinct_column_names(columns: Any) -> TypeGuard[list[str]]: + """Check an explicit list of case-insensitively distinct string column names.""" + return ( + type(columns) is list + and bool(columns) + and all(type(name) is str for name in columns) + and len({name.casefold() for name in columns}) == len(columns) + ) + + def deduplicate_columns(step: dict[str, Any]) -> tuple[str, ...]: """Require an explicit, lossless survivor policy for Core Deduplicate.""" params = step["params"] @@ -19,10 +29,7 @@ def deduplicate_columns(step: dict[str, Any]) -> tuple[str, ...]: keep = params.get("keep", "first") if ( set(params) - {"subset", "keep"} - or type(subset) is not list - or not subset - or any(type(name) is not str for name in subset) - or len({name.casefold() for name in subset}) != len(subset) + or not _distinct_column_names(subset) or (keep is not False and keep not in ("first", "last", "none")) ): raise ValueError( @@ -45,10 +52,7 @@ def custom_filter_columns(step: dict[str, Any]) -> tuple[str, ...]: or set(declaration) != {"effect", "required_columns", "learns_from_data"} or declaration["effect"] != "filter" or declaration["learns_from_data"] is not False - or type(columns) is not list - or not columns - or any(type(name) is not str for name in columns) - or len({name.casefold() for name in columns}) != len(columns) + or not _distinct_column_names(columns) or not _json_value(step["params"]) ): raise ValueError( @@ -102,23 +106,10 @@ def _casting_columns(params: dict[str, Any]) -> tuple[str, ...]: type_map = params.get("column_types", {}) if not isinstance(type_map, dict) or any(not isinstance(k, str) for k in type_map): raise ValueError("pre_split_steps Casting requires named column_types.") - if columns is None: - columns = [] - if not isinstance(columns, list) or any(not isinstance(c, str) or not c for c in columns): - raise ValueError("pre_split_steps Casting requires explicit columns.") - if columns and "target_type" not in params: - raise ValueError("pre_split_steps Casting columns require target_type.") - if "target_type" in params and not columns: - raise ValueError("pre_split_steps Casting target_type requires columns.") + columns = _casting_selection(params, columns) selected = dict(type_map) selected.update(dict.fromkeys(columns, params.get("target_type"))) - if not selected or any( - not isinstance(dtype, str) - or TYPE_ALIASES.get(dtype.lower(), dtype) not in set(TYPE_ALIASES.values()) - or TYPE_ALIASES.get(dtype.lower(), dtype) == "category" - for dtype in selected.values() - ): - raise ValueError("pre_split_steps Casting needs fixed noncategorical dtypes.") + _validate_cast_dtypes(selected) if type(params.get("coerce_on_error", True)) is not bool: raise ValueError("pre_split_steps Casting coerce_on_error must be boolean.") return tuple(dict.fromkeys(selected)) @@ -128,48 +119,18 @@ def _validate_replacement_mapping(params: dict[str, Any], columns: tuple[str, .. """Keep flat or per-column mappings lossless through saved JSON.""" mapping = params.get("mapping") if mapping is not None: - maps = mapping.values() if isinstance(mapping, dict) else () - if ( - not isinstance(mapping, dict) - or not mapping - or any(not isinstance(key, str) for key in mapping) - or any(not isinstance(item, dict) and not _json_value(item) for item in maps) - ): - raise ValueError( - "pre_split_steps mapping needs string keys; use replacements pairs for numeric keys." - ) + maps = _replacement_maps(mapping) if "value" in params or "to_replace" in params or "replacements" in params: raise ValueError( "pre_split_steps mapping cannot be combined with another replacement mode." ) - nested = [isinstance(item, dict) for item in maps] - if any(nested) and (not all(nested) or any(column not in columns for column in mapping)): - raise ValueError("pre_split_steps nested mapping must name only selected columns.") - for item in maps: - if isinstance(item, dict) and ( - any(not isinstance(key, str) for key in item) or not _json_value(item) - ): - raise ValueError( - "pre_split_steps mapping needs string keys; use replacements pairs for numeric keys." - ) - for item in [mapping] if not any(nested) else maps: - identities = [_pair_key(key) for key in item] - if len(set(identities)) != len(identities): - raise ValueError("pre_split_steps mapping keys collide after numeric coercion.") + _validate_mapping_columns(mapping, maps, columns) def _validate_replacement_pairs(params: dict[str, Any]) -> None: """Reject malformed or colliding numeric replacement pairs.""" pairs = params.get("replacements") - if pairs is not None and ( - not isinstance(pairs, list) - or not pairs - or any( - not isinstance(pair, dict) or set(pair) != {"old", "new"} or not _json_value(pair) - for pair in pairs - ) - ): - raise ValueError("pre_split_steps replacements requires lossless old/new pairs.") + _validate_pair_payload(pairs) if pairs is not None and ("value" in params or "to_replace" in params or "mapping" in params): raise ValueError("pre_split_steps replacements cannot be combined with another mode.") if pairs is not None: @@ -294,16 +255,7 @@ def _invalid_value_columns(params: dict[str, Any]) -> tuple[str, ...]: type(params.get(flag, False)) is not bool for flag in ("replace_inf", "replace_neg_inf") ): raise ValueError("pre_split_steps InvalidValueReplacement flags must be boolean.") - if rule == "custom_range" and all( - params.get(bound) is None for bound in ("min_value", "max_value") - ): - raise ValueError("pre_split_steps custom_range needs a bound.") - if rule != "custom_range" and any( - params.get(bound) is not None for bound in ("min_value", "max_value") - ): - raise ValueError("pre_split_steps range bounds require custom_range.") - if "replacement" in params and "value" in params: - raise ValueError("pre_split_steps choose replacement or value, not both.") + _validate_invalid_value_range(params, rule) _validate_range_bounds(params) return columns @@ -370,29 +322,8 @@ def projected_fixed_steps( continue clone = deepcopy(step) params = clone["params"] - if clone["transformer"] == "Casting": - params["column_types"] = { - column: dtype - for column, dtype in params.get("column_types", {}).items() - if column in selected - } - if "columns" in params: - params["columns"] = [column for column in params["columns"] if column in selected] - if not params.get("columns"): - params.pop("columns", None) - params.pop("target_type", None) - else: - params["columns"] = keep - if clone["transformer"] == "ValueReplacement" and isinstance( - params.get("mapping"), dict - ): - mapping = params["mapping"] - if any(isinstance(value, dict) for value in mapping.values()): - params["mapping"] = { - column: value for column, value in mapping.items() if column in selected - } - if not any(params["mapping"].values()): - continue + if not _project_fixed_params(clone, params, keep, selected): + continue projected.append(clone) return projected @@ -401,3 +332,125 @@ def target_contract(steps: tuple[dict[str, Any], ...], target_column: str) -> li """Describe ordered target edits without step labels or feature-only parameters.""" projected = projected_fixed_steps(steps, (target_column,)) return [{"transformer": step["transformer"], "params": step["params"]} for step in projected] + + +def _casting_selection(params: dict[str, Any], columns: Any) -> list[str]: + """Require explicit cast columns paired with their requested target type.""" + if columns is None: + columns = [] + if not isinstance(columns, list) or any(not isinstance(c, str) or not c for c in columns): + raise ValueError("pre_split_steps Casting requires explicit columns.") + if columns and "target_type" not in params: + raise ValueError("pre_split_steps Casting columns require target_type.") + if "target_type" in params and not columns: + raise ValueError("pre_split_steps Casting target_type requires columns.") + return columns + + +def _validate_cast_dtypes(selected: dict[str, Any]) -> None: + """Require supported noncategorical fixed dtypes for every selected cast column.""" + if not selected or any( + not isinstance(dtype, str) + or TYPE_ALIASES.get(dtype.lower(), dtype) not in set(TYPE_ALIASES.values()) + or TYPE_ALIASES.get(dtype.lower(), dtype) == "category" + for dtype in selected.values() + ): + raise ValueError("pre_split_steps Casting needs fixed noncategorical dtypes.") + + +def _replacement_maps(mapping: Any) -> Any: + """Validate string mapping keys and JSON-safe scalar values before choosing a mode.""" + maps = mapping.values() if isinstance(mapping, dict) else () + if ( + not isinstance(mapping, dict) + or not mapping + or any(not isinstance(key, str) for key in mapping) + or any(not isinstance(item, dict) and not _json_value(item) for item in maps) + ): + raise ValueError( + "pre_split_steps mapping needs string keys; use replacements pairs for numeric keys." + ) + return maps + + +def _validate_mapping_columns(mapping: dict[str, Any], maps: Any, columns: tuple[str, ...]) -> None: + """Validate per-column mapping structure before checking numeric key collisions.""" + nested = [isinstance(item, dict) for item in maps] + if any(nested) and (not all(nested) or any(column not in columns for column in mapping)): + raise ValueError("pre_split_steps nested mapping must name only selected columns.") + _validate_nested_mapping_values(maps) + for item in [mapping] if not any(nested) else maps: + identities = [_pair_key(key) for key in item] + if len(set(identities)) != len(identities): + raise ValueError("pre_split_steps mapping keys collide after numeric coercion.") + + +def _validate_nested_mapping_values(maps: Any) -> None: + """Require nested mapping keys and values to survive a JSON round trip.""" + for item in maps: + if isinstance(item, dict) and ( + any(not isinstance(key, str) for key in item) or not _json_value(item) + ): + raise ValueError( + "pre_split_steps mapping needs string keys; use replacements pairs for numeric keys." + ) + + +def _validate_pair_payload(pairs: Any) -> None: + """Check replacement pair structure and lossless JSON values before mode conflicts.""" + if pairs is not None and ( + not isinstance(pairs, list) + or not pairs + or any( + not isinstance(pair, dict) or set(pair) != {"old", "new"} or not _json_value(pair) + for pair in pairs + ) + ): + raise ValueError("pre_split_steps replacements requires lossless old/new pairs.") + + +def _validate_invalid_value_range(params: dict[str, Any], rule: Any) -> None: + """Require range bounds only for custom ranges and one replacement value field.""" + if rule == "custom_range" and all( + params.get(bound) is None for bound in ("min_value", "max_value") + ): + raise ValueError("pre_split_steps custom_range needs a bound.") + if rule != "custom_range" and any( + params.get(bound) is not None for bound in ("min_value", "max_value") + ): + raise ValueError("pre_split_steps range bounds require custom_range.") + if "replacement" in params and "value" in params: + raise ValueError("pre_split_steps choose replacement or value, not both.") + + +def _project_fixed_params( + clone: dict[str, Any], params: dict[str, Any], keep: list[str], selected: set[str] +) -> bool: + """Project cast or replacement parameters and report whether a mapping has any edits.""" + if clone["transformer"] == "Casting": + _project_cast_params(params, selected) + else: + params["columns"] = keep + if clone["transformer"] == "ValueReplacement" and isinstance(params.get("mapping"), dict): + mapping = params["mapping"] + if any(isinstance(value, dict) for value in mapping.values()): + params["mapping"] = { + column: value for column, value in mapping.items() if column in selected + } + if not any(params["mapping"].values()): + return False + return True + + +def _project_cast_params(params: dict[str, Any], selected: set[str]) -> None: + """Restrict column type maps and shared target casts to selected model columns.""" + params["column_types"] = { + column: dtype + for column, dtype in params.get("column_types", {}).items() + if column in selected + } + if "columns" in params: + params["columns"] = [column for column in params["columns"] if column in selected] + if not params.get("columns"): + params.pop("columns", None) + params.pop("target_type", None) diff --git a/skyulf-core/skyulf/integrations/databricks/local_publish.py b/skyulf-core/skyulf/integrations/databricks/local_publish.py index 6f9dc60a5..62ea5fb67 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_publish.py +++ b/skyulf-core/skyulf/integrations/databricks/local_publish.py @@ -16,7 +16,7 @@ from .batch import _manifest from .delta import history, publish_replace_period, table_identity from .local_batch import LocalSourceSpec, score_local_source -from .local_sdk import PreparedLocalWorkflow +from .local_sdk import LocalWorkflowConfig, PreparedLocalWorkflow _OUTPUT_TYPES = {"float64": "double", "int64": "long", "string": "string", "bool": "boolean"} _METADATA = PREDICTION_METADATA_COLUMNS @@ -37,34 +37,9 @@ def _validate_request( admission = validate_admission(spark, admission) if not prepared.preflight.ready or not isinstance(prepared.artifact, LocalPipelineArtifact): raise ValueError("Local publication requires a ready fitted local pipeline.") - config = prepared.config - if config.runtime != "databricks" or config.sink.kind != "uc_delta": - raise ValueError("Local publication requires a Databricks UC Delta sink.") - if config.sink.table != spec.output_table or config.source.kind != "uc_table": - raise ValueError("Configured UC source or target differs from the publication request.") - if config.source.table != source.table or config.source.version != source.version: - raise ValueError("Prepared source differs from the pinned Delta snapshot.") - if source.max_rows > config.source.max_rows or source.max_bytes > config.source.max_bytes: - raise ValueError("Source budget exceeds the prepared workflow budget.") - if config.model.kind != "local_pipeline" or config.model.name != spec.model_name: - raise ValueError("Publication model name differs from the prepared registry model.") - if prepared.preflight.model_version != spec.model_version: - raise ValueError("Publication model version differs from the pinned model.") - if prepared.preflight.model_digest != spec.model_digest: - raise ValueError("Publication model digest differs from the fitted artifact.") - if spec.code_version != version("skyulf-core"): - raise ValueError("Publication code version differs from the installed runtime.") - if ( - spec.source_version != source.version - or spec.record_key_columns != source.record_key_columns - or spec.period_column != source.period_column - or spec.period_start_utc != source.period_start.astimezone(spec.period_start_utc.tzinfo) - or spec.period_end_utc != source.period_end.astimezone(spec.period_end_utc.tzinfo) - or spec.business_timezone != source.business_timezone - ): - raise ValueError("Publication period and source contract must match exactly.") - if source.table == spec.output_table: - raise ValueError("Source and prediction target must be different tables.") + config = _validate_publication_source(source, prepared, spec) + _validate_publication_model(prepared, spec, config) + _validate_publication_period(source, spec) return admission @@ -88,18 +63,7 @@ def _check_target( or set(target.columns) != expected ): raise ValueError("Prediction target columns differ from the explicit local output schema.") - if period_column is not None: - if target.schema[period_column].dataType.typeName() != "timestamp": - raise ValueError("Prediction target period must be a Spark timestamp.") - if source_frame.schema[period_column].dataType.typeName() != "timestamp": - raise ValueError("Source period must be a Spark timestamp.") - for name in record_key_columns: - target_type = target.schema[name].dataType - if target_type != source_frame.schema[name].dataType or target_type.typeName() not in ( - "long", - "string", - ): - raise ValueError("Source and target row-key types must match and be long or string.") + _check_target_controls(source_frame, target, record_key_columns, period_column) for column in outputs: expected_type = _OUTPUT_TYPES.get(column.dtype) if expected_type is None or target.schema[column.name].dataType.typeName() != expected_type: @@ -157,6 +121,95 @@ def run_local_batch( output_names = _check_target( spark, source_frame, target, source.record_key_columns, source.period_column, prepared ) + bridge = _local_prediction_bridge(spark, source, scored, output_names, target) + period = source_frame[source.period_column] + source_period = source_frame.where( + (period >= functions.lit(spec.period_start_utc)) + & (period < functions.lit(spec.period_end_utc)) + ).select(*source.record_key_columns, source.period_column) + output = bridge.join(source_period, on=list(source.record_key_columns), how="inner") + output = _complete_local_output(output, target, spec, functions, count) + manifest = _manifest(spec, source_id, source.table, snapshot.committed_us, count, count) + committed_version, recorded, replayed = publish_replace_period( + spark, output, spec, manifest=manifest, admission=admission + ) + return BatchResult( + spec, + recorded["input_count"], + recorded["output_count"], + committed_version, + recorded, + replayed, + ) + + +def _validate_publication_source( + source: LocalSourceSpec, prepared: PreparedLocalWorkflow, spec: BatchSpec +) -> LocalWorkflowConfig: + """Validate configured target, pinned source and local input budgets.""" + config = prepared.config + if config.runtime != "databricks" or config.sink.kind != "uc_delta": + raise ValueError("Local publication requires a Databricks UC Delta sink.") + if config.sink.table != spec.output_table or config.source.kind != "uc_table": + raise ValueError("Configured UC source or target differs from the publication request.") + if config.source.table != source.table or config.source.version != source.version: + raise ValueError("Prepared source differs from the pinned Delta snapshot.") + if source.max_rows > config.source.max_rows or source.max_bytes > config.source.max_bytes: + raise ValueError("Source budget exceeds the prepared workflow budget.") + return config + + +def _validate_publication_model( + prepared: PreparedLocalWorkflow, spec: BatchSpec, config: LocalWorkflowConfig +) -> None: + """Validate pinned registry identity and installed scoring code.""" + if config.model.kind != "local_pipeline" or config.model.name != spec.model_name: + raise ValueError("Publication model name differs from the prepared registry model.") + if prepared.preflight.model_version != spec.model_version: + raise ValueError("Publication model version differs from the pinned model.") + if prepared.preflight.model_digest != spec.model_digest: + raise ValueError("Publication model digest differs from the fitted artifact.") + if spec.code_version != version("skyulf-core"): + raise ValueError("Publication code version differs from the installed runtime.") + + +def _validate_publication_period(source: LocalSourceSpec, spec: BatchSpec) -> None: + """Require publication boundaries to match the source contract exactly.""" + if ( + spec.source_version != source.version + or spec.record_key_columns != source.record_key_columns + or spec.period_column != source.period_column + or spec.period_start_utc != source.period_start.astimezone(spec.period_start_utc.tzinfo) + or spec.period_end_utc != source.period_end.astimezone(spec.period_end_utc.tzinfo) + or spec.business_timezone != source.business_timezone + ): + raise ValueError("Publication period and source contract must match exactly.") + if source.table == spec.output_table: + raise ValueError("Source and prediction target must be different tables.") + + +def _check_target_controls( + source_frame: Any, target: Any, record_key_columns: tuple[str, ...], period_column: str | None +) -> None: + """Validate target timestamp and row-key types against the source.""" + if period_column is not None: + if target.schema[period_column].dataType.typeName() != "timestamp": + raise ValueError("Prediction target period must be a Spark timestamp.") + if source_frame.schema[period_column].dataType.typeName() != "timestamp": + raise ValueError("Source period must be a Spark timestamp.") + for name in record_key_columns: + target_type = target.schema[name].dataType + if target_type != source_frame.schema[name].dataType or target_type.typeName() not in ( + "long", + "string", + ): + raise ValueError("Source and target row-key types must match and be long or string.") + + +def _local_prediction_bridge( + spark: Any, source: LocalSourceSpec, scored: Any, output_names: tuple[str, ...], target: Any +) -> Any: + """Check local prediction keys and construct a Spark frame with target types.""" bridge_names = (*source.record_key_columns, *output_names) if list(scored.predictions.columns) != list(bridge_names): raise ValueError("Local prediction columns differ from the saved model output.") @@ -170,12 +223,13 @@ def run_local_batch( for row in scored.predictions.itertuples(index=False, name=None) ] bridge = spark.createDataFrame(records, schema=bridge_schema) - period = source_frame[source.period_column] - source_period = source_frame.where( - (period >= functions.lit(spec.period_start_utc)) - & (period < functions.lit(spec.period_end_utc)) - ).select(*source.record_key_columns, source.period_column) - output = bridge.join(source_period, on=list(source.record_key_columns), how="inner") + return bridge + + +def _complete_local_output( + output: Any, target: Any, spec: BatchSpec, functions: Any, count: int +) -> Any: + """Attach prediction identity and verify final output schema and membership.""" for name, value in ( ("run_id", spec.run_id), ("model_name", spec.model_name), @@ -189,15 +243,4 @@ def run_local_batch( output = output.select(*target.columns) if output.count() != count: raise ValueError("Prediction keys do not match the pinned source rows.") - manifest = _manifest(spec, source_id, source.table, snapshot.committed_us, count, count) - committed_version, recorded, replayed = publish_replace_period( - spark, output, spec, manifest=manifest, admission=admission - ) - return BatchResult( - spec, - recorded["input_count"], - recorded["output_count"], - committed_version, - recorded, - replayed, - ) + return output diff --git a/skyulf-core/skyulf/integrations/databricks/local_retraining.py b/skyulf-core/skyulf/integrations/databricks/local_retraining.py index aefff5d01..da1f0d5de 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_retraining.py +++ b/skyulf-core/skyulf/integrations/databricks/local_retraining.py @@ -137,19 +137,7 @@ def __post_init__(self) -> None: def _validate_random_split(self) -> None: """Check the random split and its optional event-selection window.""" - if self.holdout_start is not None: - raise ValueError("Random split requires inactive holdout_start to be null.") - if self.event_column is None and ( - self.start is not None - or self.cutoff is not None - or self.event_time_parsing != TrainingDateSpec() - ): - raise ValueError("Random split requires inactive event/date fields to be null.") - if self.event_column is not None: - start = _validate_instant(self.start, "start") - cutoff = _validate_instant(self.cutoff, "cutoff") - if start >= cutoff: - raise ValueError("Require start < cutoff for event selection.") + _validate_random_window(self) if ( self.test_size is None or type(self.test_size) not in (int, float) @@ -171,14 +159,7 @@ def _validate_temporal_split(self) -> None: ] if not boundaries[0] < boundaries[1] < boundaries[2]: raise ValueError("Require start < holdout_start < cutoff.") - if ( - self.test_size not in (None, 0.2) - or self.random_state not in (None, 42) - or self.stratify not in (None, False) - or (self.random_state is not None and type(self.random_state) is not int) - or (self.stratify is not None and type(self.stratify) is not bool) - ): - raise ValueError("Temporal split cannot use active random split settings.") + _validate_inactive_random_settings(self) def _validate_result_filter(self) -> None: """Require a cutoff only when result-availability filtering is enabled.""" @@ -299,16 +280,7 @@ def _missing_row_filter_columns(params: dict[str, Any]) -> list[str]: "missing_threshold", }: raise ValueError("pre_split_steps DropMissingRows has invalid row-filter params.") - threshold = params.get("threshold") - if threshold is not None and (type(threshold) is not int or not 0 <= threshold <= len(subset)): - raise ValueError("pre_split_steps threshold must be an integer from 0 to subset size.") - missing_threshold = params.get("missing_threshold") - if missing_threshold is not None and ( - type(missing_threshold) not in (int, float) - or not math.isfinite(missing_threshold) - or not 0 <= missing_threshold <= 100 - ): - raise ValueError("pre_split_steps missing_threshold must be between 0 and 100.") + _validate_missing_thresholds(params, len(subset)) return subset @@ -318,15 +290,7 @@ def _validate_manual_limits(limit: dict[str, Any]) -> None: key in limit and limit[key] is not None for key in ("lower", "upper") ): raise ValueError("pre_split_steps ManualBounds requires lower or upper.") - for value in limit.values(): - if value is not None and (type(value) not in (int, float) or not math.isfinite(value)): - raise ValueError("pre_split_steps ManualBounds requires finite numeric bounds.") - if ( - limit.get("lower") is not None - and limit.get("upper") is not None - and limit["lower"] > limit["upper"] - ): - raise ValueError("pre_split_steps ManualBounds lower must not exceed upper.") + _validate_manual_bound_values(limit) def _manual_bounds_columns(params: dict[str, Any]) -> list[str]: @@ -381,12 +345,7 @@ def _validate_pre_split_step( step: Any, index: int, target_column: str, protected: tuple[str | None, ...] ) -> tuple[str, ...] | list[str]: """Reject learned or malformed steps before accepting their source dependencies.""" - if not isinstance(step, dict) or not isinstance(step.get("name"), str) or not step["name"]: - raise ValueError(f"pre_split_steps[{index}] requires a name.") - step_type = step.get("transformer") - params = step.get("params", {}) - if not isinstance(params, dict) or not isinstance(step_type, str): - raise ValueError(f"pre_split_steps[{index}] requires a Core transformer and params.") + step_type, params = _pre_split_step_identity(step, index) custom_filter = is_registered_project_step(step_type) if ( step_type != "Deduplicate" @@ -476,22 +435,7 @@ def read_training_snapshot(spark: Any, spec: LocalTrainingSpec) -> pd.DataFrame: source, selection = _sample_training_source(source, spec) ordering = ([spec.event_column] if spec.event_column else []) + list(spec.record_key_columns) selected = source.orderBy(*ordering).limit(spec.max_rows + 1) - records: list[dict[str, Any]] = [] - serialized_bytes = 0 - for row in selected.toLocalIterator(): - if len(records) >= spec.max_rows: - raise ValueError("Training source exceeds max_rows.") - record = row.asDict(recursive=True) if hasattr(row, "asDict") else dict(row) - for name in (spec.event_column, spec.result_available_at_column): - if name is not None: - record[name] = instant_from_microseconds(record[name]) - serialized_bytes += len(pickle.dumps(record, protocol=pickle.HIGHEST_PROTOCOL)) - if serialized_bytes > spec.max_bytes: - raise ValueError("Training source exceeds max_bytes.") - records.append(record) - frame = pd.DataFrame.from_records(records, columns=names) - if _frame_bytes(frame) > spec.max_bytes: - raise ValueError("Training frame exceeds max_bytes.") + frame = _materialize_training_rows(selected, spec, names) if selection is not None: frame.attrs["training_selection"] = {**selection, "selected_rows": len(frame)} return frame @@ -507,20 +451,7 @@ def _sample_training_source(source: Any, spec: LocalTrainingSpec) -> tuple[Any, for field in source.schema.fields if field.dataType.typeName() in {"double", "float"} } - null_keys = " OR ".join( - f"({column_name(key)} IS NULL OR isnan({column_name(key)}))" - if key in floating - else f"{column_name(key)} IS NULL" - for key in keys - ) - if source.where(null_keys).limit(1).count(): - raise ValueError("Training row keys must not be null.") - count_name = "_sample_count" - while count_name.casefold() in {key.casefold() for key in keys}: - count_name += "_" - counts = source.groupBy(*keys).agg(F.count(F.lit(1)).alias(count_name)) - if counts.where(F.col(count_name) > 1).limit(1).count(): - raise ValueError("Training row keys must be unique before sampling.") + _validate_sample_keys(source, keys, floating, F) source_rows = source.count() if spec.filter_unavailable_results: result = column_name(cast(str, spec.result_available_at_column)) @@ -532,15 +463,7 @@ def _sample_training_source(source: Any, spec: LocalTrainingSpec) -> tuple[Any, cutoff = instant_microseconds(cast(datetime, spec.result_cutoff)) source = source.where(f"{result} IS NOT NULL AND {result} <= {cutoff}") eligible_rows = source.count() if spec.filter_unavailable_results else source_rows - invalid_target = F.col(spec.target_column).isNull() - if spec.target_column in floating: - invalid_target = invalid_target | F.isnan(F.col(spec.target_column)) - target_filter = any( - step["transformer"] == "DropMissingRows" and spec.target_column in step["params"]["subset"] - for step in spec.pre_split_steps - ) - if not target_filter and source.where(invalid_target).limit(1).count(): - raise ValueError("Available labels must have nonnull targets before sampling.") + _validate_sample_targets(source, spec, floating, F) # Struct field order, UTC timestamp rendering and the tie-break keys are # explicit so partition layout and Spark session timezone cannot change membership. key_json = F.to_json( @@ -592,26 +515,7 @@ def _validate_pre_split_inputs( if any(column not in native.columns for column in columns): missing = sorted(set(columns) - set(native.columns)) raise ValueError(f"pre_split_steps {step['name']} missing source columns: {missing}.") - if step["transformer"] == "ManualBounds": - for column in columns: - if isinstance(native, pl.DataFrame): - numeric = native.schema[column].is_numeric() - else: - dtype = native[column].dtype - numeric = pd.api.types.is_numeric_dtype(dtype) and not pd.api.types.is_bool_dtype( - dtype - ) - if not numeric: - raise ValueError(f"pre_split_steps ManualBounds requires numeric column {column}.") - if step_type == "Deduplicate": - working = native.to_pandas() if isinstance(native, pl.DataFrame) else native - for _, group in working.groupby(list(columns), dropna=False, sort=False): - labels = group[target_column] - if labels.nunique(dropna=True) > 1 or (labels.isna().any() and labels.notna().any()): - raise ValueError( - "pre_split_steps Deduplicate found conflicting target values " - "within one subset group." - ) + _validate_filter_values(native, step, columns, target_column) return list(columns) @@ -635,18 +539,9 @@ def _validate_pre_split_survivors( positions[key] for key in after_keys ] != sorted({positions[key] for key in after_keys}): raise ValueError("pre_split_steps must preserve row identities and order.") - for column in filtered.columns: - if column in allowed_edits: - continue - after_values = filtered[column].to_list() - for key, value in zip(after_keys, after_values, strict=True): - expected = before_columns[column][positions[key]] - expected_missing = bool(pd.isna(expected)) - value_missing = bool(pd.isna(value)) - if expected_missing != value_missing or (not expected_missing and expected != value): - if column == target_column: - raise ValueError("pre_split_steps must preserve target pairing.") - raise ValueError(f"pre_split_steps changed undeclared column {column}.") + _validate_survivor_values( + filtered, after_keys, positions, before_columns, target_column, allowed_edits + ) def _apply_pre_split_steps( @@ -669,12 +564,7 @@ def _apply_pre_split_steps( before_columns = {column: native[column].to_list() for column in native.columns} artifact = NodeRegistry.get_calculator(step["transformer"])().fit(native, step["params"]) filtered = NodeRegistry.get_applier(step["transformer"])().apply(native, artifact) - if not isinstance(filtered, type(native)): - raise ValueError("pre_split_steps filter did not return a frame.") - if list(filtered.columns) != original_columns: - raise ValueError("pre_split_steps must preserve all source columns.") - if is_registered_project_step(step_type) and list(filtered.dtypes) != original_dtypes: - raise ValueError("pre_split_steps custom filter must preserve source dtypes.") + _validate_filter_frame(filtered, native, step_type, original_columns, original_dtypes) _validate_pre_split_survivors( filtered, keys, @@ -711,131 +601,25 @@ def split_labeled_snapshot( Candidate training installs the saved fixed feature prefix before model fit; callers of this function receive untransformed model features. """ - if not isinstance(frame, pd.DataFrame) or not isinstance(spec, LocalTrainingSpec): - raise TypeError("Expected a pandas frame and LocalTrainingSpec.") - _pre_split_columns( - spec.pre_split_steps, - spec.target_column, - (*spec.record_key_columns, spec.event_column, spec.result_available_at_column), - ) - if engine not in ("pandas", "polars"): - raise ValueError("engine must be pandas or polars.") - missing_columns = sorted(set(spec.source_columns) - set(frame.columns)) - if missing_columns: - raise ValueError( - f"Training snapshot is missing required source columns: {missing_columns}." - ) - if len(frame) > spec.max_rows or _frame_bytes(frame) > spec.max_bytes: - raise ValueError("Training snapshot exceeds max_rows or max_bytes.") - if frame.loc[:, list(spec.record_key_columns)].isna().any().any(): - raise ValueError("Training row keys must not be null.") - if frame.duplicated(subset=list(spec.record_key_columns)).any(): - raise ValueError("Training row keys must be unique.") + _validate_labeled_snapshot(frame, spec, engine) selected = frame.copy() - events = None - if spec.event_column is not None: - events = pd.Series( - [ - parse_training_date(value, spec.event_time_parsing) - for value in frame[spec.event_column] - ], - index=frame.index, - dtype="datetime64[ns, UTC]", - ) - if events.isna().any() or (events < spec.start).any() or (events >= spec.cutoff).any(): - raise ValueError("Training event time falls outside the pinned window.") - selected[spec.event_column] = events - available = pd.Series(True, index=frame.index) - if spec.filter_unavailable_results: - labels = pd.Series( - [ - parse_training_date(value, spec.result_time_parsing, allow_null=True) - for value in frame[spec.result_available_at_column] - ], - index=frame.index, - dtype="datetime64[ns, UTC]", - ) - if events is not None and ((labels < events) & labels.notna()).any(): - raise ValueError("Label availability precedes event time.") - available = labels.notna() & (labels <= spec.result_cutoff) + available = _label_availability(frame, selected, spec) ordering = ([spec.event_column] if spec.event_column else []) + list(spec.record_key_columns) selected = selected.loc[available].sort_values(ordering, kind="stable").reset_index(drop=True) raw_selected = selected.copy() - sample_digest = None - if spec.training_sample_rows is not None: - if len(selected) > spec.training_sample_rows: - raise ValueError("Training snapshot was not bounded by training_sample_rows.") - sample_digest = _key_digest(selected, spec.record_key_columns) - if spec.sample_key_sha256 is not None and sample_digest != spec.sample_key_sha256: - raise ValueError("Training sample membership differs from saved evidence.") + sample_digest = _training_sample_digest(selected, spec) pre_filter_digest = _key_digest(selected, spec.record_key_columns) selected, filter_counts = _apply_pre_split_steps(selected, spec, engine) survivor_digest = _key_digest(selected, spec.record_key_columns) - if spec.survivor_key_sha256 is not None and survivor_digest != spec.survivor_key_sha256: - raise ValueError("Survivor membership differs from saved training evidence.") - if selected[spec.target_column].isna().any(): - raise ValueError( - "Available labels must have nonnull targets; add explicit DropMissingRows for the target." - ) - if spec.pre_split_steps and len(selected) < 4: - raise ValueError( - "Training filters leave fewer than four eligible rows for train and holdout." - ) - if spec.split_strategy == "random": - if spec.stratify: - counts = selected[spec.target_column].value_counts() - if counts.empty or counts.min() < 2: - raise ValueError("Requested stratification requires at least two rows per class.") - test_rows = math.ceil(len(selected) * cast(float, spec.test_size)) - if min(test_rows, len(selected) - test_rows) < len(counts): - raise ValueError("Requested stratification needs each class in both partitions.") - split = DataSplitter( - test_size=cast(float, spec.test_size), - random_state=cast(int, spec.random_state), - stratify_col=spec.target_column if spec.stratify else None, - ).split(selected) - train, heldout = cast(pd.DataFrame, split.train), cast(pd.DataFrame, split.test) - else: - holdout_mask = selected[spec.event_column] >= spec.holdout_start - train, heldout = selected.loc[~holdout_mask], selected.loc[holdout_mask] - if len(train) < 2 or len(heldout) < 2: - raise ValueError("Training and holdout each need at least two labeled rows.") + _validate_training_survivors(selected, spec, survivor_digest) + train, heldout = _partition_training_rows(selected, spec) # Hash the ordered identity tuples only; never include keys in model features. digest = _key_digest(heldout, spec.record_key_columns) if spec.holdout_key_sha256 is not None and digest != spec.holdout_key_sha256: raise ValueError("Holdout membership differs from saved training evidence.") - columns = [*spec.input_columns, spec.target_column] - train_columns = ( - [*columns, spec.event_column] if keep_training_event and spec.event_column else columns + train_frame, holdout_frame = _raw_model_partitions( + train, heldout, raw_selected, spec, keep_training_event ) - if spec.pre_split_steps: - raw_positions = { - key: index - for index, key in enumerate( - raw_selected.loc[:, list(spec.record_key_columns)].itertuples( - index=False, name=None - ) - ) - } - - def raw_partition(partition: pd.DataFrame, output_columns: list[str]) -> pd.DataFrame: - """Recover untouched model inputs by immutable keys after normalized splitting.""" - keys = partition.loc[:, list(spec.record_key_columns)].itertuples( - index=False, name=None - ) - raw = ( - raw_selected.iloc[[raw_positions[key] for key in keys]] - .loc[:, output_columns] - .copy() - ) - raw[spec.target_column] = partition[spec.target_column].to_numpy() - return raw.reset_index(drop=True) - - train_frame = raw_partition(train, train_columns) - holdout_frame = raw_partition(heldout, columns) - else: - train_frame = train.loc[:, train_columns].reset_index(drop=True) - holdout_frame = heldout.loc[:, columns].reset_index(drop=True) holdout_frame.attrs["holdout_key_sha256"] = digest holdout_frame.attrs["sample_key_sha256"] = sample_digest holdout_frame.attrs["pre_split_filter_counts"] = filter_counts @@ -930,28 +714,14 @@ def _candidate_config( != "classification" ): raise ValueError("stratify requires a classification model.") - if risk_category is not None and ( - not isinstance(risk_category, str) or len(risk_category.encode("utf-8")) > 256 - ): - raise ValueError("risk_category must be text of at most 256 UTF-8 bytes.") - if ( - type(min_improvement) not in (int, float) - or not math.isfinite(min_improvement) - or min_improvement < 0 - ): - raise ValueError("min_improvement must be a finite nonnegative number.") + _validate_candidate_metadata(risk_category, min_improvement) validate_quality_policy( metric, quality_threshold, quality_gates, task=NodeRegistry.get_calculator(base_model_config(config)["type"])().problem_type, ) - if champion_version is not None and ( - type(champion_version) is not str - or not champion_version.isdecimal() - or int(champion_version) <= 0 - ): - raise ValueError("champion_version must be a concrete positive version.") + _validate_champion_version(champion_version) return pipeline_config @@ -1002,13 +772,7 @@ def _fit_candidate( target_column=spec.target_column, event_column=spec.event_column if temporal_cv else None, ) - if temporal_cv and not search: - model_columns = [*spec.input_columns, spec.target_column] - native_train = ( - native_train.select(model_columns) - if isinstance(native_train, pl.DataFrame) - else native_train.loc[:, model_columns] - ) + native_train = _final_fit_frame(native_train, spec, temporal_cv, search) artifact = fit_local_workflow( pipeline_config, SplitDataset(train=native_train, test=native_train.head(0)), @@ -1064,19 +828,7 @@ def _log_fitted_candidate( frame, holdout = fitted.source_frame, fitted.evidence_holdout cv_results, evidence = fitted.cv_results, fitted.evidence unavailable = fitted.unavailable_labels - if config["modeling"]["type"] == "hyperparameter_tuner": - search_result = tuning_evidence(artifact) - if search_result is None: - raise ValueError("Fitted search artifact lacks tuning evidence.") - run.client.log_dict(run.run_id, search_result, "tuning.json") - run.log_params( - { - "tuning_strategy": search_result["modeling"]["strategy"], - "tuning_metric": search_result["scoring_metric"], - "tuning_trials": search_result["n_trials"], - } - ) - run.log_metrics({"tuning_best_score": search_result["best_score"]}) + _log_tuning_evidence(run, artifact, config) if cv_results is not None: cv_results.update( dataset_id=spec.dataset_id, training_rows=fitted.training_rows, engine=engine @@ -1363,3 +1115,411 @@ def train_local_candidate( holdout_rows=fitted.holdout_rows, unavailable=fitted.unavailable_labels, ) + + +def _validate_random_window(spec: LocalTrainingSpec) -> None: + """Validate optional event selection independently of random partition settings.""" + if spec.holdout_start is not None: + raise ValueError("Random split requires inactive holdout_start to be null.") + if spec.event_column is None and ( + spec.start is not None + or spec.cutoff is not None + or spec.event_time_parsing != TrainingDateSpec() + ): + raise ValueError("Random split requires inactive event/date fields to be null.") + if spec.event_column is not None: + start = _validate_instant(spec.start, "start") + cutoff = _validate_instant(spec.cutoff, "cutoff") + if start >= cutoff: + raise ValueError("Require start < cutoff for event selection.") + + +def _validate_inactive_random_settings(spec: LocalTrainingSpec) -> None: + """Reject active or mistyped random settings for a temporal split.""" + if ( + spec.test_size not in (None, 0.2) + or spec.random_state not in (None, 42) + or spec.stratify not in (None, False) + or (spec.random_state is not None and type(spec.random_state) is not int) + or (spec.stratify is not None and type(spec.stratify) is not bool) + ): + raise ValueError("Temporal split cannot use active random split settings.") + + +def _validate_missing_thresholds(params: dict[str, Any], subset_size: int) -> None: + """Require count and percentage thresholds within the explicitly selected subset.""" + threshold = params.get("threshold") + if threshold is not None and (type(threshold) is not int or not 0 <= threshold <= subset_size): + raise ValueError("pre_split_steps threshold must be an integer from 0 to subset size.") + missing_threshold = params.get("missing_threshold") + if missing_threshold is not None and ( + type(missing_threshold) not in (int, float) + or not math.isfinite(missing_threshold) + or not 0 <= missing_threshold <= 100 + ): + raise ValueError("pre_split_steps missing_threshold must be between 0 and 100.") + + +def _validate_manual_bound_values(limit: dict[str, Any]) -> None: + """Check finite numeric values before comparing lower and upper manual limits.""" + for value in limit.values(): + if value is not None and (type(value) not in (int, float) or not math.isfinite(value)): + raise ValueError("pre_split_steps ManualBounds requires finite numeric bounds.") + if ( + limit.get("lower") is not None + and limit.get("upper") is not None + and limit["lower"] > limit["upper"] + ): + raise ValueError("pre_split_steps ManualBounds lower must not exceed upper.") + + +def _pre_split_step_identity(step: Any, index: int) -> tuple[str, dict[str, Any]]: + """Validate a named Core transformer and its parameter object before policy checks.""" + if not isinstance(step, dict) or not isinstance(step.get("name"), str) or not step["name"]: + raise ValueError(f"pre_split_steps[{index}] requires a name.") + step_type = step.get("transformer") + params = step.get("params", {}) + if not isinstance(params, dict) or not isinstance(step_type, str): + raise ValueError(f"pre_split_steps[{index}] requires a Core transformer and params.") + return step_type, params + + +def _materialize_training_rows( + selected: Any, spec: LocalTrainingSpec, names: tuple[str, ...] +) -> pd.DataFrame: + """Decode bounded rows and dates while enforcing serialized and local frame budgets.""" + records: list[dict[str, Any]] = [] + serialized_bytes = 0 + for row in selected.toLocalIterator(): + if len(records) >= spec.max_rows: + raise ValueError("Training source exceeds max_rows.") + record = row.asDict(recursive=True) if hasattr(row, "asDict") else dict(row) + for name in (spec.event_column, spec.result_available_at_column): + if name is not None: + record[name] = instant_from_microseconds(record[name]) + serialized_bytes += len(pickle.dumps(record, protocol=pickle.HIGHEST_PROTOCOL)) + if serialized_bytes > spec.max_bytes: + raise ValueError("Training source exceeds max_bytes.") + records.append(record) + frame = pd.DataFrame.from_records(records, columns=names) + if _frame_bytes(frame) > spec.max_bytes: + raise ValueError("Training frame exceeds max_bytes.") + return frame + + +def _validate_sample_keys(source: Any, keys: list[str], floating: set[str], F: Any) -> None: + """Reject missing and duplicated sampling keys before counting the source population.""" + null_keys = " OR ".join( + f"({column_name(key)} IS NULL OR isnan({column_name(key)}))" + if key in floating + else f"{column_name(key)} IS NULL" + for key in keys + ) + if source.where(null_keys).limit(1).count(): + raise ValueError("Training row keys must not be null.") + count_name = "_sample_count" + while count_name.casefold() in {key.casefold() for key in keys}: + count_name += "_" + counts = source.groupBy(*keys).agg(F.count(F.lit(1)).alias(count_name)) + if counts.where(F.col(count_name) > 1).limit(1).count(): + raise ValueError("Training row keys must be unique before sampling.") + + +def _validate_sample_targets( + source: Any, spec: LocalTrainingSpec, floating: set[str], F: Any +) -> None: + """Require available targets unless an explicit missing-target filter owns exclusion.""" + invalid_target = F.col(spec.target_column).isNull() + if spec.target_column in floating: + invalid_target = invalid_target | F.isnan(F.col(spec.target_column)) + target_filter = any( + step["transformer"] == "DropMissingRows" and spec.target_column in step["params"]["subset"] + for step in spec.pre_split_steps + ) + if not target_filter and source.where(invalid_target).limit(1).count(): + raise ValueError("Available labels must have nonnull targets before sampling.") + + +def _validate_filter_values( + native: pd.DataFrame | pl.DataFrame, step: dict[str, Any], columns: Any, target_column: str +) -> None: + """Check numeric bounds and label consistency after required columns exist.""" + step_type = step["transformer"] + if step["transformer"] == "ManualBounds": + for column in columns: + if isinstance(native, pl.DataFrame): + numeric = native.schema[column].is_numeric() + else: + dtype = native[column].dtype + numeric = pd.api.types.is_numeric_dtype(dtype) and not pd.api.types.is_bool_dtype( + dtype + ) + if not numeric: + raise ValueError(f"pre_split_steps ManualBounds requires numeric column {column}.") + if step_type == "Deduplicate": + _validate_deduplicate_labels(native, columns, target_column) + + +def _validate_deduplicate_labels( + native: pd.DataFrame | pl.DataFrame, columns: Any, target_column: str +) -> None: + """Reject groups whose deduplication would choose among conflicting labels.""" + working = native.to_pandas() if isinstance(native, pl.DataFrame) else native + for _, group in working.groupby(list(columns), dropna=False, sort=False): + labels = group[target_column] + if labels.nunique(dropna=True) > 1 or (labels.isna().any() and labels.notna().any()): + raise ValueError( + "pre_split_steps Deduplicate found conflicting target values " + "within one subset group." + ) + + +def _validate_survivor_values( + filtered: pd.DataFrame | pl.DataFrame, + after_keys: list[tuple[Any, ...]], + positions: dict[tuple[Any, ...], int], + before_columns: dict[str, list[Any]], + target_column: str, + allowed_edits: set[str], +) -> None: + """Preserve target pairing and every source value outside declared fixed edits.""" + for column in filtered.columns: + if column in allowed_edits: + continue + after_values = filtered[column].to_list() + for key, value in zip(after_keys, after_values, strict=True): + expected = before_columns[column][positions[key]] + expected_missing = bool(pd.isna(expected)) + value_missing = bool(pd.isna(value)) + if expected_missing != value_missing or (not expected_missing and expected != value): + if column == target_column: + raise ValueError("pre_split_steps must preserve target pairing.") + raise ValueError(f"pre_split_steps changed undeclared column {column}.") + + +def _validate_filter_frame( + filtered: Any, + native: pd.DataFrame | pl.DataFrame, + step_type: str, + original_columns: list[str], + original_dtypes: list[Any], +) -> None: + """Require the same frame type and columns, plus stable custom-filter dtypes.""" + if not isinstance(filtered, type(native)): + raise ValueError("pre_split_steps filter did not return a frame.") + if list(filtered.columns) != original_columns: + raise ValueError("pre_split_steps must preserve all source columns.") + if is_registered_project_step(step_type) and list(filtered.dtypes) != original_dtypes: + raise ValueError("pre_split_steps custom filter must preserve source dtypes.") + + +def _validate_labeled_snapshot(frame: pd.DataFrame, spec: LocalTrainingSpec, engine: str) -> None: + """Validate the split request, source schema, budgets and unique identities.""" + if not isinstance(frame, pd.DataFrame) or not isinstance(spec, LocalTrainingSpec): + raise TypeError("Expected a pandas frame and LocalTrainingSpec.") + _pre_split_columns( + spec.pre_split_steps, + spec.target_column, + (*spec.record_key_columns, spec.event_column, spec.result_available_at_column), + ) + if engine not in ("pandas", "polars"): + raise ValueError("engine must be pandas or polars.") + missing_columns = sorted(set(spec.source_columns) - set(frame.columns)) + if missing_columns: + raise ValueError( + f"Training snapshot is missing required source columns: {missing_columns}." + ) + if len(frame) > spec.max_rows or _frame_bytes(frame) > spec.max_bytes: + raise ValueError("Training snapshot exceeds max_rows or max_bytes.") + if frame.loc[:, list(spec.record_key_columns)].isna().any().any(): + raise ValueError("Training row keys must not be null.") + if frame.duplicated(subset=list(spec.record_key_columns)).any(): + raise ValueError("Training row keys must be unique.") + + +def _label_availability( + frame: pd.DataFrame, selected: pd.DataFrame, spec: LocalTrainingSpec +) -> pd.Series: + """Normalize source event times before checking result availability and cutoff.""" + events = None + if spec.event_column is not None: + events = pd.Series( + [ + parse_training_date(value, spec.event_time_parsing) + for value in frame[spec.event_column] + ], + index=frame.index, + dtype="datetime64[ns, UTC]", + ) + if events.isna().any() or (events < spec.start).any() or (events >= spec.cutoff).any(): + raise ValueError("Training event time falls outside the pinned window.") + selected[spec.event_column] = events + available = pd.Series(True, index=frame.index) + if spec.filter_unavailable_results: + labels = pd.Series( + [ + parse_training_date(value, spec.result_time_parsing, allow_null=True) + for value in frame[spec.result_available_at_column] + ], + index=frame.index, + dtype="datetime64[ns, UTC]", + ) + if events is not None and ((labels < events) & labels.notna()).any(): + raise ValueError("Label availability precedes event time.") + available = labels.notna() & (labels <= spec.result_cutoff) + return available + + +def _training_sample_digest(selected: pd.DataFrame, spec: LocalTrainingSpec) -> str | None: + """Verify bounded sample size and the saved ordered sample membership.""" + sample_digest = None + if spec.training_sample_rows is not None: + if len(selected) > spec.training_sample_rows: + raise ValueError("Training snapshot was not bounded by training_sample_rows.") + sample_digest = _key_digest(selected, spec.record_key_columns) + if spec.sample_key_sha256 is not None and sample_digest != spec.sample_key_sha256: + raise ValueError("Training sample membership differs from saved evidence.") + return sample_digest + + +def _validate_training_survivors( + selected: pd.DataFrame, spec: LocalTrainingSpec, survivor_digest: str +) -> None: + """Require pinned survivor membership, available targets and enough eligible rows.""" + if spec.survivor_key_sha256 is not None and survivor_digest != spec.survivor_key_sha256: + raise ValueError("Survivor membership differs from saved training evidence.") + if selected[spec.target_column].isna().any(): + raise ValueError( + "Available labels must have nonnull targets; add explicit DropMissingRows for the target." + ) + if spec.pre_split_steps and len(selected) < 4: + raise ValueError( + "Training filters leave fewer than four eligible rows for train and holdout." + ) + + +def _partition_training_rows( + selected: pd.DataFrame, spec: LocalTrainingSpec +) -> tuple[pd.DataFrame, pd.DataFrame]: + """Build reproducible random or temporal partitions with viable labeled row counts.""" + if spec.split_strategy == "random": + if spec.stratify: + counts = selected[spec.target_column].value_counts() + if counts.empty or counts.min() < 2: + raise ValueError("Requested stratification requires at least two rows per class.") + test_rows = math.ceil(len(selected) * cast(float, spec.test_size)) + if min(test_rows, len(selected) - test_rows) < len(counts): + raise ValueError("Requested stratification needs each class in both partitions.") + split = DataSplitter( + test_size=cast(float, spec.test_size), + random_state=cast(int, spec.random_state), + stratify_col=spec.target_column if spec.stratify else None, + ).split(selected) + train, heldout = cast(pd.DataFrame, split.train), cast(pd.DataFrame, split.test) + else: + holdout_mask = selected[spec.event_column] >= spec.holdout_start + train, heldout = selected.loc[~holdout_mask], selected.loc[holdout_mask] + if len(train) < 2 or len(heldout) < 2: + raise ValueError("Training and holdout each need at least two labeled rows.") + return train, heldout + + +def _raw_model_partitions( + train: pd.DataFrame, + heldout: pd.DataFrame, + raw_selected: pd.DataFrame, + spec: LocalTrainingSpec, + keep_training_event: bool, +) -> tuple[pd.DataFrame, pd.DataFrame]: + """Recover untouched features by immutable keys while retaining normalized target values.""" + columns = [*spec.input_columns, spec.target_column] + train_columns = ( + [*columns, spec.event_column] if keep_training_event and spec.event_column else columns + ) + if spec.pre_split_steps: + raw_positions = { + key: index + for index, key in enumerate( + raw_selected.loc[:, list(spec.record_key_columns)].itertuples( + index=False, name=None + ) + ) + } + + def raw_partition(partition: pd.DataFrame, output_columns: list[str]) -> pd.DataFrame: + """Recover untouched model inputs by immutable keys after normalized splitting.""" + keys = partition.loc[:, list(spec.record_key_columns)].itertuples( + index=False, name=None + ) + raw = ( + raw_selected.iloc[[raw_positions[key] for key in keys]] + .loc[:, output_columns] + .copy() + ) + raw[spec.target_column] = partition[spec.target_column].to_numpy() + return raw.reset_index(drop=True) + + train_frame = raw_partition(train, train_columns) + holdout_frame = raw_partition(heldout, columns) + else: + train_frame = train.loc[:, train_columns].reset_index(drop=True) + holdout_frame = heldout.loc[:, columns].reset_index(drop=True) + return train_frame, holdout_frame + + +def _validate_candidate_metadata(risk_category: str | None, min_improvement: float) -> None: + """Validate risk label size and a finite nonnegative improvement requirement.""" + if risk_category is not None and ( + not isinstance(risk_category, str) or len(risk_category.encode("utf-8")) > 256 + ): + raise ValueError("risk_category must be text of at most 256 UTF-8 bytes.") + if ( + type(min_improvement) not in (int, float) + or not math.isfinite(min_improvement) + or min_improvement < 0 + ): + raise ValueError("min_improvement must be a finite nonnegative number.") + + +def _validate_champion_version(champion_version: str | None) -> None: + """Require an explicitly supplied champion version to be a positive decimal string.""" + if champion_version is not None and ( + type(champion_version) is not str + or not champion_version.isdecimal() + or int(champion_version) <= 0 + ): + raise ValueError("champion_version must be a concrete positive version.") + + +def _final_fit_frame( + native_train: pd.DataFrame | pl.DataFrame, + spec: LocalTrainingSpec, + temporal_cv: bool, + search: bool, +) -> pd.DataFrame | pl.DataFrame: + """Remove CV-only event metadata before fitting a fixed final model.""" + if temporal_cv and not search: + model_columns = [*spec.input_columns, spec.target_column] + native_train = ( + native_train.select(model_columns) + if isinstance(native_train, pl.DataFrame) + else native_train.loc[:, model_columns] + ) + return native_train + + +def _log_tuning_evidence(run: Any, artifact: Any, config: dict[str, Any]) -> None: + """Persist fitted search evidence and metrics before logging CV results.""" + if config["modeling"]["type"] == "hyperparameter_tuner": + search_result = tuning_evidence(artifact) + if search_result is None: + raise ValueError("Fitted search artifact lacks tuning evidence.") + run.client.log_dict(run.run_id, search_result, "tuning.json") + run.log_params( + { + "tuning_strategy": search_result["modeling"]["strategy"], + "tuning_metric": search_result["scoring_metric"], + "tuning_trials": search_result["n_trials"], + } + ) + run.log_metrics({"tuning_best_score": search_result["best_score"]}) diff --git a/skyulf-core/skyulf/integrations/databricks/local_sdk.py b/skyulf-core/skyulf/integrations/databricks/local_sdk.py index 61549f5cf..3c37fae13 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_sdk.py +++ b/skyulf-core/skyulf/integrations/databricks/local_sdk.py @@ -95,12 +95,7 @@ def validate_selector(self) -> ModelSelection: not self.name or not self.name.strip() or (self.alias is None) == (self.version is None) ): raise ValueError("A registry model needs a name and exactly one alias or version.") - if self.alias is not None and not self.alias.strip(): - raise ValueError("alias must be non-empty.") - if self.version is not None and ( - not self.version.isascii() or not self.version.isdigit() or int(self.version) <= 0 - ): - raise ValueError("version must be a concrete positive integer string.") + _validate_registry_selector_values(self) return self @@ -187,36 +182,7 @@ def _config_issues(config: LocalWorkflowConfig) -> list[PreflightIssue]: "Choose local or databricks; use the separate Spark batch runner for Spark inference.", ) ) - if config.source.kind == "uc_table": - if ( - not config.source.table - or ( - config.source.read_mode == "snapshot" - and (config.source.version is None or config.source.version < 0) - ) - or (config.source.read_mode == "incremental" and config.source.version is not None) - ): - issues.append( - PreflightIssue( - "source_unbounded", - "source", - "Snapshot reads need a fixed nonnegative version; incremental reads derive it.", - "Set a version for snapshot reads or omit it for incremental reads.", - ) - ) - elif ( - config.source.table is not None - or config.source.version is not None - or config.source.read_mode != "snapshot" - ): - issues.append( - PreflightIssue( - "source_conflict", - "source", - "A caller frame cannot also select a UC table or version.", - "Remove table and version from caller_frame input.", - ) - ) + _collect_source_issues(config, issues) if config.sink.kind == "uc_delta": if config.runtime != "databricks": issues.append( @@ -236,28 +202,7 @@ def _config_issues(config: LocalWorkflowConfig) -> list[PreflightIssue]: "Choose an existing UC source table and concrete Delta version.", ) ) - try: - if config.sink.table is None or len(config.sink.table.split(".")) != 3: - raise ValueError("A three-part UC target is required.") - table_name(config.sink.table) - except ValueError: - issues.append( - PreflightIssue( - "sink_invalid_target", - "sink", - "UC Delta publication requires a three-part target table.", - "Specify an existing catalog.schema.table target.", - ) - ) - if config.sink.table and config.sink.table.lower() == (config.source.table or "").lower(): - issues.append( - PreflightIssue( - "sink_source_conflict", - "sink", - "Source and target tables must be different.", - "Choose a separate prediction target table.", - ) - ) + _collect_target_issues(config, issues) elif config.sink.table is not None: issues.append( PreflightIssue( @@ -287,29 +232,7 @@ def preflight_local( raise TypeError("config must be a LocalWorkflowConfig.") issues = _config_issues(config) remote_checked = resolved is not None - if config.model.name is not None and resolved is None: - issues.append( - PreflightIssue( - "model_unresolved", - "model", - "Registry identity and artifact metadata have not been checked.", - "Call prepare_local_workflow to resolve the alias once and load its pinned version.", - ) - ) - if resolved is not None and ( - config.model.name != resolved.name - or (config.model.version is not None and config.model.version != resolved.version) - or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" - ): - issues.append( - PreflightIssue( - "model_reference_mismatch", - "model", - "Resolved model differs from the selected concrete identity.", - "Resolve the configured name and selector again before this job.", - "remote", - ) - ) + _collect_reference_issues(config, resolved, issues) if artifact is None: issues.append( PreflightIssue( @@ -321,63 +244,7 @@ def preflight_local( ) return PreflightResult(tuple(issues), remote_checked) if config.model.kind == "local_pipeline" and isinstance(artifact, LocalPipelineArtifact): - manifest = artifact.manifest - digest = manifest.pipeline_sha256 - feature_order = manifest.feature_columns - label = "float64" if manifest.task == "regression" else label_dtype(manifest.classes) - output = ( - ColumnSpec(name="prediction", dtype=label), - *( - tuple( - ColumnSpec(name=f"probability_{i}", dtype="float64") - for i in range(len(manifest.classes)) - ) - if manifest.task == "classification" and manifest.classification_probabilities - else () - ), - ) - if config.engine != manifest.fitted_engine: - issues.append( - PreflightIssue( - "engine_mismatch", - "runtime", - "Selected engine differs from the fitted local pipeline.", - f"Choose engine='{manifest.fitted_engine}' or refit the pipeline.", - ) - ) - if manifest.execution_scope != "whole_frame_local": - issues.append( - PreflightIssue( - "scope_unsupported", - "model", - "Local package is not eligible for whole-frame local scoring.", - "Use a package fitted for whole_frame_local.", - ) - ) - if artifact.pipeline.preprocessing_steps != artifact.pipeline.feature_engineer.steps_config: - issues.append( - PreflightIssue( - "node_contract_mismatch", - "node", - "Pipeline FE configuration differs from its fitted transformer.", - "Reload the original fitted artifact instead of changing its steps.", - ) - ) - estimator = artifact.pipeline.model_estimator - if estimator is None or estimator.model is None: - actual_model_class = None - else: - model = estimator._unwrap_tuned_model() - actual_model_class = f"{type(model).__module__}.{type(model).__qualname__}" - if actual_model_class != manifest.model_class: - issues.append( - PreflightIssue( - "model_contract_mismatch", - "model", - "Artifact model class differs from the fitted estimator.", - "Reload a complete fitted artifact without changing its metadata.", - ) - ) + digest, feature_order, output = _local_pipeline_metadata(config, artifact, issues) elif config.model.kind == "portable_bundle" and isinstance(artifact, InferenceBundle): manifest = artifact.manifest digest = artifact.semantic_digest @@ -403,22 +270,7 @@ def preflight_local( "remote", ) ) - if probe_frame is not None and not issues: - try: - _check_frame_budget(probe_frame, config.source) - if isinstance(artifact, LocalPipelineArtifact): - predict_local_pipeline(probe_frame, artifact) - else: - predict_local(probe_frame, artifact) - except (TypeError, ValueError, RuntimeError) as exc: - issues.append( - PreflightIssue( - "prediction_probe_failed", - "model", - str(exc), - "Fix the sample schema or fitted pipeline; replay a representative batch.", - ) - ) + _probe_prediction(probe_frame, config, artifact, issues) return PreflightResult( tuple(issues), remote_checked, @@ -476,21 +328,7 @@ def prepare_local_workflow( selection = config.model resolved = None if selection.path is not None: - path = Path(selection.path) - try: - artifact = ( - load_local_pipeline(path) - if selection.kind == "local_pipeline" - else load_bundle(path) - ) - except (OSError, ValueError) as exc: - issue = PreflightIssue( - "artifact_invalid", - "model", - str(exc), - "Select a trusted, complete artifact of the declared kind and compatible runtime.", - ) - raise PreflightError(PreflightResult((issue,), False)) from exc + artifact = _load_selected_path(selection, selection.path) else: from ..mlflow.registry import ( # noqa: PLC0415 - optional MLflow client boundary load_registered_bundle, @@ -517,17 +355,7 @@ def prepare_local_workflow( resolved, tracking_uri=selection.tracking_uri, registry_uri=selection.registry_uri ) except (RegistryError, OSError, ValueError) as exc: - if isinstance(exc, RegistryAccessError): - code, fix = ( - "registry_access_denied", - "Grant model read/EXECUTE to the job identity.", - ) - elif isinstance(exc, RegistryModelNotFoundError): - code, fix = "registry_model_missing", "Check the model name and alias or version." - elif isinstance(exc, RegistryDependencyError): - code, fix = "mlflow_unavailable", "Install the optional MLflow extra." - else: - code, fix = "registry_or_artifact_invalid", "Check the trusted package metadata." + code, fix = _registry_failure_help(exc) issue = PreflightIssue(code, "model", str(exc), fix, "remote") result = PreflightResult( (issue,), True, resolved.version if resolved is not None else None @@ -537,3 +365,249 @@ def prepare_local_workflow( if not result.ready: raise PreflightError(result) return PreparedLocalWorkflow(config, artifact, result) + + +def _validate_registry_selector_values(selection: ModelSelection) -> None: + """Validate alias text and a concrete positive version after selector cardinality.""" + if selection.alias is not None and not selection.alias.strip(): + raise ValueError("alias must be non-empty.") + if selection.version is not None and ( + not selection.version.isascii() + or not selection.version.isdigit() + or int(selection.version) <= 0 + ): + raise ValueError("version must be a concrete positive integer string.") + + +def _collect_source_issues(config: LocalWorkflowConfig, issues: list[PreflightIssue]) -> None: + """Append source selection issues before sink validation.""" + if config.source.kind == "uc_table": + _collect_uc_source_issues(config, issues) + elif ( + config.source.table is not None + or config.source.version is not None + or config.source.read_mode != "snapshot" + ): + issues.append( + PreflightIssue( + "source_conflict", + "source", + "A caller frame cannot also select a UC table or version.", + "Remove table and version from caller_frame input.", + ) + ) + + +def _collect_target_issues(config: LocalWorkflowConfig, issues: list[PreflightIssue]) -> None: + """Check the target name and reject source-target collisions.""" + try: + if config.sink.table is None or len(config.sink.table.split(".")) != 3: + raise ValueError("A three-part UC target is required.") + table_name(config.sink.table) + except ValueError: + issues.append( + PreflightIssue( + "sink_invalid_target", + "sink", + "UC Delta publication requires a three-part target table.", + "Specify an existing catalog.schema.table target.", + ) + ) + if config.sink.table and config.sink.table.lower() == (config.source.table or "").lower(): + issues.append( + PreflightIssue( + "sink_source_conflict", + "sink", + "Source and target tables must be different.", + "Choose a separate prediction target table.", + ) + ) + + +def _collect_reference_issues( + config: LocalWorkflowConfig, resolved: ResolvedModel | None, issues: list[PreflightIssue] +) -> None: + """Append unresolved or mismatched registry identity issues before artifact checks.""" + if config.model.name is not None and resolved is None: + issues.append( + PreflightIssue( + "model_unresolved", + "model", + "Registry identity and artifact metadata have not been checked.", + "Call prepare_local_workflow to resolve the alias once and load its pinned version.", + ) + ) + if resolved is not None and ( + config.model.name != resolved.name + or (config.model.version is not None and config.model.version != resolved.version) + or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" + ): + issues.append( + PreflightIssue( + "model_reference_mismatch", + "model", + "Resolved model differs from the selected concrete identity.", + "Resolve the configured name and selector again before this job.", + "remote", + ) + ) + + +def _local_pipeline_metadata( + config: LocalWorkflowConfig, artifact: LocalPipelineArtifact, issues: list[PreflightIssue] +) -> tuple[str, tuple[str, ...], tuple[ColumnSpec, ...]]: + """Check local fitted contracts and return their prediction metadata.""" + manifest = artifact.manifest + digest = manifest.pipeline_sha256 + feature_order = manifest.feature_columns + output = _local_output_schema(artifact) + if config.engine != manifest.fitted_engine: + issues.append( + PreflightIssue( + "engine_mismatch", + "runtime", + "Selected engine differs from the fitted local pipeline.", + f"Choose engine='{manifest.fitted_engine}' or refit the pipeline.", + ) + ) + if manifest.execution_scope != "whole_frame_local": + issues.append( + PreflightIssue( + "scope_unsupported", + "model", + "Local package is not eligible for whole-frame local scoring.", + "Use a package fitted for whole_frame_local.", + ) + ) + if artifact.pipeline.preprocessing_steps != artifact.pipeline.feature_engineer.steps_config: + issues.append( + PreflightIssue( + "node_contract_mismatch", + "node", + "Pipeline FE configuration differs from its fitted transformer.", + "Reload the original fitted artifact instead of changing its steps.", + ) + ) + _collect_estimator_issues(artifact, issues) + + return digest, feature_order, output + + +def _local_output_schema(artifact: LocalPipelineArtifact) -> tuple[ColumnSpec, ...]: + """Derive ordered prediction columns from the saved task and classes.""" + manifest = artifact.manifest + label = "float64" if manifest.task == "regression" else label_dtype(manifest.classes) + output = ( + ColumnSpec(name="prediction", dtype=label), + *( + tuple( + ColumnSpec(name=f"probability_{i}", dtype="float64") + for i in range(len(manifest.classes)) + ) + if manifest.task == "classification" and manifest.classification_probabilities + else () + ), + ) + return output + + +def _collect_estimator_issues( + artifact: LocalPipelineArtifact, issues: list[PreflightIssue] +) -> None: + """Check the fitted estimator class without changing or unwrapping absent models.""" + estimator = artifact.pipeline.model_estimator + if estimator is None or estimator.model is None: + actual_model_class = None + else: + model = estimator._unwrap_tuned_model() + actual_model_class = f"{type(model).__module__}.{type(model).__qualname__}" + if actual_model_class != artifact.manifest.model_class: + issues.append( + PreflightIssue( + "model_contract_mismatch", + "model", + "Artifact model class differs from the fitted estimator.", + "Reload a complete fitted artifact without changing its metadata.", + ) + ) + + +def _registry_failure_help(exc: Exception) -> tuple[str, str]: + """Map registry failures to their stable preflight code and repair.""" + if isinstance(exc, RegistryAccessError): + code, fix = ( + "registry_access_denied", + "Grant model read/EXECUTE to the job identity.", + ) + elif isinstance(exc, RegistryModelNotFoundError): + code, fix = "registry_model_missing", "Check the model name and alias or version." + elif isinstance(exc, RegistryDependencyError): + code, fix = "mlflow_unavailable", "Install the optional MLflow extra." + else: + code, fix = "registry_or_artifact_invalid", "Check the trusted package metadata." + return code, fix + + +def _probe_prediction( + probe_frame: pd.DataFrame | pl.DataFrame | None, + config: LocalWorkflowConfig, + artifact: LocalPipelineArtifact | InferenceBundle, + issues: list[PreflightIssue], +) -> None: + """Exercise an optional bounded prediction only after all contract checks pass.""" + if probe_frame is not None and not issues: + try: + _check_frame_budget(probe_frame, config.source) + if isinstance(artifact, LocalPipelineArtifact): + predict_local_pipeline(probe_frame, artifact) + else: + predict_local(probe_frame, artifact) + except (TypeError, ValueError, RuntimeError) as exc: + issues.append( + PreflightIssue( + "prediction_probe_failed", + "model", + str(exc), + "Fix the sample schema or fitted pipeline; replay a representative batch.", + ) + ) + + +def _load_selected_path( + selection: ModelSelection, selected_path: str +) -> LocalPipelineArtifact | InferenceBundle: + """Load the selected trusted local artifact and translate invalid package errors.""" + path = Path(selected_path) + try: + artifact = ( + load_local_pipeline(path) if selection.kind == "local_pipeline" else load_bundle(path) + ) + except (OSError, ValueError) as exc: + issue = PreflightIssue( + "artifact_invalid", + "model", + str(exc), + "Select a trusted, complete artifact of the declared kind and compatible runtime.", + ) + raise PreflightError(PreflightResult((issue,), False)) from exc + return artifact + + +def _collect_uc_source_issues(config: LocalWorkflowConfig, issues: list[PreflightIssue]) -> None: + """Check pinned snapshot or automatically selected incremental source settings.""" + if ( + not config.source.table + or ( + config.source.read_mode == "snapshot" + and (config.source.version is None or config.source.version < 0) + ) + or (config.source.read_mode == "incremental" and config.source.version is not None) + ): + issues.append( + PreflightIssue( + "source_unbounded", + "source", + "Snapshot reads need a fixed nonnegative version; incremental reads derive it.", + "Set a version for snapshot reads or omit it for incremental reads.", + ) + ) diff --git a/skyulf-core/skyulf/integrations/databricks/local_search.py b/skyulf-core/skyulf/integrations/databricks/local_search.py index eb4da100e..0ced478dd 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_search.py +++ b/skyulf-core/skyulf/integrations/databricks/local_search.py @@ -57,21 +57,31 @@ def base_model_config(pipeline: dict[str, Any]) -> dict[str, Any]: return selected +def _validate_axis_values(values: list[Any]) -> None: + """Reject non-scalar or nonfinite candidates before JSON encoding.""" + for value in values: + if value is not None and type(value) not in {bool, str, int, float}: + raise ValueError("search_space candidates must be finite JSON scalars.") + if type(value) in {int, float} and not math.isfinite(value): + raise ValueError("search_space candidates must be finite JSON scalars.") + + +def _validate_axis(key: Any, values: Any) -> None: + """Check an axis name and candidate bounds without implicit coercion.""" + if not isinstance(key, str) or not key or not isinstance(values, list) or not values: + raise ValueError("Each search_space axis needs a name and nonempty candidate list.") + if len(values) > _MAX_CANDIDATES_PER_AXIS: + raise ValueError("search_space has too many candidates in one axis.") + _validate_axis_values(values) + + def _bounded_space(space: Any) -> dict[str, list[Any]]: """Accept small finite JSON scalar candidate lists without implicit coercion.""" if not isinstance(space, dict) or len(space) > _MAX_AXES: raise ValueError(f"search_space must be an object with at most {_MAX_AXES} axes.") checked: dict[str, list[Any]] = {} for key, values in space.items(): - if not isinstance(key, str) or not key or not isinstance(values, list) or not values: - raise ValueError("Each search_space axis needs a name and nonempty candidate list.") - if len(values) > _MAX_CANDIDATES_PER_AXIS: - raise ValueError("search_space has too many candidates in one axis.") - for value in values: - if value is not None and type(value) not in {bool, str, int, float}: - raise ValueError("search_space candidates must be finite JSON scalars.") - if type(value) in {int, float} and not math.isfinite(value): - raise ValueError("search_space candidates must be finite JSON scalars.") + _validate_axis(key, values) checked[key] = values if len(json.dumps(checked, allow_nan=False).encode("utf-8")) > _MAX_SEARCH_BYTES: raise ValueError("search_space exceeds the JSON size limit.") @@ -167,7 +177,20 @@ def _prepare_selected_model( selected.setdefault("params", {}).setdefault("tune_base_models", True) prepare_ensemble_model(selected, calculator) calculator.prepare_tuning_params(selected) - if cv.method == "stratified_k_fold" and calculator.problem_type != "classification": + _bind_search_time(modeling, cv, calculator.problem_type, event_column) + steps = pipeline.get("preprocessing", []) + if any(step.get("transformer") in SPLITTER_STEP_TYPES for step in steps): + raise ValueError("Search owns the split; remove preprocessing splitter nodes.") + FeatureEngineerFoldAdapter(steps, target_column) + _bind_shared_cv(modeling, cv) + return selected, calculator + + +def _bind_search_time( + modeling: dict[str, Any], cv: "LocalCVSpec", problem_type: str, event_column: str | None +) -> None: + """Validate splitter compatibility and bind authoritative temporal metadata.""" + if cv.method == "stratified_k_fold" and problem_type != "classification": raise ValueError("Stratified CV requires a classification model.") if cv.method == "time_series_split" and (not cv.enabled or not event_column): raise ValueError("Time-series search requires enabled CV and an event_column.") @@ -178,10 +201,10 @@ def _prepare_selected_model( modeling["cv_time_column"] = event_column elif requested_time is not None: raise ValueError("cv_time_column is only used by time_series_split.") - steps = pipeline.get("preprocessing", []) - if any(step.get("transformer") in SPLITTER_STEP_TYPES for step in steps): - raise ValueError("Search owns the split; remove preprocessing splitter nodes.") - FeatureEngineerFoldAdapter(steps, target_column) + + +def _bind_shared_cv(modeling: dict[str, Any], cv: "LocalCVSpec") -> None: + """Reject wrapper overrides before copying the workflow's shared fold settings.""" shared = { "cv_enabled": cv.enabled, "cv_folds": cv.folds, @@ -197,7 +220,6 @@ def _prepare_selected_model( ): raise ValueError(f"Conflicting wrapper {name}; use the shared workflow CV setting.") modeling.update(shared) - return selected, calculator def _validate_strategy( @@ -213,6 +235,31 @@ def _validate_strategy( max_candidates = modeling.get("max_candidates", 1000) if type(max_candidates) is not int or not 1 <= max_candidates <= 10_000: raise ValueError("max_candidates must be an integer from 1 to 10000.") + _validate_strategy_options(modeling, strategy, calculator) + seed = _validate_search_execution(modeling) + _validate_metric(modeling.get("metric"), calculator.problem_type) + modeling.update( + strategy=strategy, n_trials=n_trials, max_candidates=max_candidates, random_state=seed + ) + return strategy, max_candidates + + +def _validate_search_execution(modeling: dict[str, Any]) -> int: + """Validate threshold, worker and seed controls before metric validation.""" + if modeling.get("tune_threshold", False) is not False: + raise ValueError("tune_threshold is not supported by this search.") + if modeling.get("n_jobs", 1) != 1 or type(modeling.get("n_jobs", 1)) is not int: + raise ValueError("n_jobs must be 1 to avoid nested parallel fits.") + seed = modeling.get("random_state", 42) + if type(seed) is not int or not 0 <= seed < 2**32: + raise ValueError("random_state must be an integer from 0 to 2**32 - 1.") + return seed + + +def _validate_strategy_options( + modeling: dict[str, Any], strategy: str, calculator: BaseModelCalculator +) -> None: + """Check strategy-specific time and scheduler options in request order.""" timeout = modeling.get("timeout") if timeout is not None and ( strategy != "optuna" @@ -227,30 +274,23 @@ def _validate_strategy( if strategy in {"halving_grid", "halving_random"}: _validate_halving_params(strategy_params, calculator) elif strategy == "optuna": - if set(strategy_params) - {"sampler", "pruner", "pruning"}: - raise ValueError("Unsupported optuna strategy_params.") - if strategy_params.get("sampler", "tpe") not in {"tpe", "random", "cmaes"}: - raise ValueError("optuna sampler must be tpe, random or cmaes.") - if strategy_params.get("pruner", "median") not in {"median", "hyperband", "none"}: - raise ValueError("optuna pruner must be median, hyperband or none.") - if "pruning" in strategy_params and type(strategy_params["pruning"]) is not bool: - raise ValueError("optuna pruning must be boolean.") - if not _optuna_available(): - raise ValueError("optuna strategy requires Optuna and its sklearn integration.") + _validate_optuna_params(strategy_params) elif strategy_params: raise ValueError("strategy_params are unsupported for grid and random search.") - if modeling.get("tune_threshold", False) is not False: - raise ValueError("tune_threshold is not supported by this search.") - if modeling.get("n_jobs", 1) != 1 or type(modeling.get("n_jobs", 1)) is not int: - raise ValueError("n_jobs must be 1 to avoid nested parallel fits.") - seed = modeling.get("random_state", 42) - if type(seed) is not int or not 0 <= seed < 2**32: - raise ValueError("random_state must be an integer from 0 to 2**32 - 1.") - _validate_metric(modeling.get("metric"), calculator.problem_type) - modeling.update( - strategy=strategy, n_trials=n_trials, max_candidates=max_candidates, random_state=seed - ) - return strategy, max_candidates + + +def _validate_optuna_params(strategy_params: dict[str, Any]) -> None: + """Validate Optuna choices and require the optional integration.""" + if set(strategy_params) - {"sampler", "pruner", "pruning"}: + raise ValueError("Unsupported optuna strategy_params.") + if strategy_params.get("sampler", "tpe") not in {"tpe", "random", "cmaes"}: + raise ValueError("optuna sampler must be tpe, random or cmaes.") + if strategy_params.get("pruner", "median") not in {"median", "hyperband", "none"}: + raise ValueError("optuna pruner must be median, hyperband or none.") + if "pruning" in strategy_params and type(strategy_params["pruning"]) is not bool: + raise ValueError("optuna pruning must be boolean.") + if not _optuna_available(): + raise ValueError("optuna strategy requires Optuna and its sklearn integration.") def _validate_halving_params(params: dict[str, Any], calculator: BaseModelCalculator) -> None: @@ -261,19 +301,36 @@ def _validate_halving_params(params: dict[str, Any], calculator: BaseModelCalcul if type(factor) is not int or not 2 <= factor <= 10: raise ValueError("halving factor must be an integer from 2 to 10.") resource = params.get("resource", "n_samples") + _normalize_halving_counts(params) + maximum = params.get("max_resources", "auto") + if maximum != "auto" and (type(maximum) is not int or maximum < 2 or maximum > 1_000_000): + raise ValueError("halving max_resources must be auto or a bounded positive integer.") + _validate_estimator_resource(resource, maximum, calculator) + _validate_minimum_resources(params, resource, maximum) + + +def _normalize_halving_counts(params: dict[str, Any]) -> None: + """Normalize the accepted decimal-string resource counts in place.""" for field in ("min_resources", "max_resources"): value = params.get(field) if isinstance(value, str) and value.isascii() and value.isdecimal(): params[field] = int(value) - maximum = params.get("max_resources", "auto") - if maximum != "auto" and (type(maximum) is not int or maximum < 2 or maximum > 1_000_000): - raise ValueError("halving max_resources must be auto or a bounded positive integer.") + + +def _validate_estimator_resource( + resource: Any, maximum: Any, calculator: BaseModelCalculator +) -> None: + """Require an explicit bound and a real estimator parameter for custom resources.""" if resource != "n_samples": if not isinstance(resource, str) or not resource or maximum == "auto": raise ValueError("Estimator resource requires an explicit max_resources integer.") estimator = instantiate_model(cast(Any, calculator).model_class, calculator.default_params) if resource not in estimator.get_params(deep=True): raise ValueError(f"Unknown halving estimator resource: {resource}.") + + +def _validate_minimum_resources(params: dict[str, Any], resource: Any, maximum: Any) -> None: + """Check the minimum resource policy against the previously validated maximum.""" minimum = params.get("min_resources", "exhaust") if minimum not in {"exhaust", "smallest"} and ( type(minimum) is not int or not 2 <= minimum <= 1_000_000 @@ -304,6 +361,22 @@ def _prepare_space( space = _bounded_space(raw_space) if automatic_space and strategy in {"halving_grid", "halving_random"}: space.pop(modeling.get("strategy_params", {}).get("resource", "n_samples"), None) + _merge_fixed_axes(space, selected, calculator, automatic_space) + merge_ensemble_fixed_space(space, selected, automatic=automatic_space) + space = _bounded_space(space) + _validate_grid_size(space, strategy, max_candidates) + _bind_estimator_workers(space, modeling, calculator, strategy) + _validate_parameter_names(calculator, space) + return space + + +def _merge_fixed_axes( + space: dict[str, list[Any]], + selected: dict[str, Any], + calculator: BaseModelCalculator, + automatic_space: bool, +) -> None: + """Preserve explicit fixed parameters and reject contradictory manual axes.""" fixed = selected.get("params", {}) _validate_single_worker(fixed) structural = ensemble_structural_keys(calculator) @@ -318,14 +391,25 @@ def _prepare_space( raise ValueError(f"Fixed base parameter conflicts with search_space: {name}.") if name not in structural: space[name] = [value] - merge_ensemble_fixed_space(space, selected, automatic=automatic_space) - space = _bounded_space(space) + + +def _validate_grid_size(space: dict[str, list[Any]], strategy: str, max_candidates: int) -> None: + """Bound exhaustive candidate combinations before estimator construction.""" if strategy in {"grid", "halving_grid"}: count = math.prod(len(values) for values in space.values()) if count > max_candidates: raise ValueError( f"Grid search_space has {count} candidates, above max_candidates={max_candidates}." ) + + +def _bind_estimator_workers( + space: dict[str, list[Any]], + modeling: dict[str, Any], + calculator: BaseModelCalculator, + strategy: str, +) -> None: + """Constrain estimator workers and keep halving resources out of search axes.""" estimator = instantiate_model(cast(Any, calculator).model_class, calculator.default_params) for name in estimator.get_params(deep=True): if name == "n_jobs" or name.endswith("__n_jobs"): @@ -336,13 +420,16 @@ def _prepare_space( raise ValueError( f"Halving resource {resource} cannot also be a fixed or searched parameter." ) + _validate_worker_axes(space) + + +def _validate_worker_axes(space: dict[str, list[Any]]) -> None: + """Reject non-single-worker values on every nested parallelism axis.""" for name, values in space.items(): if (name == "n_jobs" or name.endswith("__n_jobs")) and any( type(value) is not int or value != 1 for value in values ): raise ValueError("Estimator n_jobs search candidates must all be 1.") - _validate_parameter_names(calculator, space) - return space def prepare_search_pipeline( diff --git a/skyulf-core/skyulf/integrations/databricks/local_search_results.py b/skyulf-core/skyulf/integrations/databricks/local_search_results.py index 2bfe437ab..04361722e 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_search_results.py +++ b/skyulf-core/skyulf/integrations/databricks/local_search_results.py @@ -61,19 +61,8 @@ def _json_value(value: Any) -> Any: raise ValueError("Tuning evidence contains a non-JSON value.") -def tuning_evidence(artifact: LocalPipelineArtifact) -> dict[str, Any] | None: - """Return the fitted tuning result and effective search recipe as JSON-safe evidence.""" - config = artifact.pipeline.config - modeling = config.get("modeling", {}) - if modeling.get("type") != "hyperparameter_tuner": - return None - estimator = artifact.pipeline.model_estimator - fitted = estimator.model if estimator is not None else None - if not isinstance(fitted, tuple) or len(fitted) != 2 or not isinstance(fitted[1], TuningResult): - raise ValueError("Fitted search artifact lacks a Core TuningResult.") - result = fitted[1] - if not math.isfinite(result.best_score): - raise ValueError("Fitted search has no finite best score.") +def _trial_evidence(result: TuningResult) -> list[dict[str, Any]]: + """Normalize failed trial scores without allowing nonfinite JSON numbers.""" trials = [] for trial in result.trials: score = trial.get("score") @@ -89,6 +78,23 @@ def tuning_evidence(artifact: LocalPipelineArtifact) -> dict[str, Any] | None: "status": "completed" if finite else "failed", } ) + return trials + + +def tuning_evidence(artifact: LocalPipelineArtifact) -> dict[str, Any] | None: + """Return the fitted tuning result and effective search recipe as JSON-safe evidence.""" + config = artifact.pipeline.config + modeling = config.get("modeling", {}) + if modeling.get("type") != "hyperparameter_tuner": + return None + estimator = artifact.pipeline.model_estimator + fitted = estimator.model if estimator is not None else None + if not isinstance(fitted, tuple) or len(fitted) != 2 or not isinstance(fitted[1], TuningResult): + raise ValueError("Fitted search artifact lacks a Core TuningResult.") + result = fitted[1] + if not math.isfinite(result.best_score): + raise ValueError("Fitted search has no finite best score.") + trials = _trial_evidence(result) evidence = { "status": "completed", "modeling": _json_value(modeling), diff --git a/skyulf-core/skyulf/integrations/databricks/local_training_evidence.py b/skyulf-core/skyulf/integrations/databricks/local_training_evidence.py index 1151b0e87..6905f1042 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_training_evidence.py +++ b/skyulf-core/skyulf/integrations/databricks/local_training_evidence.py @@ -84,17 +84,7 @@ def _validate_population_counts(evidence: dict[str, Any], spec: Any) -> None: counts = evidence["filter_counts"] if not isinstance(counts, list) or len(counts) != len(spec.pre_split_steps): raise ValueError("Saved training filter evidence has invalid step counts.") - remaining = evidence["pre_filter_rows"] - for step, count in zip(spec.pre_split_steps, counts, strict=True): - if ( - count["name"] != step["name"] - or count["transformer"] != step["transformer"] - or count["input_rows"] != remaining - or count["excluded_rows"] < 0 - or count["output_rows"] != remaining - count["excluded_rows"] - ): - raise ValueError("Saved training filter evidence has inconsistent step counts.") - remaining = count["output_rows"] + remaining = _remaining_filter_population(evidence, spec, counts) if ( remaining != evidence["survivor_rows"] or remaining != evidence["training_rows"] + evidence["holdout_rows"] @@ -219,3 +209,19 @@ def load_candidate_evidence( if source_sha is not None and recipe != list(spec.pre_split_steps): raise ValueError("Saved project source recipe differs from training evidence.") return report, spec, engine, saved_filter_evidence + + +def _remaining_filter_population(evidence: dict[str, Any], spec: Any, counts: list[Any]) -> int: + """Verify ordered filter transitions and return their surviving population.""" + remaining = evidence["pre_filter_rows"] + for step, count in zip(spec.pre_split_steps, counts, strict=True): + if ( + count["name"] != step["name"] + or count["transformer"] != step["transformer"] + or count["input_rows"] != remaining + or count["excluded_rows"] < 0 + or count["output_rows"] != remaining - count["excluded_rows"] + ): + raise ValueError("Saved training filter evidence has inconsistent step counts.") + remaining = count["output_rows"] + return remaining diff --git a/skyulf-core/skyulf/integrations/databricks/local_workflow.py b/skyulf-core/skyulf/integrations/databricks/local_workflow.py index 0600b25e5..b7e8182b4 100644 --- a/skyulf-core/skyulf/integrations/databricks/local_workflow.py +++ b/skyulf-core/skyulf/integrations/databricks/local_workflow.py @@ -181,24 +181,28 @@ def resolve_target_config(config: dict[str, Any], bindings: dict[str, str]) -> d raise ValueError("Invalid resource_suffix for a Unity Catalog identifier.") resolved = config.copy() for name in _TABLE_FIELDS: - value = config[name] - if type(value) is not str: - raise ValueError(f"{name} must be a string.") - for key, replacement in bindings.items(): - value = value.replace("{" + key + "}", replacement) - if not _TABLE_NAME.fullmatch(value): - raise ValueError(f"{name} must resolve to a three-part UC name.") - if name in {"prediction_table", "model_name"}: - schema = "output_schema" if name == "prediction_table" else "metadata_schema" - expected = f"{bindings['catalog']}.{bindings[schema]}." - if not value.startswith(expected): - raise ValueError(f"{name} must use the active target's {schema}.") - if suffix and not value.endswith(suffix): - raise ValueError(f"{name} must include the active target's resource_suffix.") - resolved[name] = value + resolved[name] = _bind_target_name(name, config[name], bindings, suffix) return resolved +def _bind_target_name(name: str, value: Any, bindings: dict[str, str], suffix: str) -> str: + """Resolve one UC name and enforce the target's output ownership.""" + if type(value) is not str: + raise ValueError(f"{name} must be a string.") + for key, replacement in bindings.items(): + value = value.replace("{" + key + "}", replacement) + if not _TABLE_NAME.fullmatch(value): + raise ValueError(f"{name} must resolve to a three-part UC name.") + if name in {"prediction_table", "model_name"}: + schema = "output_schema" if name == "prediction_table" else "metadata_schema" + expected = f"{bindings['catalog']}.{bindings[schema]}." + if not value.startswith(expected): + raise ValueError(f"{name} must use the active target's {schema}.") + if suffix and not value.endswith(suffix): + raise ValueError(f"{name} must include the active target's resource_suffix.") + return value + + def _scoring_config(config: dict[str, Any]) -> LocalWorkflowConfig: """Bind the pinned local model and source for incremental scoring.""" return LocalWorkflowConfig( @@ -276,13 +280,39 @@ def _optional_boundary(config: dict[str, Any], field: str) -> datetime | None: raise ValueError(f"{field} must be an ISO timestamp with timezone.") from exc -def _training_window_mode(config: dict[str, Any]) -> str: - """Validate source selection independently of the random/temporal evaluation split.""" - mode = config.get("training_window_mode", "full_snapshot") - if mode not in ("full_snapshot", "fixed_window", "rolling_calendar"): - raise ValueError( - "training_window_mode must be full_snapshot, fixed_window or rolling_calendar." - ) +def _validate_rolling_window(config: dict[str, Any]) -> None: + """Validate calendar history, holdout duration and timezone in that order.""" + months = config.get("monthly_lookback_months") + minimum = 2 if config.get("split_strategy") == "temporal" else 1 + if type(months) is not int or not minimum <= months <= 120: + raise ValueError(f"monthly_lookback_months must be an integer from {minimum} to 120.") + if config.get("split_strategy") == "temporal": + holdout = config.get("holdout_months", 1) + if type(holdout) is not int or not 1 <= holdout < months: + raise ValueError( + "holdout_months must be an integer from 1 to monthly_lookback_months - 1." + ) + zone = config.get("window_timezone") + if not isinstance(zone, str) or not zone: + raise ValueError("Rolling-calendar selection requires window_timezone.") + try: + ZoneInfo(zone) + except ZoneInfoNotFoundError as exc: + raise ValueError("window_timezone must name an IANA timezone.") from exc + + +def _validate_result_lag(config: dict[str, Any]) -> None: + """Reject unavailable-result lag settings outside their active policy.""" + if config.get("filter_unavailable_results") is True: + lag = config.get("result_availability_lag_hours", 0) + if type(lag) is not int or not 0 <= lag <= 87600: + raise ValueError("result_availability_lag_hours must be an integer from 0 to 87600.") + elif config.get("result_availability_lag_hours") is not None: + raise ValueError("Inactive result filtering requires null result_availability_lag_hours.") + + +def _validate_window_event(config: dict[str, Any], mode: str) -> None: + """Require event columns only for time-based source selection.""" if mode == "full_snapshot": if ( config.get("event_column") is not None @@ -293,24 +323,18 @@ def _training_window_mode(config: dict[str, Any]) -> str: ) elif not config.get("event_column"): raise ValueError("Window selection requires an explicit event_column.") + + +def _training_window_mode(config: dict[str, Any]) -> str: + """Validate source selection independently of the random/temporal evaluation split.""" + mode = config.get("training_window_mode", "full_snapshot") + if mode not in ("full_snapshot", "fixed_window", "rolling_calendar"): + raise ValueError( + "training_window_mode must be full_snapshot, fixed_window or rolling_calendar." + ) + _validate_window_event(config, mode) if mode == "rolling_calendar": - months = config.get("monthly_lookback_months") - minimum = 2 if config.get("split_strategy") == "temporal" else 1 - if type(months) is not int or not minimum <= months <= 120: - raise ValueError(f"monthly_lookback_months must be an integer from {minimum} to 120.") - if config.get("split_strategy") == "temporal": - holdout = config.get("holdout_months", 1) - if type(holdout) is not int or not 1 <= holdout < months: - raise ValueError( - "holdout_months must be an integer from 1 to monthly_lookback_months - 1." - ) - zone = config.get("window_timezone") - if not isinstance(zone, str) or not zone: - raise ValueError("Rolling-calendar selection requires window_timezone.") - try: - ZoneInfo(zone) - except ZoneInfoNotFoundError as exc: - raise ValueError("window_timezone must name an IANA timezone.") from exc + _validate_rolling_window(config) elif ( config.get("monthly_lookback_months") is not None or config.get("window_timezone") is not None @@ -322,12 +346,7 @@ def _training_window_mode(config: dict[str, Any]) -> str: "holdout_months" ) is not None: raise ValueError("holdout_months must be null outside rolling temporal selection.") - if config.get("filter_unavailable_results") is True: - lag = config.get("result_availability_lag_hours", 0) - if type(lag) is not int or not 0 <= lag <= 87600: - raise ValueError("result_availability_lag_hours must be an integer from 0 to 87600.") - elif config.get("result_availability_lag_hours") is not None: - raise ValueError("Inactive result filtering requires null result_availability_lag_hours.") + _validate_result_lag(config) return mode @@ -482,6 +501,13 @@ def _automatic_promotion( expected_challenger_version=report.candidate_version, **options, ) + return _promote_staged_candidate(report, native, options, promote) + + +def _promote_staged_candidate( + report: Any, native: Any, options: dict[str, Any], promote: bool +) -> AliasChangeReceipt | None: + """Apply promotion policy after contender evidence has been staged.""" if not promote: return None if report.champion_version is None: @@ -604,6 +630,29 @@ def _run_scoring_action( return result +def _run_rollback_action( + config: dict[str, Any], + promotion_receipt: AliasChangeReceipt | None, + expected_champion_version: str | None, + tracking_uri: str, + registry_uri: str, +) -> AliasChangeReceipt: + """Validate rollback identity before attempting its alias transition.""" + if ( + not isinstance(promotion_receipt, AliasChangeReceipt) + or promotion_receipt.model_name != config["model_name"] + or not isinstance(expected_champion_version, str) + ): + raise ValueError("Rollback needs a receipt for the configured model and expected champion.") + return rollback_promotion( + promotion_receipt, + expected_current_version=expected_champion_version, + admission=ExclusiveAliasWriterAdmission(), + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + + def run_action( spark: Any, config: dict[str, Any], @@ -623,20 +672,8 @@ def run_action( registry_uri = config.get("registry_uri", "databricks-uc") selection, policy = _workflow_policies(config) if action == "rollback": - if ( - not isinstance(promotion_receipt, AliasChangeReceipt) - or promotion_receipt.model_name != config["model_name"] - or not isinstance(expected_champion_version, str) - ): - raise ValueError( - "Rollback needs a receipt for the configured model and expected champion." - ) - return rollback_promotion( - promotion_receipt, - expected_current_version=expected_champion_version, - admission=ExclusiveAliasWriterAdmission(), - tracking_uri=tracking_uri, - registry_uri=registry_uri, + return _run_rollback_action( + config, promotion_receipt, expected_champion_version, tracking_uri, registry_uri ) if action == "reject": return reject_local_candidate( diff --git a/skyulf-core/skyulf/integrations/databricks/prediction_output.py b/skyulf-core/skyulf/integrations/databricks/prediction_output.py index b0dd307c7..86c09f80a 100644 --- a/skyulf-core/skyulf/integrations/databricks/prediction_output.py +++ b/skyulf-core/skyulf/integrations/databricks/prediction_output.py @@ -65,14 +65,7 @@ def _activate_prediction_view(spark: Any, logical: str, generation: str) -> None f"AS SELECT * FROM {generation}" ).collect() return - active_columns = tuple( - (field.name, field.dataType.typeName()) for field in spark.table(logical).schema.fields - ) - candidate_columns = tuple( - (field.name, field.dataType.typeName()) for field in physical.schema.fields - ) - if active_columns != candidate_columns: - raise ValueError("New prediction generation differs from the active view schema.") + _validate_generation_schema(spark, logical, physical) definition = spark.sql(f"SHOW CREATE TABLE {logical}").first() if definition is not None: sql = definition["createtab_stmt"].casefold().replace("`", "") @@ -85,17 +78,7 @@ def _prediction_columns( config: dict[str, Any], prepared: Any, source: Any ) -> tuple[tuple[str, str, str], ...]: """Derive an exact Delta target schema from source keys and saved model outputs.""" - keys = tuple(config["record_key_columns"]) - inputs = tuple(prepared.artifact.manifest.input_columns) - if not keys or tuple(config["input_columns"]) != inputs: - raise ValueError("Configured keys or model inputs differ from the fitted model.") - names = (*keys, *inputs) - if any(not _IDENTIFIER.fullmatch(name) for name in names): - raise ValueError("Source keys and model inputs need simple column identifiers.") - if len({name.lower() for name in names}) != len(names): - raise ValueError("Source keys and model inputs must be distinct.") - if not set(names).issubset(source.columns): - raise ValueError("Scoring source lacks a row key or fitted model input column.") + keys = _prediction_source_keys(config, prepared, source) columns = [] for key in keys: kind = source.schema[key].dataType.typeName() @@ -136,26 +119,10 @@ def _generation_properties(config: dict[str, Any], prepared: Any) -> dict[str, s def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any) -> bool: """Preflight an existing source/model and create only a missing output table.""" - source_name = config["score_source_table"] - target_name = config["prediction_table"] - for name in (source_name, target_name, config["model_name"]): - if not _TABLE_NAME.fullmatch(name): - raise ValueError("Scoring needs valid three-part Unity Catalog names.") - if source_name == target_name: - raise ValueError("Prediction output must differ from the source table.") - if not spark.catalog.tableExists(source_name): - raise ValueError(f"Existing input source table is missing: {source_name}.") - if not prepared.preflight.ready: - raise ValueError("The pinned registered model failed Skyulf preflight.") + source_name, target_name = _validate_prediction_request(spark, config, prepared) source = spark.table(source_name) columns = _prediction_columns(config, prepared, source) - detail = spark.sql(f"DESCRIBE DETAIL {source_name}").first() - properties = detail["properties"] or {} - if not any( - key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" - for key, value in properties.items() - ): - raise ValueError("Scoring source must have Delta Change Data Feed enabled.") + _require_change_feed(spark, source_name) target_exists = spark.catalog.tableExists(target_name) generation = config.get("model_change_mode") == "full_rebuild" generation_properties = _generation_properties(config, prepared) if generation else {} @@ -172,21 +139,91 @@ def provision_prediction_table(spark: Any, config: dict[str, Any], prepared: Any ) _check_existing_table(spark, target_name, columns) if not target_exists: - if ( - source.select(*config["record_key_columns"], *config["input_columns"]) - .limit(config["max_rows"] + 1) - .count() - > config["max_rows"] - ): - raise ValueError("Initial scoring source exceeds the configured max_rows budget.") - definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) - table_properties = "" - if generation: - properties = ", ".join( - f"'{key}' = '{value}'" for key, value in generation_properties.items() - ) - table_properties = f" TBLPROPERTIES ({properties})" - spark.sql( - f"CREATE TABLE {target_name} ({definition}) USING DELTA{table_properties}" - ).collect() + _create_prediction_table( + spark, config, source, target_name, columns, generation, generation_properties + ) return not target_exists + + +def _validate_generation_schema(spark: Any, logical: str, physical: Any) -> None: + """Require a new generation to preserve the active prediction view schema.""" + active_columns = tuple( + (field.name, field.dataType.typeName()) for field in spark.table(logical).schema.fields + ) + candidate_columns = tuple( + (field.name, field.dataType.typeName()) for field in physical.schema.fields + ) + if active_columns != candidate_columns: + raise ValueError("New prediction generation differs from the active view schema.") + + +def _prediction_source_keys(config: dict[str, Any], prepared: Any, source: Any) -> tuple[str, ...]: + """Validate source key identifiers and saved input column membership.""" + keys = tuple(config["record_key_columns"]) + inputs = tuple(prepared.artifact.manifest.input_columns) + if not keys or tuple(config["input_columns"]) != inputs: + raise ValueError("Configured keys or model inputs differ from the fitted model.") + names = (*keys, *inputs) + if any(not _IDENTIFIER.fullmatch(name) for name in names): + raise ValueError("Source keys and model inputs need simple column identifiers.") + if len({name.lower() for name in names}) != len(names): + raise ValueError("Source keys and model inputs must be distinct.") + if not set(names).issubset(source.columns): + raise ValueError("Scoring source lacks a row key or fitted model input column.") + return keys + + +def _validate_prediction_request( + spark: Any, config: dict[str, Any], prepared: Any +) -> tuple[str, str]: + """Check existing source, target identity and model readiness before provisioning.""" + source_name = config["score_source_table"] + target_name = config["prediction_table"] + for name in (source_name, target_name, config["model_name"]): + if not _TABLE_NAME.fullmatch(name): + raise ValueError("Scoring needs valid three-part Unity Catalog names.") + if source_name == target_name: + raise ValueError("Prediction output must differ from the source table.") + if not spark.catalog.tableExists(source_name): + raise ValueError(f"Existing input source table is missing: {source_name}.") + if not prepared.preflight.ready: + raise ValueError("The pinned registered model failed Skyulf preflight.") + return source_name, target_name + + +def _require_change_feed(spark: Any, source_name: str) -> None: + """Require enabled Delta change data feed before provisioning prediction output.""" + detail = spark.sql(f"DESCRIBE DETAIL {source_name}").first() + properties = detail["properties"] or {} + if not any( + key.lower() == "delta.enablechangedatafeed" and str(value).lower() == "true" + for key, value in properties.items() + ): + raise ValueError("Scoring source must have Delta Change Data Feed enabled.") + + +def _create_prediction_table( + spark: Any, + config: dict[str, Any], + source: Any, + target_name: str, + columns: tuple[tuple[str, str, str], ...], + generation: bool, + generation_properties: dict[str, str], +) -> None: + """Check bootstrap size and create a target with the pinned generation properties.""" + if ( + source.select(*config["record_key_columns"], *config["input_columns"]) + .limit(config["max_rows"] + 1) + .count() + > config["max_rows"] + ): + raise ValueError("Initial scoring source exceeds the configured max_rows budget.") + definition = ", ".join(f"{name} {sql_type}" for name, _, sql_type in columns) + table_properties = "" + if generation: + properties = ", ".join( + f"'{key}' = '{value}'" for key, value in generation_properties.items() + ) + table_properties = f" TBLPROPERTIES ({properties})" + spark.sql(f"CREATE TABLE {target_name} ({definition}) USING DELTA{table_properties}").collect() diff --git a/skyulf-core/skyulf/integrations/databricks/project.py b/skyulf-core/skyulf/integrations/databricks/project.py index 04c2a9031..9f9d5294b 100644 --- a/skyulf-core/skyulf/integrations/databricks/project.py +++ b/skyulf-core/skyulf/integrations/databricks/project.py @@ -19,9 +19,7 @@ def _strict_json_value(value: Any) -> Any: """Copy only finite JSON values from trusted project hook output.""" if type(value) is dict: - if any(type(key) is not str for key in value): - raise ValueError("ensemble.py must return a JSON object with string keys.") - return {key: _strict_json_value(item) for key, item in value.items()} + return _strict_json_object(value) if type(value) is list: return [_strict_json_value(item) for item in value] if value is None or type(value) in {str, bool, int}: @@ -31,6 +29,13 @@ def _strict_json_value(value: Any) -> Any: raise ValueError("ensemble.py must return finite JSON values.") +def _strict_json_object(value: dict[Any, Any]) -> dict[str, Any]: + """Copy nested hook mappings while rejecting non-string JSON keys.""" + if any(type(key) is not str for key in value): + raise ValueError("ensemble.py must return a JSON object with string keys.") + return {key: _strict_json_value(item) for key, item in value.items()} + + def _load_ensemble_hook(result: dict[str, Any], preprocessing_path: Path) -> None: """Apply an optional ensemble recipe before resolving any tuning override.""" modeling = result["pipeline"].get("modeling", {}) diff --git a/skyulf-core/skyulf/integrations/databricks/training_dates.py b/skyulf-core/skyulf/integrations/databricks/training_dates.py index 254c85e9c..5dfc6f391 100644 --- a/skyulf-core/skyulf/integrations/databricks/training_dates.py +++ b/skyulf-core/skyulf/integrations/databricks/training_dates.py @@ -56,22 +56,7 @@ def _validate_format(self) -> None: """Limit parsing to full numeric calendar dates and explicit clock/offset fields.""" if not isinstance(self.format, str) or not self.format: raise ValueError("format must be a nonempty explicit numeric date format.") - tokens = re.findall(r"%.", self.format) - literals = re.sub(r"%.", "", self.format) - if ( - not {"%Y", "%m", "%d"}.issubset(tokens) - or len(tokens) != len(set(tokens)) - or any(token not in _TOKENS for token in tokens) - or re.search(r"[^ /:.,T+\-]", literals) - ): - raise ValueError("format requires %Y, %m, %d and supported numeric directives.") - timed = "%H" in tokens - if ( - ("%M" in tokens) != timed - or any(token in tokens and not timed for token in ("%S", "%f", "%z")) - or ("%f" in tokens and "%S" not in tokens) - ): - raise ValueError("format time requires %H and %M; fractions require %S.") + tokens, timed = _format_directives(self.format) if not timed and self.date_only != "midnight": raise ValueError("Date-only format requires date_only=midnight.") if "%z" in tokens and self.timezone is not None: @@ -111,34 +96,11 @@ def parse_training_date( value: Any, spec: TrainingDateSpec, *, allow_null: bool = False ) -> datetime | None: """Normalize one declared source value to UTC without inferring a format or zone.""" - if ( - value is None - or value is pd.NaT - or value is pd.NA - or (isinstance(value, float) and pd.isna(value)) - ): + if _null_training_date(value): if allow_null: return None raise ValueError("Training event time must not be null.") - if isinstance(value, str): - if spec.format is None: - raise ValueError("String training dates require an explicit format.") - pattern = re.escape(spec.format) - for token, expression in _TOKENS.items(): - pattern = pattern.replace(re.escape(token), expression) - if not re.fullmatch(pattern, value): - raise ValueError("Training date does not match its declared format.") - value = datetime.strptime(value, spec.format) - elif isinstance(value, date) and not isinstance(value, datetime): - if spec.date_only != "midnight": - raise ValueError("Date-only source requires date_only=midnight and timezone.") - value = datetime.combine(value, time.min) - if not isinstance(value, datetime): - raise ValueError("Training dates must be datetime, date or explicitly formatted strings.") - if isinstance(value, pd.Timestamp): - if value.nanosecond: - raise ValueError("Training dates support microsecond precision, not nanoseconds.") - value = value.to_pydatetime() + value = _source_datetime(value, spec) if value.tzinfo is not None and value.utcoffset() is not None: normalized = value.astimezone(UTC) if normalized.astimezone(value.tzinfo).replace(tzinfo=None) != value.replace(tzinfo=None): @@ -182,40 +144,9 @@ def normalize_training_dates( F = import_module("pyspark.sql.functions") types = import_module("pyspark.sql.types") - expressions = {} - for name, spec, nullable in ( - (event_column, event_spec, False), - (result_column, result_spec, True), - ): - if name is None: - continue - dtype = source.schema[name].dataType - value = F.col(name) - if isinstance(dtype, types.TimestampType): - if spec != TrainingDateSpec(): - raise ValueError(f"{name}: native Spark timestamps require default parsing rules.") - micros = F.expr(f"unix_micros(`{name}`)") - error = F.lit(None).cast("string") - if not nullable: - error = F.when(value.isNull(), F.lit("Training event time must not be null.")) - expressions[name] = F.struct(micros.alias("micros"), error.alias("error")) - continue - if isinstance(dtype, types.StringType): - if spec.format is None: - raise ValueError(f"{name}: string training dates require an explicit format.") - elif isinstance(dtype, types.DateType): - if spec.date_only != "midnight" or spec.timezone is None or spec.format is not None: - raise ValueError( - f"{name}: native dates require date_only=midnight, timezone and no format." - ) - elif isinstance(dtype, types.TimestampNTZType): - if spec.timezone is None or spec.format is not None or spec.date_only != "reject": - raise ValueError(f"{name}: native local timestamps require timezone only.") - else: - raise ValueError(f"{name}: unsupported training date source type.") - expressions[name] = F.udf( - _date_transport_parser(spec, nullable), "struct" - )(value) + expressions = _date_expressions( + source, event_column, result_column, event_spec, result_spec, F, types + ) normalized = source.select( *( expressions[name].alias(name) if name in expressions else F.col(name) @@ -250,3 +181,131 @@ def parse(value: Any) -> tuple[int | None, str | None]: return None, str(exc) return parse + + +def _format_directives(format_string: str) -> tuple[list[str], bool]: + """Validate supported calendar and clock directives before timezone policy.""" + tokens = re.findall(r"%.", format_string) + literals = re.sub(r"%.", "", format_string) + if ( + not {"%Y", "%m", "%d"}.issubset(tokens) + or len(tokens) != len(set(tokens)) + or any(token not in _TOKENS for token in tokens) + or re.search(r"[^ /:.,T+\-]", literals) + ): + raise ValueError("format requires %Y, %m, %d and supported numeric directives.") + timed = _validate_clock_directives(tokens) + return tokens, timed + + +def _source_datetime(value: Any, spec: TrainingDateSpec) -> datetime: + """Parse declared calendar values and precision before timezone conversion.""" + if isinstance(value, str): + if spec.format is None: + raise ValueError("String training dates require an explicit format.") + pattern = re.escape(spec.format) + for token, expression in _TOKENS.items(): + pattern = pattern.replace(re.escape(token), expression) + if not re.fullmatch(pattern, value): + raise ValueError("Training date does not match its declared format.") + value = datetime.strptime(value, spec.format) + elif isinstance(value, date) and not isinstance(value, datetime): + if spec.date_only != "midnight": + raise ValueError("Date-only source requires date_only=midnight and timezone.") + value = datetime.combine(value, time.min) + if not isinstance(value, datetime): + raise ValueError("Training dates must be datetime, date or explicitly formatted strings.") + value = _microsecond_datetime(value) + return value + + +def _null_training_date(value: Any) -> bool: + """Recognize missing dates without applying pandas null checks to arbitrary objects.""" + return ( + value is None + or value is pd.NaT + or value is pd.NA + or (isinstance(value, float) and pd.isna(value)) + ) + + +def _date_expression( + name: str, dtype: Any, spec: TrainingDateSpec, nullable: bool, F: Any, types: Any +) -> Any: + """Build one validated Spark date transport expression for its native source type.""" + value = F.col(name) + if isinstance(dtype, types.TimestampType): + if spec != TrainingDateSpec(): + raise ValueError(f"{name}: native Spark timestamps require default parsing rules.") + micros = F.expr(f"unix_micros(`{name}`)") + error = F.lit(None).cast("string") + if not nullable: + error = F.when(value.isNull(), F.lit("Training event time must not be null.")) + return F.struct(micros.alias("micros"), error.alias("error")) + _validate_native_date_type(name, dtype, spec, types) + return F.udf(_date_transport_parser(spec, nullable), "struct")(value) + + +def _validate_native_date_type(name: str, dtype: Any, spec: TrainingDateSpec, types: Any) -> None: + """Require parsing rules appropriate for strings, dates or native local timestamps.""" + if isinstance(dtype, types.StringType): + if spec.format is None: + raise ValueError(f"{name}: string training dates require an explicit format.") + elif isinstance(dtype, types.DateType): + _validate_native_calendar(name, spec) + elif isinstance(dtype, types.TimestampNTZType): + if spec.timezone is None or spec.format is not None or spec.date_only != "reject": + raise ValueError(f"{name}: native local timestamps require timezone only.") + else: + raise ValueError(f"{name}: unsupported training date source type.") + + +def _validate_clock_directives(tokens: list[str]) -> bool: + """Require complete clocks and seconds whenever fractional seconds are declared.""" + timed = "%H" in tokens + if ( + ("%M" in tokens) != timed + or any(token in tokens and not timed for token in ("%S", "%f", "%z")) + or ("%f" in tokens and "%S" not in tokens) + ): + raise ValueError("format time requires %H and %M; fractions require %S.") + return timed + + +def _microsecond_datetime(value: datetime) -> datetime: + """Reject pandas timestamps whose nanoseconds would be lost in Python transport.""" + if isinstance(value, pd.Timestamp): + if value.nanosecond: + raise ValueError("Training dates support microsecond precision, not nanoseconds.") + value = value.to_pydatetime() + return value + + +def _date_expressions( + source: Any, + event_column: str | None, + result_column: str | None, + event_spec: TrainingDateSpec, + result_spec: TrainingDateSpec, + F: Any, + types: Any, +) -> dict[str, Any]: + """Build event and nullable result expressions in their validation order.""" + expressions = {} + for name, spec, nullable in ( + (event_column, event_spec, False), + (result_column, result_spec, True), + ): + if name is None: + continue + dtype = source.schema[name].dataType + expressions[name] = _date_expression(name, dtype, spec, nullable, F, types) + return expressions + + +def _validate_native_calendar(name: str, spec: TrainingDateSpec) -> None: + """Require explicit midnight and timezone semantics for native calendar dates.""" + if spec.date_only != "midnight" or spec.timezone is None or spec.format is not None: + raise ValueError( + f"{name}: native dates require date_only=midnight, timezone and no format." + ) diff --git a/skyulf-core/skyulf/integrations/databricks/workflow_config.py b/skyulf-core/skyulf/integrations/databricks/workflow_config.py index 869297e34..a3b2a11e1 100644 --- a/skyulf-core/skyulf/integrations/databricks/workflow_config.py +++ b/skyulf-core/skyulf/integrations/databricks/workflow_config.py @@ -103,6 +103,11 @@ def _columns(config: dict[str, Any]) -> None: for key in ("event_column", "result_available_at_column") if config.get(key) is not None ) + _validate_column_roles(names, config["record_key_columns"]) + + +def _validate_column_roles(names: list[Any], record_key_columns: list[str]) -> None: + """Reject ambiguous or reserved source column roles in their declared order.""" checked: list[str] = [] for name in names: if not isinstance(name, str) or not _IDENTIFIER.fullmatch(name): @@ -110,7 +115,7 @@ def _columns(config: dict[str, Any]) -> None: checked.append(name) if len({name.casefold() for name in checked}) != len(checked): raise ValueError("Key, input, target, event and label columns must be distinct.") - if any(name.lower() in PREDICTION_METADATA_COLUMNS for name in config["record_key_columns"]): + if any(name.lower() in PREDICTION_METADATA_COLUMNS for name in record_key_columns): raise ValueError("record_key_columns contain reserved prediction metadata names.") if any( name.lower() in {"_change_type", "_commit_version", "_commit_timestamp"} for name in checked @@ -178,8 +183,8 @@ def _validate_workflow_sources(config: dict[str, Any]) -> None: training_date_spec(config.get(field) if config.get(field) is not None else {}) -def _validate_workflow_model_selection(config: dict[str, Any], selection: str) -> None: - """Require valid pins, risk metadata and registry selection settings.""" +def _validate_champion_metadata(config: dict[str, Any]) -> None: + """Validate optional champion pins and risk metadata before scoring selection.""" champion = config.get("champion_version") if champion is not None and ( not isinstance(champion, str) or not re.fullmatch(r"[1-9][0-9]*", champion) @@ -188,6 +193,11 @@ def _validate_workflow_model_selection(config: dict[str, Any], selection: str) - risk = config.get("risk_category") if risk is not None and (not isinstance(risk, str) or len(risk.encode("utf-8")) > 256): raise ValueError("risk_category must be text of at most 256 UTF-8 bytes.") + + +def _validate_workflow_model_selection(config: dict[str, Any], selection: str) -> None: + """Require valid pins, risk metadata and registry selection settings.""" + _validate_champion_metadata(config) version = config.get("model_version") if version is not None and ( not isinstance(version, str) or not re.fullmatch(r"[1-9][0-9]*", version) @@ -404,6 +414,17 @@ def _preview_search(checked: dict[str, Any], cv: LocalCVSpec) -> list[str]: f"Search random_state={effective.get('random_state', 42)} | " f"cv_random_state={cv.random_state} (independent seeds).", ] + _append_search_cv_preview(lines, cv) + if strategy == "optuna" and effective.get("timeout") is not None: + lines.append( + f"Optuna timeout: {effective['timeout']} seconds is a soft study limit; " + "it does not interrupt an in-flight fit." + ) + return lines + + +def _append_search_cv_preview(lines: list[str], cv: LocalCVSpec) -> None: + """Explain the effective search fold policy and repeated nested-search budgets.""" if cv.enabled: lines.append(f"Search CV: {cv.method}, {cv.folds} folds, training partition only.") else: @@ -414,12 +435,6 @@ def _preview_search(checked: dict[str, Any], cv: LocalCVSpec) -> list[str]: f"Nested CV: independent {inner}-fold inner search inside each of {cv.folds} outer folds, " "then a separate final training search. Search budgets apply to each search." ) - if strategy == "optuna" and effective.get("timeout") is not None: - lines.append( - f"Optuna timeout: {effective['timeout']} seconds is a soft study limit; " - "it does not interrupt an in-flight fit." - ) - return lines def _preview_explanations(pipeline: dict[str, Any]) -> list[str]: @@ -479,15 +494,7 @@ def migrate_workflow_config( if "task" in config and config["task"] != task: raise ValueError("Migration must not change the existing task.") migrated = deepcopy(config) - if "model_selection_mode" in migrated: - if {"score_model_selection", "promotion_policy"}.intersection(migrated): - raise ValueError("Remove mixed legacy/new policies before migration.") - legacy = _choice(migrated, "model_selection_mode", {"pinned_version", "auto_champion"}) - migrated.pop("model_selection_mode") - migrated.update( - score_model_selection="champion" if legacy == "auto_champion" else "pinned_version", - promotion_policy="automatic" if legacy == "auto_champion" else "manual_approval", - ) + _migrate_selection_policy(migrated) if "score_handoff" in migrated and migrated["score_handoff"] != score_handoff: raise ValueError("Migration must not silently change the existing score_handoff.") migrated.update(config_version=1, task=task, score_handoff=score_handoff) @@ -499,6 +506,19 @@ def migrate_workflow_config( return migrated +def _migrate_selection_policy(migrated: dict[str, Any]) -> None: + """Translate legacy policy fields without merging contradictory generations.""" + if "model_selection_mode" in migrated: + if {"score_model_selection", "promotion_policy"}.intersection(migrated): + raise ValueError("Remove mixed legacy/new policies before migration.") + legacy = _choice(migrated, "model_selection_mode", {"pinned_version", "auto_champion"}) + migrated.pop("model_selection_mode") + migrated.update( + score_model_selection="champion" if legacy == "auto_champion" else "pinned_version", + promotion_policy="automatic" if legacy == "auto_champion" else "manual_approval", + ) + + def validate_deployed_contract(config: dict[str, Any], parameters: dict[str, str]) -> None: """Require notebook/job generation to agree with the project's handoff contract.""" if parameters.get("workflow_contract") != "2" or parameters.get( diff --git a/skyulf-core/skyulf/integrations/mlflow/challenger.py b/skyulf-core/skyulf/integrations/mlflow/challenger.py index 4a242a278..776c9013c 100644 --- a/skyulf-core/skyulf/integrations/mlflow/challenger.py +++ b/skyulf-core/skyulf/integrations/mlflow/challenger.py @@ -48,14 +48,7 @@ def registered(self, candidate: ResolvedModel) -> None: if not isinstance(candidate, ResolvedModel) or candidate.name != self.model_name: raise ValueError("Registered candidate must belong to the lifecycle model.") _admission(self.admission, self.registry_uri) - fresh = resolve_model( - candidate.name, - version=candidate.version, - tracking_uri=self.tracking_uri, - registry_uri=self.registry_uri, - ) - if fresh.digest != candidate.digest or not candidate.digest: - raise ValueError("Candidate artifact digest changed before nomination.") + _verify_nomination_digest(candidate, self.tracking_uri, self.registry_uri) client = _make_client(_require_mlflow(), self.tracking_uri, self.registry_uri) with self.admission.hold(alias_resource_id(candidate.name)): _assert_not_rejected(client, candidate.name, candidate.version) @@ -146,3 +139,17 @@ def failed(self) -> None: "promotion_status": "not_promoted", }, ) + + +def _verify_nomination_digest( + candidate: ResolvedModel, tracking_uri: str | None, registry_uri: str | None +) -> None: + """Resolve and verify the nominated artifact before acquiring alias admission.""" + fresh = resolve_model( + candidate.name, + version=candidate.version, + tracking_uri=tracking_uri, + registry_uri=registry_uri, + ) + if fresh.digest != candidate.digest or not candidate.digest: + raise ValueError("Candidate artifact digest changed before nomination.") diff --git a/skyulf-core/skyulf/integrations/mlflow/local_model.py b/skyulf-core/skyulf/integrations/mlflow/local_model.py index 1ea5062fb..9ed8b6c24 100644 --- a/skyulf-core/skyulf/integrations/mlflow/local_model.py +++ b/skyulf-core/skyulf/integrations/mlflow/local_model.py @@ -58,14 +58,7 @@ def log_local_model( tracking_uri: str | None = None, ) -> str: """Log a fitted local pipeline under one explicit MLflow run and artifact path.""" - if type(run_id) is not str or not run_id.strip(): - raise ValueError("run_id must be a non-empty string.") - if type(artifact_path) is not str or not artifact_path.strip(): - raise ValueError("artifact_path must be a non-empty string.") - if any(marker in artifact_path for marker in ("#", "?")): - raise ValueError("artifact_path cannot contain URI delimiters.") - if tracking_uri is not None and (type(tracking_uri) is not str or not tracking_uri.strip()): - raise ValueError("tracking_uri must be a non-empty string or None.") + _validate_local_destination(run_id, artifact_path, tracking_uri) local_path = Path(local_artifact_path).resolve() artifact = load_local_pipeline(local_path) client = _make_client(tracking_uri) @@ -157,3 +150,15 @@ def _pip_requirements(artifact: LocalPipelineArtifact) -> list[str]: *(f"{name}=={value}" for name, value in artifact.manifest.requirements if name != "python"), f"mlflow=={mlflow.__version__}", ] + + +def _validate_local_destination(run_id: str, artifact_path: str, tracking_uri: str | None) -> None: + """Validate the explicit run and upload destination before reading the artifact.""" + if type(run_id) is not str or not run_id.strip(): + raise ValueError("run_id must be a non-empty string.") + if type(artifact_path) is not str or not artifact_path.strip(): + raise ValueError("artifact_path must be a non-empty string.") + if any(marker in artifact_path for marker in ("#", "?")): + raise ValueError("artifact_path cannot contain URI delimiters.") + if tracking_uri is not None and (type(tracking_uri) is not str or not tracking_uri.strip()): + raise ValueError("tracking_uri must be a non-empty string or None.") diff --git a/skyulf-core/skyulf/integrations/mlflow/model.py b/skyulf-core/skyulf/integrations/mlflow/model.py index 303d948a7..2b9ac5981 100644 --- a/skyulf-core/skyulf/integrations/mlflow/model.py +++ b/skyulf-core/skyulf/integrations/mlflow/model.py @@ -106,12 +106,7 @@ def _validate_arguments( raise TypeError("bundle must be an InferenceBundle.") if type(run_id) is not str or not run_id.strip(): raise ValueError("run_id must be a non-empty string.") - if type(artifact_path) is not str or not artifact_path.strip(): - raise ValueError("artifact_path must be a non-empty string.") - if any(reserved in artifact_path for reserved in ("#", "?")): - raise ValueError("artifact_path cannot contain '#' or '?' because they are URI delimiters.") - if tracking_uri is not None and (type(tracking_uri) is not str or not tracking_uri.strip()): - raise ValueError("tracking_uri must be a non-empty string or None.") + _validate_artifact_destination(artifact_path, tracking_uri) return run_id @@ -221,3 +216,13 @@ def _mlflow_dtype(dtype: str) -> Any: "MLflow column signatures cannot preserve this bundle dtype exactly: " f"{dtype}. Use int32/int64, float32/float64, bool or string." ) from exc + + +def _validate_artifact_destination(artifact_path: str, tracking_uri: str | None) -> None: + """Validate the upload path and optional tracking store before packaging.""" + if type(artifact_path) is not str or not artifact_path.strip(): + raise ValueError("artifact_path must be a non-empty string.") + if any(reserved in artifact_path for reserved in ("#", "?")): + raise ValueError("artifact_path cannot contain '#' or '?' because they are URI delimiters.") + if tracking_uri is not None and (type(tracking_uri) is not str or not tracking_uri.strip()): + raise ValueError("tracking_uri must be a non-empty string or None.") diff --git a/skyulf-core/skyulf/integrations/mlflow/promotion.py b/skyulf-core/skyulf/integrations/mlflow/promotion.py index 9f108505a..5a4217866 100644 --- a/skyulf-core/skyulf/integrations/mlflow/promotion.py +++ b/skyulf-core/skyulf/integrations/mlflow/promotion.py @@ -201,36 +201,11 @@ def _read_challenger_history(client: Any, name: str) -> str | None: raise AliasConflictError("Challenger history alias lacks a controlled receipt.") return None try: - marker = json.loads(raw) - if ( - not isinstance(marker, dict) - or not isinstance(marker.get("event_id"), str) - or not marker["event_id"] - or not isinstance(marker.get("version"), str) - or not marker["version"].isascii() - or not marker["version"].isdigit() - ): - raise ValueError + marker = _parse_history_marker(raw) tags = client.get_model_version(name, marker["version"]).tags or {} history = json.loads(tags[f"challenger_history_{marker['event_id']}"]) event = _read_event(tags[_event_tag(marker["event_id"])]) - if ( - history["state"] != "committed" - or event["s"] != "committed" - or history["to_version"] != current - or event["k"] not in {"nomination", "challenger", "initial", "promotion", "rollback"} - ): - raise ValueError - if current is not None: - if event["k"] not in {"nomination", "challenger"} or event["p"] != current: - raise ValueError - if current in { - _read_optional_alias(client, name, _ALIAS), - _read_optional_alias(client, name, _CHALLENGER), - }: - raise ValueError - elif history["from_version"] != marker["version"]: - raise ValueError + _verify_history_transition(client, name, current, marker, history, event) except (TypeError, ValueError, KeyError) as exc: raise AliasConflictError( "Challenger history disagrees with its committed receipt." @@ -308,23 +283,7 @@ def controlled_champion_version( if tags.get(_ACTIVE_TAG): raise AliasConflictError("Champion receipt exists without its alias.") return None - event_id = _active_marker(client, model_name, current) - if event_id is None: - raise AliasConflictError("Champion alias lacks a controlled committed receipt.") - try: - version_tags = client.get_model_version(model_name, current).tags or {} - except Exception as exc: # noqa: BLE001 - registry transport boundary - raise _translate_error(exc, name=model_name, version=current) from exc - try: - event = _read_event(version_tags.get(_event_tag(event_id))) - except (TypeError, ValueError) as exc: - raise AliasConflictError("Champion receipt is malformed.") from exc - if ( - not isinstance(event, dict) - or event.get("s") != "committed" - or event.get("k") not in ("initial", "promotion", "rollback") - ): - raise AliasConflictError("Champion lacks a committed lifecycle receipt.") + _verify_champion_receipt(client, model_name, current) return current @@ -579,17 +538,7 @@ def _validated_report( """Re-evaluate the pinned candidate and return its comparison digest.""" if not isinstance(report, ModelComparisonReport): raise TypeError("report must be a ModelComparisonReport.") - if expected_champion_version != report.champion_version or ( - expected_champion_version is not None - and ( - type(expected_champion_version) is not str - or not expected_champion_version.isascii() - or not expected_champion_version.isdigit() - ) - ): - raise ValueError("Expected champion version must match the comparison report.") - if require_eligible and (not report.eligible or report.reason != "candidate_improved"): - raise ValueError("Comparison does not approve candidate promotion.") + _validate_report_approval(report, expected_champion_version, require_eligible) candidate = resolve_model( report.model_name, version=report.candidate_version, @@ -687,15 +636,7 @@ def initialize_champion( comparison_sha256=digest, parent_event_id=None, ) - challenger = _read_optional_alias(client, report.model_name, _CHALLENGER) - if challenger is not None and challenger != report.candidate_version: - raise AliasConflictError("A different challenger exists before initialization.") - updates: list[tuple[str, str | None, str | None]] = [ - (_ALIAS, report.candidate_version, None) - ] - if challenger is not None: - _checked_challenger_event(client, report.model_name, challenger) - updates.append((_CHALLENGER, None, challenger)) + updates = _initial_alias_updates(client, report) _commit_change(client, receipt, updates) return receipt @@ -752,21 +693,7 @@ def stage_challenger( else None ), ) - passed = report.eligible - reason = { - "candidate_improved": "Improved over champion", - "insufficient_improvement": "No improvement over champion", - "quality_gate_failed": "Quality threshold not met", - }.get(report.reason, report.reason) - if report.reason == "insufficient_improvement" and (report.improvement or 0) > 0: - reason = "Improvement below required minimum" - if report.champion_version is None: - passed = report.quality_threshold is not None and quality_gates_pass(report) - reason = ( - "First model passed quality threshold" - if passed - else "First model quality not approved" - ) + passed, reason = _staging_decision(report) _commit_change( client, receipt, @@ -914,46 +841,12 @@ def rollback_promotion( legacy = _verify_original_receipt(client, receipt) current = _read_alias(client, receipt.model_name) if current == receipt.prior_version: - event_id = _active_marker(client, receipt.model_name, current) - if event_id is None: - raise AliasConflictError("Rollback replay lacks a controlled receipt.") - reversal = AliasChangeReceipt( - event_id=event_id, - kind="rollback", - model_name=receipt.model_name, - alias=_ALIAS, - prior_version=receipt.new_version, - new_version=receipt.prior_version, - comparison_sha256=receipt.comparison_sha256, - parent_event_id=receipt.event_id, - previous_champion_version=receipt.previous_champion_version, - ) - _verify_original_receipt(client, reversal) - if ( - not legacy - and _read_optional_alias(client, receipt.model_name, _PREVIOUS) - != receipt.previous_champion_version - ): - raise AliasConflictError("Previous champion changed after rollback.") - challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) - if challenger is not None: - _checked_challenger_event(client, receipt.model_name, challenger) - if challenger == current: - raise AliasConflictError("Challenger conflicts with the restored champion.") - return reversal + return _replayed_rollback(client, receipt, current, legacy, receipt.prior_version) if current != expected_current_version: raise AliasConflictError("Champion alias differs from expected current version.") if _active_marker(client, receipt.model_name, current) != receipt.event_id: raise AliasConflictError("A newer promotion superseded this rollback receipt.") - challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) - if challenger is not None: - _checked_challenger_event(client, receipt.model_name, challenger) - if challenger in {current, receipt.prior_version}: - raise AliasConflictError("Challenger conflicts with the rollback versions.") - if not legacy and ( - _read_optional_alias(client, receipt.model_name, _PREVIOUS) != receipt.prior_version - ): - raise AliasConflictError("Previous champion alias differs from promotion receipt.") + _verify_rollback_roles(client, receipt, current, legacy) # The previous version must still exist before changing the alias. resolve_model( receipt.model_name, @@ -979,3 +872,164 @@ def rollback_promotion( updates.append((_PREVIOUS, receipt.previous_champion_version, receipt.prior_version)) _commit_change(client, reversal, updates) return reversal + + +def _parse_history_marker(raw: str) -> dict[str, Any]: + """Decode a complete challenger history pointer before reading its version.""" + marker = json.loads(raw) + if ( + not isinstance(marker, dict) + or not isinstance(marker.get("event_id"), str) + or not marker["event_id"] + or not isinstance(marker.get("version"), str) + or not marker["version"].isascii() + or not marker["version"].isdigit() + ): + raise ValueError + return marker + + +def _verify_history_transition( + client: Any, + name: str, + current: str | None, + marker: dict[str, Any], + history: dict[str, Any], + event: dict[str, Any], +) -> None: + """Verify committed history evidence against current alias roles.""" + if ( + history["state"] != "committed" + or event["s"] != "committed" + or history["to_version"] != current + or event["k"] not in {"nomination", "challenger", "initial", "promotion", "rollback"} + ): + raise ValueError + if current is not None: + if event["k"] not in {"nomination", "challenger"} or event["p"] != current: + raise ValueError + if current in { + _read_optional_alias(client, name, _ALIAS), + _read_optional_alias(client, name, _CHALLENGER), + }: + raise ValueError + elif history["from_version"] != marker["version"]: + raise ValueError + + +def _verify_champion_receipt(client: Any, model_name: str, current: str) -> None: + """Require the current champion to have a committed lifecycle receipt.""" + event_id = _active_marker(client, model_name, current) + if event_id is None: + raise AliasConflictError("Champion alias lacks a controlled committed receipt.") + try: + version_tags = client.get_model_version(model_name, current).tags or {} + except Exception as exc: # noqa: BLE001 - registry transport boundary + raise _translate_error(exc, name=model_name, version=current) from exc + try: + event = _read_event(version_tags.get(_event_tag(event_id))) + except (TypeError, ValueError) as exc: + raise AliasConflictError("Champion receipt is malformed.") from exc + if ( + not isinstance(event, dict) + or event.get("s") != "committed" + or event.get("k") not in ("initial", "promotion", "rollback") + ): + raise AliasConflictError("Champion lacks a committed lifecycle receipt.") + + +def _validate_report_approval( + report: ModelComparisonReport, expected_champion_version: str | None, require_eligible: bool +) -> None: + """Check comparison identity and requested promotion approval before re-evaluation.""" + if expected_champion_version != report.champion_version or ( + expected_champion_version is not None + and ( + type(expected_champion_version) is not str + or not expected_champion_version.isascii() + or not expected_champion_version.isdigit() + ) + ): + raise ValueError("Expected champion version must match the comparison report.") + if require_eligible and (not report.eligible or report.reason != "candidate_improved"): + raise ValueError("Comparison does not approve candidate promotion.") + + +def _initial_alias_updates( + client: Any, report: ModelComparisonReport +) -> list[tuple[str, str | None, str | None]]: + """Check an existing contender and plan initial champion alias updates.""" + challenger = _read_optional_alias(client, report.model_name, _CHALLENGER) + if challenger is not None and challenger != report.candidate_version: + raise AliasConflictError("A different challenger exists before initialization.") + updates: list[tuple[str, str | None, str | None]] = [(_ALIAS, report.candidate_version, None)] + if challenger is not None: + _checked_challenger_event(client, report.model_name, challenger) + updates.append((_CHALLENGER, None, challenger)) + return updates + + +def _staging_decision(report: ModelComparisonReport) -> tuple[bool, str]: + """Describe contender quality independently of committing the alias event.""" + passed = report.eligible + reason = { + "candidate_improved": "Improved over champion", + "insufficient_improvement": "No improvement over champion", + "quality_gate_failed": "Quality threshold not met", + }.get(report.reason, report.reason) + if report.reason == "insufficient_improvement" and (report.improvement or 0) > 0: + reason = "Improvement below required minimum" + if report.champion_version is None: + passed = report.quality_threshold is not None and quality_gates_pass(report) + reason = ( + "First model passed quality threshold" if passed else "First model quality not approved" + ) + return passed, reason + + +def _replayed_rollback( + client: Any, receipt: AliasChangeReceipt, current: str, legacy: bool, prior_version: str +) -> AliasChangeReceipt: + """Verify a still-current rollback receipt and all related alias roles.""" + event_id = _active_marker(client, receipt.model_name, current) + if event_id is None: + raise AliasConflictError("Rollback replay lacks a controlled receipt.") + reversal = AliasChangeReceipt( + event_id=event_id, + kind="rollback", + model_name=receipt.model_name, + alias=_ALIAS, + prior_version=receipt.new_version, + new_version=prior_version, + comparison_sha256=receipt.comparison_sha256, + parent_event_id=receipt.event_id, + previous_champion_version=receipt.previous_champion_version, + ) + _verify_original_receipt(client, reversal) + if ( + not legacy + and _read_optional_alias(client, receipt.model_name, _PREVIOUS) + != receipt.previous_champion_version + ): + raise AliasConflictError("Previous champion changed after rollback.") + challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) + if challenger is not None: + _checked_challenger_event(client, receipt.model_name, challenger) + if challenger == current: + raise AliasConflictError("Challenger conflicts with the restored champion.") + return reversal + + +def _verify_rollback_roles( + client: Any, receipt: AliasChangeReceipt, current: str, legacy: bool +) -> None: + """Reject challenger or previous-champion conflicts before restoring a version.""" + challenger = _read_optional_alias(client, receipt.model_name, _CHALLENGER) + if challenger is not None: + _checked_challenger_event(client, receipt.model_name, challenger) + if challenger in {current, receipt.prior_version}: + raise AliasConflictError("Challenger conflicts with the rollback versions.") + if not legacy and ( + _read_optional_alias(client, receipt.model_name, _PREVIOUS) != receipt.prior_version + ): + raise AliasConflictError("Previous champion alias differs from promotion receipt.") diff --git a/skyulf-core/skyulf/integrations/mlflow/registry.py b/skyulf-core/skyulf/integrations/mlflow/registry.py index cc7c5a248..939cf030b 100644 --- a/skyulf-core/skyulf/integrations/mlflow/registry.py +++ b/skyulf-core/skyulf/integrations/mlflow/registry.py @@ -84,14 +84,7 @@ def load_registered_bundle( if not isinstance(resolved, ResolvedModel): raise TypeError("resolved must be a ResolvedModel.") _validate_registry_options(resolved.name, tracking_uri, registry_uri) - if ( - not isinstance(resolved.version, str) - or not resolved.version.isascii() - or not resolved.version.isdigit() - or int(resolved.version) <= 0 - or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" - ): - raise ValueError("resolved must identify a concrete positive model version.") + _validate_concrete_version(resolved) if not isinstance(resolved.digest, str) or not resolved.digest.strip(): raise ValueError("resolved must include the Skyulf bundle digest.") mlflow = _require_mlflow() @@ -138,14 +131,7 @@ def load_registered_local_pipeline( if not isinstance(resolved, ResolvedModel): raise TypeError("resolved must be a ResolvedModel.") _validate_registry_options(resolved.name, tracking_uri, registry_uri) - if ( - not isinstance(resolved.version, str) - or not resolved.version.isascii() - or not resolved.version.isdigit() - or int(resolved.version) <= 0 - or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" - ): - raise ValueError("resolved must identify a concrete positive model version.") + _validate_concrete_version(resolved) if not isinstance(resolved.digest, str) or not resolved.digest.strip(): raise ValueError("resolved must include the Skyulf local pipeline digest.") mlflow = _require_mlflow() @@ -257,23 +243,7 @@ def resolve_model( _validate_reference(name, alias, version, tracking_uri, registry_uri) mlflow = _require_mlflow() client = _make_client(mlflow, tracking_uri, registry_uri) - try: - model_version = ( - client.get_model_version_by_alias(name, alias) - if alias is not None - else client.get_model_version(name, str(version)) - ) - except Exception as exc: # noqa: BLE001 - translate MLflow's backend errors at the boundary - if ( - alias is not None - and _error_code(exc) == "INVALID_PARAMETER_VALUE" - and "alias" in str(exc).lower() - and "not found" in str(exc).lower() - ): - raise RegistryModelNotFoundError( - f"Model '{name}' alias '{alias}' was not found." - ) from exc - raise _translate_error(exc, name=name, version=str(version or alias)) from exc + model_version = _resolve_version(client, name, alias, version) concrete_version = str(model_version.version) model_uri = f"models:/{name}/{concrete_version}" @@ -380,9 +350,7 @@ def _validate_registry_options( parts = name.split(".") if any(not part for part in parts) or len(parts) not in (1, 3): raise ValueError("name must be model or catalog.schema.model.") - for value, label in ((tracking_uri, "tracking_uri"), (registry_uri, "registry_uri")): - if value is not None and (type(value) is not str or not value.strip()): - raise ValueError(f"{label} must be a non-empty string or None.") + _validate_store_uris(tracking_uri, registry_uri) if _is_unity_catalog(registry_uri) and len(parts) != 3: raise ValueError("Unity Catalog names must use catalog.schema.model.") @@ -417,3 +385,44 @@ def _translate_error(exc: Exception, *, name: str, version: str) -> RegistryErro if code in {"PERMISSION_DENIED", "UNAUTHENTICATED", "UNAUTHORIZED"}: return RegistryAccessError(f"Access denied for model '{name}' version '{version}'.") return RegistryOperationError(f"MLflow registry operation failed for model '{name}'.") + + +def _validate_concrete_version(resolved: ResolvedModel) -> None: + """Require a positive pinned version whose URI agrees with its identity.""" + if ( + not isinstance(resolved.version, str) + or not resolved.version.isascii() + or not resolved.version.isdigit() + or int(resolved.version) <= 0 + or resolved.model_uri != f"models:/{resolved.name}/{resolved.version}" + ): + raise ValueError("resolved must identify a concrete positive model version.") + + +def _validate_store_uris(tracking_uri: str | None, registry_uri: str | None) -> None: + """Reject malformed explicit store URIs before constructing a client.""" + for value, label in ((tracking_uri, "tracking_uri"), (registry_uri, "registry_uri")): + if value is not None and (type(value) is not str or not value.strip()): + raise ValueError(f"{label} must be a non-empty string or None.") + + +def _resolve_version(client: Any, name: str, alias: str | None, version: str | int | None) -> Any: + """Resolve one registry selector and translate missing alias errors.""" + try: + model_version = ( + client.get_model_version_by_alias(name, alias) + if alias is not None + else client.get_model_version(name, str(version)) + ) + except Exception as exc: # noqa: BLE001 - translate MLflow's backend errors at the boundary + if ( + alias is not None + and _error_code(exc) == "INVALID_PARAMETER_VALUE" + and "alias" in str(exc).lower() + and "not found" in str(exc).lower() + ): + raise RegistryModelNotFoundError( + f"Model '{name}' alias '{alias}' was not found." + ) from exc + raise _translate_error(exc, name=name, version=str(version or alias)) from exc + return model_version diff --git a/skyulf-core/skyulf/integrations/mlflow/rejection.py b/skyulf-core/skyulf/integrations/mlflow/rejection.py index 8f24d47d3..18a69d3b9 100644 --- a/skyulf-core/skyulf/integrations/mlflow/rejection.py +++ b/skyulf-core/skyulf/integrations/mlflow/rejection.py @@ -1,5 +1,6 @@ """Explicit operator rejection of an evaluated, registered challenger.""" +from typing import Any from uuid import uuid4 from .promotion import ( @@ -57,30 +58,7 @@ def reject_candidate( raise AliasConflictError("Challenger changed before rejection.") event = _checked_challenger_event(client, name, version) if event["k"] == "rejection": - tags = client.get_model_version(name, version).tags or {} - if ( - event.get("h") != digest - or tags.get("approval_status") != "rejected" - or tags.get("approval_reason") != reason - ): - raise AliasConflictError( - "Rejection proof, status or reason differs from the recorded decision." - ) - event_id = _active_marker(client, name, version, "challenger") - if event_id is None: - raise AliasConflictError("Rejected challenger lacks an active decision receipt.") - receipt = AliasChangeReceipt( - event_id=event_id, - kind="rejection", - model_name=name, - alias="challenger", - prior_version=version, - new_version=version, - comparison_sha256=digest, - parent_event_id=event.get("e"), - ) - _verify_original_receipt(client, receipt) - return receipt + return _replayed_rejection(client, name, version, event, digest, reason) stage_event = _verify_staged_challenger(client, report, digest) receipt = AliasChangeReceipt( event_id=uuid4().hex, @@ -103,3 +81,38 @@ def reject_candidate( }, ) return receipt + + +def _replayed_rejection( + client: Any, + name: str, + version: str, + event: dict[str, Any], + digest: str, + reason: str, +) -> AliasChangeReceipt: + """Verify repeated rejection evidence and return its original receipt.""" + tags = client.get_model_version(name, version).tags or {} + if ( + event.get("h") != digest + or tags.get("approval_status") != "rejected" + or tags.get("approval_reason") != reason + ): + raise AliasConflictError( + "Rejection proof, status or reason differs from the recorded decision." + ) + event_id = _active_marker(client, name, version, "challenger") + if event_id is None: + raise AliasConflictError("Rejected challenger lacks an active decision receipt.") + receipt = AliasChangeReceipt( + event_id=event_id, + kind="rejection", + model_name=name, + alias="challenger", + prior_version=version, + new_version=version, + comparison_sha256=digest, + parent_event_id=event.get("e"), + ) + _verify_original_receipt(client, receipt) + return receipt diff --git a/skyulf-core/skyulf/integrations/mlflow/validation.py b/skyulf-core/skyulf/integrations/mlflow/validation.py index 63088d064..65e2daba5 100644 --- a/skyulf-core/skyulf/integrations/mlflow/validation.py +++ b/skyulf-core/skyulf/integrations/mlflow/validation.py @@ -110,14 +110,7 @@ def validate_quality_policy( raise ValueError("metric must be a supported heldout metric compatible with the task.") if quality_threshold is not None: _validate_threshold(metric, quality_threshold, "quality_threshold") - if quality_gates is None: - return - if not isinstance(quality_gates, dict): - raise ValueError("quality_gates must map additional heldout metrics to thresholds.") - for name, threshold in quality_gates.items(): - if not isinstance(name, str) or name not in supported or name == metric: - raise ValueError("quality_gates needs distinct, task-compatible additional metrics.") - _validate_threshold(name, threshold, f"quality_gates[{name}]") + _validate_additional_gates(quality_gates, metric, supported) def evaluate_quality_gates( @@ -131,12 +124,7 @@ def evaluate_quality_gates( thresholds.update(sorted((quality_gates or {}).items())) results = [] for name, threshold in thresholds.items(): - value = metrics.get(name) - direction = "minimize" if name in _MINIMIZE else "maximize" - available = value is not None and math.isfinite(value) - passed = available and ( - value <= threshold if direction == "minimize" else value >= threshold - ) + value, direction, available, passed = _quality_gate_outcome(metrics, name, threshold) results.append( { "metric": name, @@ -193,10 +181,9 @@ def _validate_model_reference(reference: ResolvedModel) -> None: or not reference.version.isdigit() or int(reference.version) <= 0 or reference.model_uri != f"models:/{reference.name}/{reference.version}" - or not isinstance(reference.digest, str) - or not reference.digest ): raise ValueError("Each model must have a concrete version and artifact digest.") + _validate_reference_digest(reference) def _validate_model_pair(candidate: ResolvedModel, champion: ResolvedModel | None) -> None: @@ -421,3 +408,34 @@ def compare_registered_local_models( reason=reason, quality_gates=dict(quality_gates) if quality_gates else None, ) + + +def _validate_additional_gates( + quality_gates: dict[str, float] | None, metric: str, supported: set[str] +) -> None: + """Validate additional task-compatible thresholds in their configured order.""" + if quality_gates is None: + return + if not isinstance(quality_gates, dict): + raise ValueError("quality_gates must map additional heldout metrics to thresholds.") + for name, threshold in quality_gates.items(): + if not isinstance(name, str) or name not in supported or name == metric: + raise ValueError("quality_gates needs distinct, task-compatible additional metrics.") + _validate_threshold(name, threshold, f"quality_gates[{name}]") + + +def _quality_gate_outcome( + metrics: dict[str, float], name: str, threshold: float +) -> tuple[float | None, str, bool, bool]: + """Compute availability and threshold outcome for one quality metric.""" + value = metrics.get(name) + direction = "minimize" if name in _MINIMIZE else "maximize" + available = value is not None and math.isfinite(value) + passed = available and (value <= threshold if direction == "minimize" else value >= threshold) + return value, direction, available, passed + + +def _validate_reference_digest(reference: ResolvedModel) -> None: + """Require artifact identity after the concrete registry identity is validated.""" + if not isinstance(reference.digest, str) or not reference.digest: + raise ValueError("Each model must have a concrete version and artifact digest.") diff --git a/skyulf-core/skyulf/leakage.py b/skyulf-core/skyulf/leakage.py index 7861da3b5..992950caf 100644 --- a/skyulf-core/skyulf/leakage.py +++ b/skyulf-core/skyulf/leakage.py @@ -291,10 +291,7 @@ def validate_leakage_safety( splitters = train_test_splitters() if target_column is None: target_column = _find_pipeline_target(preprocessing, splitters) - for step in preprocessing: - validate_temporal_target( - step.get("transformer") or "", step.get("params") or {}, target_column=target_column - ) + _validate_temporal_steps(preprocessing, target_column) if already_split: return [] splitter = _first_pipeline_splitter(preprocessing, splitters) @@ -307,6 +304,14 @@ def validate_leakage_safety( return violations if on_leakage == "warn" else [] +def _validate_temporal_steps(preprocessing: Any, target_column: str | None) -> None: + """Reject current-target rolling features regardless of split or warning policy.""" + for step in preprocessing: + validate_temporal_target( + step.get("transformer") or "", step.get("params") or {}, target_column=target_column + ) + + def _first_pipeline_splitter( preprocessing: Any, splitters: frozenset[str] ) -> tuple[int, Any] | None: diff --git a/skyulf-core/skyulf/modeling/_tuning/engine.py b/skyulf-core/skyulf/modeling/_tuning/engine.py index eb149d0df..cc716bd30 100644 --- a/skyulf-core/skyulf/modeling/_tuning/engine.py +++ b/skyulf-core/skyulf/modeling/_tuning/engine.py @@ -921,12 +921,9 @@ def tune( # FeatureEngineer), not the numpy arrays used by the searchers. # Holdout mode is excluded: the splitter stage already produced # the concatenated train+validation frames the mask is aligned to. - if ( - preprocessing is not None - and preprocessing_frames is not None - and validation_data is None - ): - X_for_search, y_for_search = preprocessing_frames + X_for_search, y_for_search = self._grid_search_frames( + (X_for_search, y_for_search), preprocessing, preprocessing_frames, validation_data + ) # Use custom loop to support progress and log callbacks return run_grid_or_random_search( X_for_search, @@ -981,6 +978,22 @@ def tune( log_callback, ) + @staticmethod + def _grid_search_frames( + search_frames: tuple[Any, Any], + preprocessing: "FoldPreprocessor | None", + preprocessing_frames: tuple[Any, Any] | None, + validation_data: tuple[Any, Any] | None, + ) -> tuple[Any, Any]: + """Retain named raw frames for per-fold refits outside explicit holdout mode.""" + if ( + preprocessing is not None + and preprocessing_frames is not None + and validation_data is None + ): + return preprocessing_frames + return search_frames + class TuningApplier(BaseModelApplier): """Applier for TuningCalculator. diff --git a/skyulf-core/skyulf/modeling/_tuning/strategies/halving.py b/skyulf-core/skyulf/modeling/_tuning/strategies/halving.py index ac01cdf2c..5cc7099a1 100644 --- a/skyulf-core/skyulf/modeling/_tuning/strategies/halving.py +++ b/skyulf-core/skyulf/modeling/_tuning/strategies/halving.py @@ -37,27 +37,9 @@ def build_halving_searcher( max_resources = strategy_params.get("max_resources", "auto") if type(resource) is not str or not resource: raise ValueError("Halving resource must name n_samples or an estimator parameter.") - if isinstance(min_resources, str) and min_resources.isdigit(): - min_resources = int(min_resources) - if isinstance(max_resources, str) and max_resources.isdigit(): - max_resources = int(max_resources) - if resource == "n_samples": - if min_resources not in ("exhaust", "smallest") and ( - type(min_resources) is not int or min_resources <= 0 - ): - raise ValueError("Halving min_resources must be positive or exhaust/smallest.") - if max_resources != "auto" and (type(max_resources) is not int or max_resources <= 0): - raise ValueError("Halving max_resources must be auto or a positive integer.") - else: - if type(max_resources) is not int or max_resources <= 0: - raise ValueError("Halving estimator resource requires explicit positive max_resources.") - if type(min_resources) is not int or min_resources <= 0: - raise ValueError("Halving estimator resource requires positive integer min_resources.") - params = base_estimator.get_params(deep=True) - routed = f"model__estimator__{resource}" - resource = routed if routed in params else resource - if resource not in params: - raise ValueError("Halving resource is not an available estimator parameter.") + min_resources = _resource_count(min_resources) + max_resources = _resource_count(max_resources) + resource = _validate_resource(base_estimator, resource, min_resources, max_resources) if type(min_resources) is int and type(max_resources) is int and min_resources > max_resources: raise ValueError("Halving min_resources cannot exceed max_resources.") space = clean_search_space(config.search_space) @@ -65,29 +47,7 @@ def build_halving_searcher( raise ValueError("Halving resource cannot also appear in search_space.") scoring = wrap_fold_scorer(base_estimator, scoring) - # Halving search uses sklearn's internal scheduler and does NOT - # expose per-trial callbacks (no equivalent of Optuna's callbacks=). - # Emit a started log here so the Live Logs panel is never empty - # while the search is running. Per-iteration progress is not - # available without monkey-patching sklearn internals. - if log_callback: - if config.strategy == "halving_grid": - grid_size = int(np.prod([len(v) for v in space.values()] or [0])) - log_callback( - f"Starting halving_grid search " - f"(grid_size={grid_size}, factor={factor}, " - f"resource={resource}, min_resources={min_resources}, max_resources={max_resources}). " - f"sklearn HalvingGridSearchCV runs without per-trial callbacks; " - f"this may take a while." - ) - else: - log_callback( - f"Starting halving_random search " - f"(n_candidates={config.n_trials}, factor={factor}, " - f"resource={resource}, min_resources={min_resources}, max_resources={max_resources}). " - f"sklearn HalvingRandomSearchCV runs without per-trial callbacks; " - f"this may take a while." - ) + _log_search_start(config, space, factor, resource, min_resources, max_resources, log_callback) if config.strategy == "halving_grid": return HalvingGridSearchCV( @@ -119,3 +79,81 @@ def build_halving_searcher( min_resources=min_resources, max_resources=max_resources, ) + + +def _resource_count(value: Any) -> Any: + """Accept digit strings as resource counts while retaining sklearn sentinels.""" + if isinstance(value, str) and value.isdigit(): + return int(value) + return value + + +def _validate_resource( + base_estimator: Any, resource: str, min_resources: Any, max_resources: Any +) -> str: + """Validate sample budgets or resolve the declared estimator resource parameter.""" + if resource == "n_samples": + _validate_sample_resources(min_resources, max_resources) + return resource + return _validate_estimator_resource(base_estimator, resource, min_resources, max_resources) + + +def _validate_sample_resources(min_resources: Any, max_resources: Any) -> None: + """Allow sample-budget sentinels or strictly positive integer bounds.""" + if min_resources not in ("exhaust", "smallest") and ( + type(min_resources) is not int or min_resources <= 0 + ): + raise ValueError("Halving min_resources must be positive or exhaust/smallest.") + if max_resources != "auto" and (type(max_resources) is not int or max_resources <= 0): + raise ValueError("Halving max_resources must be auto or a positive integer.") + + +def _validate_estimator_resource( + base_estimator: Any, resource: str, min_resources: Any, max_resources: Any +) -> str: + """Require numeric estimator budgets and route fold-wrapped parameter names.""" + if type(max_resources) is not int or max_resources <= 0: + raise ValueError("Halving estimator resource requires explicit positive max_resources.") + if type(min_resources) is not int or min_resources <= 0: + raise ValueError("Halving estimator resource requires positive integer min_resources.") + params = base_estimator.get_params(deep=True) + routed = f"model__estimator__{resource}" + resource = routed if routed in params else resource + if resource not in params: + raise ValueError("Halving resource is not an available estimator parameter.") + return resource + + +def _log_search_start( + config: TuningConfig, + space: dict, + factor: Any, + resource: str, + min_resources: Any, + max_resources: Any, + log_callback: Callable[[str], None] | None, +) -> None: + """Report the scheduled halving search while sklearn owns iteration progress.""" + # Halving search uses sklearn's internal scheduler and does NOT + # expose per-trial callbacks (no equivalent of Optuna's callbacks=). + # Emit a started log here so the Live Logs panel is never empty + # while the search is running. Per-iteration progress is not + # available without monkey-patching sklearn internals. + if log_callback: + if config.strategy == "halving_grid": + grid_size = int(np.prod([len(v) for v in space.values()] or [0])) + log_callback( + f"Starting halving_grid search " + f"(grid_size={grid_size}, factor={factor}, " + f"resource={resource}, min_resources={min_resources}, max_resources={max_resources}). " + f"sklearn HalvingGridSearchCV runs without per-trial callbacks; " + f"this may take a while." + ) + else: + log_callback( + f"Starting halving_random search " + f"(n_candidates={config.n_trials}, factor={factor}, " + f"resource={resource}, min_resources={min_resources}, max_resources={max_resources}). " + f"sklearn HalvingRandomSearchCV runs without per-trial callbacks; " + f"this may take a while." + ) diff --git a/skyulf-core/skyulf/pipeline/_pipeline.py b/skyulf-core/skyulf/pipeline/_pipeline.py index afbf9828c..948267e14 100644 --- a/skyulf-core/skyulf/pipeline/_pipeline.py +++ b/skyulf-core/skyulf/pipeline/_pipeline.py @@ -368,10 +368,7 @@ def _fit( input_schema = None fitted_engine = None if self.model_estimator is not None: - raw_train = data.train if isinstance(data, SplitDataset) else data - raw_features = raw_train[0] if isinstance(raw_train, tuple) else raw_train - input_schema = SkyulfSchema.from_dataframe(raw_features).drop((target_column,)) - fitted_engine = str(get_engine(raw_features).name) + input_schema, fitted_engine = self._fit_input_metadata(data, target_column) # 1. Feature Engineering logger.info("Starting Feature Engineering...") @@ -396,52 +393,75 @@ def _fit( # 2. Modeling if self.model_estimator: - logger.info("Starting Model Training...") - - # Ensure transformed_data is SplitDataset for modeling - if isinstance(transformed_data, SplitDataset): - dataset = transformed_data - else: - # If we only have a DataFrame, we can't really evaluate properly without a split - # But we can fit on it. - # Ideally, the user should provide a SplitDataset or use a Splitter node in preprocessing. - # If preprocessing didn't split, we wrap it. - engine = get_engine(transformed_data) - empty_df = engine.create_dataframe({}) - dataset = SplitDataset(train=transformed_data, test=empty_df, validation=None) - - # Observe the actual training representation before sklearn loses - # its column names. Schemas contain metadata only, never samples. - model_schema = SkyulfSchema.from_dataframe(extract_xy(dataset.train, target_column)[0]) - - # Fit the model - # Note: fit_predict updates self.model_estimator.model in-memory - if not is_tuning: - _ = self.model_estimator.fit_predict( - dataset=dataset, - target_column=target_column, - config=cast(dict[str, Any], self.modeling_config), - ) - - # Evaluate - # We can run evaluation if we have test/validation sets - try: - eval_report = self.model_estimator.evaluate( - dataset=dataset, target_column=target_column - ) - metrics["modeling"] = eval_report - except Exception as e: # noqa: BLE001 - evaluation failure is recorded as modeling_error; fit must continue - logger.warning(f"Evaluation failed: {e}") - metrics["modeling_error"] = str(e) - - if self.model_estimator.model is not None and input_schema is not None: - self._inference_schemas = (input_schema, model_schema) - self._fitted_engine = fitted_engine + self._fit_model( + transformed_data, target_column, is_tuning, metrics, input_schema, fitted_engine + ) self._fit_metrics = metrics self._target_column = target_column return metrics + @staticmethod + def _fit_input_metadata(data: Any, target_column: str) -> tuple[SkyulfSchema, str]: + """Record the training feature schema and execution engine before preprocessing.""" + raw_train = data.train if isinstance(data, SplitDataset) else data + raw_features = raw_train[0] if isinstance(raw_train, tuple) else raw_train + schema = SkyulfSchema.from_dataframe(raw_features).drop((target_column,)) + return schema, str(get_engine(raw_features).name) + + def _fit_model( + self, + transformed_data: Any, + target_column: str, + is_tuning: bool, + metrics: dict[str, Any], + input_schema: SkyulfSchema | None, + fitted_engine: str | None, + ) -> None: + """Fit and evaluate the model before publishing successful inference metadata.""" + assert self.model_estimator is not None + logger.info("Starting Model Training...") + + # Ensure transformed_data is SplitDataset for modeling + if isinstance(transformed_data, SplitDataset): + dataset = transformed_data + else: + # If we only have a DataFrame, we can't really evaluate properly without a split + # But we can fit on it. + # Ideally, the user should provide a SplitDataset or use a Splitter node in preprocessing. + # If preprocessing didn't split, we wrap it. + engine = get_engine(transformed_data) + empty_df = engine.create_dataframe({}) + dataset = SplitDataset(train=transformed_data, test=empty_df, validation=None) + + # Observe the actual training representation before sklearn loses + # its column names. Schemas contain metadata only, never samples. + model_schema = SkyulfSchema.from_dataframe(extract_xy(dataset.train, target_column)[0]) + + # Fit the model + # Note: fit_predict updates self.model_estimator.model in-memory + if not is_tuning: + _ = self.model_estimator.fit_predict( + dataset=dataset, + target_column=target_column, + config=cast(dict[str, Any], self.modeling_config), + ) + + # Evaluate + # We can run evaluation if we have test/validation sets + try: + eval_report = self.model_estimator.evaluate( + dataset=dataset, target_column=target_column + ) + metrics["modeling"] = eval_report + except Exception as e: # noqa: BLE001 - evaluation failure is recorded as modeling_error; fit must continue + logger.warning(f"Evaluation failed: {e}") + metrics["modeling_error"] = str(e) + + if self.model_estimator.model is not None and input_schema is not None: + self._inference_schemas = (input_schema, model_schema) + self._fitted_engine = fitted_engine + def get_fitted_split( self, data: pd.DataFrame | pl.DataFrame | SkyulfDataFrame | SplitDataset, diff --git a/skyulf-core/skyulf/preprocessing/_feature_state.py b/skyulf-core/skyulf/preprocessing/_feature_state.py index 621468611..e34047bf2 100644 --- a/skyulf-core/skyulf/preprocessing/_feature_state.py +++ b/skyulf-core/skyulf/preprocessing/_feature_state.py @@ -32,15 +32,7 @@ def restore_feature_state( payload: bytes, options: ExecutionOptions | None, spec: FrameSpec | None ) -> tuple[list[dict], list[dict]]: """Rebind explicit Spark keys and instantiate only known node appliers after validation.""" - if options is not None and not isinstance(options, ExecutionOptions): - raise TypeError("execution_options must be ExecutionOptions.") - if spec is not None and not isinstance(spec, FrameSpec): - raise TypeError("frame_spec must be FrameSpec.") - spark = options is not None and options.engine == "spark" - if spark and spec is None: - raise ValueError("Spark requires frame_spec when loading portable state.") - if not spark and spec is not None: - raise ValueError("frame_spec is currently supported only for Spark execution.") + spark = _validate_runtime(options, spec) records = decode_pipeline(payload, max_bytes=_budget(options)) if spark: assert spec is not None @@ -54,6 +46,20 @@ def restore_feature_state( return configs, records +def _validate_runtime(options: ExecutionOptions | None, spec: FrameSpec | None) -> bool: + """Check the destination execution context before decoding portable state.""" + if options is not None and not isinstance(options, ExecutionOptions): + raise TypeError("execution_options must be ExecutionOptions.") + if spec is not None and not isinstance(spec, FrameSpec): + raise TypeError("frame_spec must be FrameSpec.") + spark = options is not None and options.engine == "spark" + if spark and spec is None: + raise ValueError("Spark requires frame_spec when loading portable state.") + if not spark and spec is not None: + raise ValueError("frame_spec is currently supported only for Spark execution.") + return spark + + def _budget(options: ExecutionOptions | None) -> int: """Apply one total byte limit independently of the destination runtime.""" return options.state_max_bytes if options is not None else DEFAULT_MAX_STATE_BYTES diff --git a/skyulf-core/skyulf/preprocessing/_spark_numeric.py b/skyulf-core/skyulf/preprocessing/_spark_numeric.py index 624fdcab0..4fe7694fd 100644 --- a/skyulf-core/skyulf/preprocessing/_spark_numeric.py +++ b/skyulf-core/skyulf/preprocessing/_spark_numeric.py @@ -29,13 +29,18 @@ def select_columns( cols = config.get("columns") if cols is None: cols = [name for name in frame.columns if name != config.get("target_column")] + _validate_columns(cols, schema) + if automatic and numeric_only: + cols = [name for name in cols if schema[name] in NUMERIC_DTYPES] + return cols, schema, automatic + + +def _validate_columns(cols: Any, schema: dict[str, str]) -> None: + """Require a list of unique names present in the Spark schema.""" if not isinstance(cols, list) or any(not isinstance(name, str) for name in cols): raise ValueError("columns must be a list of names.") if len(set(cols)) != len(cols) or set(cols).difference(schema): raise ValueError("Spark feature columns are missing or duplicated.") - if automatic and numeric_only: - cols = [name for name in cols if schema[name] in NUMERIC_DTYPES] - return cols, schema, automatic def missing(frame: Any, name: str, dtype: str, functions: Any) -> Any: diff --git a/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py b/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py index bdb082229..1c2bbc318 100644 --- a/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py +++ b/skyulf-core/skyulf/preprocessing/imputation/_spark_simple.py @@ -20,12 +20,7 @@ def _constant(value: Any, dtype: str) -> Any: """Require unambiguous scalar constants, preserving integer precision.""" if dtype in NUMERIC_DTYPES: - value = 0 if value is None else value - if type(value) not in (int, float): - raise TypeError("Numeric Spark columns require a numeric fill_value.") - if type(value) is int and not -(2**63) <= value < 2**63: - raise ValueError("Spark integer fill_value must fit a signed 64-bit integer.") - return value + return _numeric_constant(value) if dtype == "string": if value is None: raise ValueError("String constant imputation requires an explicit fill_value.") @@ -36,6 +31,16 @@ def _constant(value: Any, dtype: str) -> Any: raise TypeError("Unsupported Spark imputer dtype or incompatible fill_value.") +def _numeric_constant(value: Any) -> int | float: + """Validate numeric constants without losing signed integer precision.""" + value = 0 if value is None else value + if type(value) not in (int, float): + raise TypeError("Numeric Spark columns require a numeric fill_value.") + if type(value) is int and not -(2**63) <= value < 2**63: + raise ValueError("Spark integer fill_value must fit a signed 64-bit integer.") + return value + + def _aggregate_expressions( frame: Any, cols: list[str], schema: dict, strategy: str, automatic: bool, functions: Any ) -> list[Any]: @@ -78,8 +83,7 @@ def _artifact(cols: list[str], strategy: str, automatic: bool, stats: Any, const counts = {} for index, name in enumerate(cols): value = constants[name] if strategy == "constant" else stats[f"v{index}"] - if strategy == "mean" and value is not None and not math.isfinite(value): - raise ValueError("Spark mean imputation requires finite observed values.") + _validate_mean(value, strategy) if strategy == "mean" and automatic and excluded(stats, index): continue fills[name] = value @@ -96,6 +100,19 @@ def _artifact(cols: list[str], strategy: str, automatic: bool, stats: Any, const } +def _validate_mean(value: Any, strategy: str) -> None: + """Reject non-finite observed means while allowing all-null columns.""" + if strategy == "mean" and value is not None and not math.isfinite(value): + raise ValueError("Spark mean imputation requires finite observed values.") + + +def _has_fill(value: Any, strategy: str) -> bool: + """Identify learned values that can replace missing observations.""" + return value is not None and not ( + strategy == "mean" and isinstance(value, float) and math.isnan(value) + ) + + def apply_spark_imputer(frame: Any, target: Any, params: dict) -> tuple[Any, Any]: """Fill with native Spark expressions; do not refit or execute a data action.""" if not params: @@ -108,9 +125,7 @@ def apply_spark_imputer(frame: Any, target: Any, params: dict) -> tuple[Any, Any expressions = {name: _column(frame, name) for name in frame.columns} for name in state["columns"]: value = state["fill_values"][name] - if value is None or ( - state["strategy"] == "mean" and isinstance(value, float) and math.isnan(value) - ): + if not _has_fill(value, state["strategy"]): continue replacement = functions.lit(value) if name in schema: diff --git a/skyulf-core/skyulf/preprocessing/pipeline.py b/skyulf-core/skyulf/preprocessing/pipeline.py index d07f6605f..b83bbf19e 100644 --- a/skyulf-core/skyulf/preprocessing/pipeline.py +++ b/skyulf-core/skyulf/preprocessing/pipeline.py @@ -228,22 +228,7 @@ def fit_transform( """ spec = getattr(self, "frame_spec", None) if use_spark(data, getattr(self, "execution_options", None), spec): - assert spec is not None - if target_column is not None and target_column != spec.target: - raise ValueError("target_column conflicts with frame_spec.target.") - if on_split is not None: - raise ValueError("Spark FE uses one frame; on_split is unsupported.") - assert self.execution_options is not None - result, metrics, records = fit_spark( - data, - self.steps_config, - spec, - state_max_bytes=self.execution_options.state_max_bytes, - ) - self.fitted_steps = records - self._spark_fitted = True - self._portable_fitted = True - return result, metrics + return self._fit_transform_spark(data, spec, target_column, on_split) self._portable_fitted = False self.fitted_steps = [] # Reset fitted steps current_data = data @@ -339,6 +324,31 @@ def fit_transform( self._portable_fitted = True return current_data, metrics + def _fit_transform_spark( + self, + data: Any, + spec: FrameSpec | None, + target_column: str | None, + on_split: Callable[[SplitDataset], None] | None, + ) -> tuple[Any, dict[str, Any]]: + """Fit one Spark frame and publish learned records after native execution succeeds.""" + assert spec is not None + if target_column is not None and target_column != spec.target: + raise ValueError("target_column conflicts with frame_spec.target.") + if on_split is not None: + raise ValueError("Spark FE uses one frame; on_split is unsupported.") + assert self.execution_options is not None + result, metrics, records = fit_spark( + data, + self.steps_config, + spec, + state_max_bytes=self.execution_options.state_max_bytes, + ) + self.fitted_steps = records + self._spark_fitted = True + self._portable_fitted = True + return result, metrics + @staticmethod def _step_metric_record( name: str, diff --git a/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py b/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py index e4a8bad5e..b137fae9e 100644 --- a/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py +++ b/skyulf-core/skyulf/preprocessing/scaling/_spark_standard.py @@ -28,6 +28,22 @@ def fit_spark_standard(frame: Any, target: Any, config: dict) -> dict: for name in cols: _validate_dtype(schema[name]) functions = importlib.import_module("pyspark.sql.functions") + references = frame.agg( + *_reference_expressions(frame, cols, schema, automatic, functions) + ).first() + selected = [i for i in range(len(cols)) if not automatic or not excluded(references, i)] + if not selected: + return {} + _validate_observations(references, selected) + expressions = _shifted_expressions(frame, cols, schema, selected, references, flags, functions) + stats = frame.agg(*expressions).first() if expressions else None + return _artifact(cols, selected, references, stats, flags) + + +def _reference_expressions( + frame: Any, cols: list[str], schema: dict, automatic: bool, functions: Any +) -> list[Any]: + """Collect numeric bounds and optional automatic-selection statistics.""" expressions = [functions.count(functions.lit(1)).alias("rows")] for index, name in enumerate(cols): valid = functions.when(~missing(frame, name, schema[name], functions), _column(frame, name)) @@ -43,14 +59,27 @@ def fit_spark_standard(frame: Any, target: Any, config: dict) -> dict: ) if automatic: expressions.extend(selection_statistics(valid, index, functions)) - references = frame.agg(*expressions).first() - selected = [i for i in range(len(cols)) if not automatic or not excluded(references, i)] - if not selected: - return {} + return expressions + + +def _validate_observations(references: Any, selected: list[int]) -> None: + """Reject empty training data and infinite selected observations.""" if not references["rows"]: raise ValueError("Cannot fit StandardScaler on empty training data.") if any(references[f"inf{index}"] for index in selected): raise ValueError("Spark StandardScaler requires finite training values; infinity found.") + + +def _shifted_expressions( + frame: Any, + cols: list[str], + schema: dict, + selected: list[int], + references: Any, + flags: dict, + functions: Any, +) -> list[Any]: + """Build mean and variance expressions around the learned numeric references.""" expressions = [] if flags["with_mean"] or flags["with_std"]: for index in selected: @@ -60,8 +89,7 @@ def fit_spark_standard(frame: Any, target: Any, config: dict) -> dict: ) shifted = valid.cast("double") - _reference(references, index) expressions.extend(_statistics(shifted, index, flags, functions)) - stats = frame.agg(*expressions).first() if expressions else None - return _artifact(cols, selected, references, stats, flags) + return expressions def _validate_dtype(dtype: str) -> None: @@ -99,11 +127,7 @@ def _artifact( variances = [] if flags["with_std"] else None scales = [] if flags["with_std"] else None for index in selected: - mean = ( - _statistic(stats[f"mean{index}"]) + _reference(references, index) - if means is not None - else None - ) + mean = _mean(stats, references, index, means is not None) if means is not None: means.append(mean) if variances is not None and scales is not None: @@ -121,6 +145,24 @@ def _artifact( } +def _mean(stats: Any, references: Any, index: int, enabled: bool) -> float | None: + """Recover the unshifted mean only when the scaler records means.""" + if enabled: + return _statistic(stats[f"mean{index}"]) + _reference(references, index) + return None + + +def _scaled_expression(frame: Any, name: str, index: int, state: dict) -> Any: + """Apply enabled centering and scaling to one numeric Spark column.""" + expr = _column(frame, name).cast("double") + if state["with_mean"]: + expr = expr - state["mean"][index] + if state["with_std"]: + scale = state["scale"][index] + expr = expr / (scale if scale != 0 else 1.0) + return expr.alias(name) + + def _statistic(value: Any) -> float: """Represent missing statistics as NaN and reject overflowing aggregates.""" if value is None: @@ -153,11 +195,5 @@ def apply_spark_standard(frame: Any, target: Any, params: dict) -> tuple[Any, An if name not in schema: continue _validate_dtype(schema[name]) - expr = _column(frame, name).cast("double") - if state["with_mean"]: - expr = expr - state["mean"][index] - if state["with_std"]: - scale = state["scale"][index] - expr = expr / (scale if scale != 0 else 1.0) - expressions[name] = expr.alias(name) + expressions[name] = _scaled_expression(frame, name, index, state) return frame.select(*expressions.values()), target diff --git a/skyulf-core/skyulf/utils.py b/skyulf-core/skyulf/utils.py index fd41ad4a5..403aec8e0 100644 --- a/skyulf-core/skyulf/utils.py +++ b/skyulf-core/skyulf/utils.py @@ -200,9 +200,7 @@ def pack_pipeline_output( through the engine dispatch below. """ if contains_spark_input(X) or contains_spark_input(y): - if was_tuple or y is not None: - raise TypeError("Use a single Spark dataframe containing row keys and target.") - return X + return _pack_spark_output(X, y, was_tuple) if was_tuple and y is None: # Caller said the input was a tuple but lost y along the way. # Surface this so wiring/upstream bugs don't silently degrade the @@ -226,6 +224,13 @@ def pack_pipeline_output( return X +def _pack_spark_output(X: Any, y: Any | None, was_tuple: bool) -> Any: + """Keep distributed features and targets in one Spark frame with record keys.""" + if was_tuple or y is not None: + raise TypeError("Use a single Spark dataframe containing row keys and target.") + return X + + def _is_binary_numeric(series: pd.Series | Any) -> bool: """Check if a numeric series contains only 0s and 1s (or close to them).""" # Handle Polars Series diff --git a/skyulf-core/tests/integrations/test_local_hard_voting.py b/skyulf-core/tests/integrations/test_local_hard_voting.py index 791d7880f..2db6555bb 100644 --- a/skyulf-core/tests/integrations/test_local_hard_voting.py +++ b/skyulf-core/tests/integrations/test_local_hard_voting.py @@ -21,7 +21,6 @@ OutputSink, preflight_local, ) -from skyulf.integrations.mlflow.local_model import SkyulfLocalPythonModel, _signature from skyulf.pipeline import SkyulfPipeline @@ -68,12 +67,6 @@ def test_hard_voting_artifact_predicts_labels_and_evaluates_without_probabilitie ) assert preflight_local(config, artifact=artifact).output_columns == ("prediction",) - signature = _signature(artifact) - assert [column.name for column in signature.outputs.inputs] == ["prediction"] - pyfunc = SkyulfLocalPythonModel() - pyfunc._artifact = artifact - assert pyfunc.predict(None, holdout[["x"]]).columns.tolist() == ["prediction"] - def test_probability_capability_preserves_soft_voting_and_legacy_manifests(tmp_path): """Old manifest files load with the existing classifier probability contract.""" @@ -84,11 +77,6 @@ def test_probability_capability_preserves_soft_voting_and_legacy_manifests(tmp_p "probability_0", "probability_1", ] - assert [column.name for column in _signature(artifact).outputs.inputs] == [ - "prediction", - "probability_0", - "probability_1", - ] metadata = path / "manifest.json" document = json.loads(metadata.read_text(encoding="utf-8")) document.pop("classification_probabilities") @@ -96,6 +84,22 @@ def test_probability_capability_preserves_soft_voting_and_legacy_manifests(tmp_p assert load_local_pipeline(path).manifest.classification_probabilities is True +@pytest.mark.parametrize("voting", ["hard", "soft"]) +def test_mlflow_voting_signature_matches_pyfunc_predictions(tmp_path, voting): + """Optional MLflow exposes only the probabilities supported by each voting mode.""" + pytest.importorskip("mlflow") + from skyulf.integrations.mlflow.local_model import SkyulfLocalPythonModel, _signature + + _, artifact, holdout = _fit(tmp_path, voting=voting) + expected = ["prediction"] + if voting == "soft": + expected += ["probability_0", "probability_1"] + assert [column.name for column in _signature(artifact).outputs.inputs] == expected + pyfunc = SkyulfLocalPythonModel() + pyfunc._artifact = artifact + assert pyfunc.predict(None, holdout[["x"]]).columns.tolist() == expected + + def test_probability_capability_is_checked_against_fitted_model(tmp_path): """Metadata cannot claim probabilities that hard voting does not expose.""" path, _, _ = _fit(tmp_path) diff --git a/skyulf-core/tests/integrations/test_mlflow_promotion.py b/skyulf-core/tests/integrations/test_mlflow_promotion.py index 5a6b0afee..f7cd0c2c8 100644 --- a/skyulf-core/tests/integrations/test_mlflow_promotion.py +++ b/skyulf-core/tests/integrations/test_mlflow_promotion.py @@ -13,6 +13,9 @@ from skyulf.data.dataset import SplitDataset from skyulf.inference.local_pipeline import save_local_pipeline + +mlflow = pytest.importorskip("mlflow") + from skyulf.integrations.mlflow.local_model import log_local_model from skyulf.integrations.mlflow.promotion import ( AliasChangeReceipt, @@ -39,8 +42,6 @@ ) from skyulf.pipeline import SkyulfPipeline -mlflow = pytest.importorskip("mlflow") - @pytest.fixture def champion_reader_client(monkeypatch): diff --git a/sonar-project.properties b/sonar-project.properties index a378e2b0a..e83c39fd2 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -10,6 +10,8 @@ sonar.projectName=Skyulf sonar.sources=backend,skyulf-core/skyulf,frontend/ml-canvas/src sonar.tests=tests,skyulf-core/tests +# Run tests in CI and import source coverage, but do not analyze test code. +sonar.test.exclusions=**/* sonar.sourceEncoding=UTF-8 sonar.python.version=3.12 @@ -20,6 +22,7 @@ sonar.exclusions=\ **/.venv/**,\ **/__pycache__/**,\ **/__snapshots__/**,\ + **/__tests__/**,\ frontend/ml-canvas/src/**/*.test.*,\ frontend/ml-canvas/src/**/*.spec.*,\ frontend/ml-canvas/src/test/**,\ diff --git a/static/ml_canvas/assets/AuditLogPage-CU3Ws-p_.js b/static/ml_canvas/assets/AuditLogPage-BjT9Erh4.js similarity index 99% rename from static/ml_canvas/assets/AuditLogPage-CU3Ws-p_.js rename to static/ml_canvas/assets/AuditLogPage-BjT9Erh4.js index 90999823e..96a0e02cf 100644 --- a/static/ml_canvas/assets/AuditLogPage-CU3Ws-p_.js +++ b/static/ml_canvas/assets/AuditLogPage-BjT9Erh4.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{A as H,y as O,z as U,t as q}from"./index-BXksgzya.js";import{a as l,w as G,l as K,H as B,C as V,x as $,G as Y,y as C,M as z,z as I,D as J,E as Q,c as W,f as X}from"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";const S=t=>String(t.id);function Z({actorFilter:t,kindFilter:r,fromTime:s,toTime:i}){return{...t!=="all"?{actor:t}:{},...r!=="all"?{kind:r}:{},...s?{createdAfter:s}:{},...i?{createdBefore:i}:{}}}function ee(t){if(!t)return null;const r=t.entries,s=new Set(r.map(o=>o.user_id!==null?`u${o.user_id}`:"anon"));let i=0,d=0,n=0;for(const o of r)i+=o.diff.nodes_added.length,d+=o.diff.nodes_removed.length,n+=o.diff.nodes_modified.length;return{saves:r.length,users:s.size,added:i,removed:d,modified:n}}function te(t,r,s,i){const{actorFilter:d,kindFilter:n,fromTime:o,toTime:x}=i,m=(t==null?void 0:t.entries)??[],y=d!=="all"||n!=="all"||o!==""||x!=="",h=(t==null?void 0:t.total)??0,u=(t==null?void 0:t.total_unfiltered)??0,g=m.length,p=`${s}`,a=t?y?`Showing ${g} of ${h} matching saves for ${r}. History total ${u}.`:`Showing ${g} of ${u} saves for ${r}.`:null,j=t?`Page limit ${p}. Newest first. Retention is not reported by the API. Filters are applied across the full history, not just this page.`:null,k=se(t,g,u,r,p);return{filteredEntries:m,historyScopeText:a,historyMetaText:j,emptyStateText:k}}function se(t,r,s,i,d){return t&&r===0?s===0?`No saves recorded for ${i} yet. The audit API shows the newest ${d} saves first, but this dataset currently has no history. Retention is not reported by the API.`:`No audit records match the current filters for ${i}. Filters were applied across all ${s} saves, so widening them is the only way to see more. Retention is not reported by the API.`:null}const re=[25,50,100,200],ae=({state:t})=>{const{actorFilter:r,setActorFilter:s,kindFilter:i,setKindFilter:d,fromTime:n,setFromTime:o,toTime:x,setToTime:m,limit:y,setLimit:h,data:u,actorOptions:g,kindOptions:p}=t;return e.jsxs("div",{className:"flex flex-wrap items-end gap-4 mb-4",children:[e.jsx(de,{state:t}),e.jsxs("div",{className:"min-w-[220px]",children:[e.jsx("label",{htmlFor:"audit-actor",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Actor"}),e.jsxs("select",{id:"audit-actor",value:r,onChange:a=>s(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50",children:[e.jsx("option",{value:"all",children:"All actors"}),g.userIds.map(a=>e.jsxs("option",{value:a,children:["user #",a]},a)),g.hasAnonymous&&e.jsx("option",{value:H,children:"anonymous"})]})]}),e.jsxs("div",{className:"min-w-[180px]",children:[e.jsx("label",{htmlFor:"audit-kind",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Action kind"}),e.jsxs("select",{id:"audit-kind",value:i,onChange:a=>d(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50",children:[e.jsx("option",{value:"all",children:"All kinds"}),p.map(a=>e.jsx("option",{value:a,children:a},a))]})]}),e.jsxs("div",{className:"min-w-[190px]",children:[e.jsx("label",{htmlFor:"audit-from",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"From time"}),e.jsx("input",{id:"audit-from",type:"datetime-local",value:n,onChange:a=>o(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50"})]}),e.jsxs("div",{className:"min-w-[190px]",children:[e.jsx("label",{htmlFor:"audit-to",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"To time"}),e.jsx("input",{id:"audit-to",type:"datetime-local",value:x,onChange:a=>m(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Limit"}),e.jsx("div",{className:"inline-flex rounded border border-gray-300 dark:border-gray-600 overflow-hidden",children:re.map(a=>e.jsx("button",{type:"button",onClick:()=>h(a),className:`px-3 py-2 text-xs font-medium ${y===a?"bg-violet-500 text-white":"bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-slate-700"}`,children:a},a))})]})]})},de=({state:t})=>{const{datasets:r,datasetsLoading:s,datasetId:i,setDatasetId:d}=t;return e.jsxs("div",{className:"flex-1 min-w-[240px]",children:[e.jsx("label",{htmlFor:"audit-dataset",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Dataset"}),e.jsx("select",{id:"audit-dataset",value:i,onChange:n=>d(n.target.value),disabled:s||!r||r.length===0,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50",children:!r||r.length===0?e.jsx("option",{value:"",children:s?"Loading…":"No datasets"}):r.map(n=>{const o=S(n),x=o.length>8?o.slice(0,8):o;return e.jsxs("option",{value:o,children:[n.name," (",x,")"]},o)})})]})},ie=t=>{try{return new Date(t).toLocaleString()}catch{return t}},w=({icon:t,label:r,count:s,tone:i})=>{if(s===0)return null;const d=i==="add"?"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-800":i==="remove"?"bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300 dark:border-rose-800":"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300 dark:border-amber-800";return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium ${d}`,title:`${s} ${r}`,children:[t,s," ",r]})},A=({title:t,items:r,tone:s})=>{if(r.length===0)return null;const i=s==="add"?"text-emerald-600 dark:text-emerald-400":s==="remove"?"text-rose-600 dark:text-rose-400":"text-amber-600 dark:text-amber-400";return e.jsxs("div",{children:[e.jsxs("div",{className:`text-[11px] font-semibold uppercase tracking-wide mb-1 ${i}`,children:[t," (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:r.map(d=>e.jsx("code",{className:"text-[11px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-slate-800 text-gray-700 dark:text-gray-300 font-mono",children:d},d))})]})},oe=({entry:t,isFirst:r})=>{const[s,i]=l.useState(!1),{diff:d}=t,n=d.nodes_added.length+d.nodes_removed.length+d.nodes_modified.length,o=r&&d.nodes_removed.length===0&&d.nodes_modified.length===0;return e.jsxs("div",{className:"border-b border-gray-200 dark:border-gray-700 last:border-b-0",children:[e.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:"w-full flex items-start gap-3 p-3 text-left hover:bg-gray-50 dark:hover:bg-slate-800/50 transition-colors",children:[e.jsx("div",{className:"pt-0.5 text-gray-400",children:s?e.jsx(G,{size:16}):e.jsx(K,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-mono text-gray-500 dark:text-gray-400",children:[e.jsx(B,{size:11}),"v",t.version_int]}),e.jsx("span",{className:"text-sm font-medium text-gray-800 dark:text-gray-100 truncate",children:t.name}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded uppercase font-semibold ${t.kind==="auto"?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300":"bg-gray-100 text-gray-700 dark:bg-slate-700 dark:text-gray-300"}`,children:t.kind}),o&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded uppercase font-semibold bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",children:"initial"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-gray-500 dark:text-gray-400",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(V,{size:11}),ie(t.created_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx($,{size:11}),t.user_id!==null?`user #${t.user_id}`:"anonymous"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Y,{size:11}),t.node_count," nodes / ",t.edge_count," edges"]})]}),t.note&&e.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300 italic truncate",children:["“",t.note,"”"]}),!o&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(w,{icon:e.jsx(C,{size:10}),label:"added",count:d.nodes_added.length,tone:"add"}),e.jsx(w,{icon:e.jsx(z,{size:10}),label:"removed",count:d.nodes_removed.length,tone:"remove"}),e.jsx(w,{icon:e.jsx(I,{size:10}),label:"modified",count:d.nodes_modified.length,tone:"modify"}),n===0&&e.jsx("span",{className:"text-[11px] text-gray-400 italic",children:"no node-level changes"})]})]})]}),e.jsx(ne,{expanded:s,diff:d,totalChanged:n})]})},ne=({expanded:t,diff:r,totalChanged:s})=>e.jsx(e.Fragment,{children:t&&s>0&&e.jsxs("div",{className:"px-10 pb-3 pt-1 space-y-2 bg-gray-50/60 dark:bg-slate-900/40",children:[e.jsx(A,{title:"Added",items:r.nodes_added,tone:"add"}),e.jsx(A,{title:"Removed",items:r.nodes_removed,tone:"remove"}),e.jsx(A,{title:"Modified",items:r.nodes_modified,tone:"modify"})]})}),le=({state:t})=>{const{isLoading:r,datasetId:s,data:i,emptyStateText:d,filteredEntries:n}=t;return e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden",children:r?e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:"Loading audit trail…"}):s?!i||i.entries.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:d}):n.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:d}):e.jsx("div",{children:n.map((o,x)=>e.jsx(oe,{entry:o,isFirst:x===n.length-1},o.id))}):e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:"Pick a dataset to view its save history."})})},ce=({summary:t})=>e.jsx(e.Fragment,{children:t&&t.saves>0&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mb-4",children:[e.jsx(f,{label:"Saves",value:t.saves,icon:e.jsx(J,{size:14})}),e.jsx(f,{label:"Users",value:t.users,icon:e.jsx($,{size:14})}),e.jsx(f,{label:"Nodes added",value:t.added,icon:e.jsx(C,{size:14}),tone:"add"}),e.jsx(f,{label:"Nodes removed",value:t.removed,icon:e.jsx(z,{size:14}),tone:"remove"}),e.jsx(f,{label:"Nodes modified",value:t.modified,icon:e.jsx(I,{size:14}),tone:"modify"})]})}),f=({label:t,value:r,icon:s,tone:i})=>{const d=i==="add"?"text-emerald-600 dark:text-emerald-400":i==="remove"?"text-rose-600 dark:text-rose-400":i==="modify"?"text-amber-600 dark:text-amber-400":"text-gray-700 dark:text-gray-200";return e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wide text-gray-500 dark:text-gray-400 font-medium",children:[s,t]}),e.jsx("div",{className:`mt-1 text-xl font-semibold ${d}`,children:r})]})};function xe(){const{data:t,isLoading:r}=O(),[s,i]=l.useState(""),[d,n]=l.useState(50),[o,x]=l.useState("all"),[m,y]=l.useState("all"),[h,u]=l.useState(""),[g,p]=l.useState(""),[a,j]=l.useState(null),[k,_]=l.useState(!1),[L,T]=l.useState(null);l.useEffect(()=>{if(!s&&t&&t.length>0){const c=t[0];c&&i(S(c))}},[t,s]);const v=l.useRef(0),N=l.useCallback(async()=>{if(!s)return;const c=++v.current;_(!0),T(null);try{const b=await U.audit(s,d,Z({actorFilter:o,kindFilter:m,fromTime:h,toTime:g}));if(c!==v.current)return;j(b)}catch(b){if(c!==v.current)return;const F=b.message||"Failed to load audit trail";T(F),q.error(F)}finally{c===v.current&&_(!1)}},[s,d,o,m,h,g]);l.useEffect(()=>{N()},[N]);const R=l.useMemo(()=>ee(a),[a]),P=l.useMemo(()=>{var c,b;return{hasAnonymous:((c=a==null?void 0:a.facets)==null?void 0:c.has_anonymous_actor)??!1,userIds:((b=a==null?void 0:a.facets)==null?void 0:b.actors)??[]}},[a]),D=l.useMemo(()=>{var c;return((c=a==null?void 0:a.facets)==null?void 0:c.kinds)??[]},[a]),E=l.useMemo(()=>{const c=t==null?void 0:t.find(b=>S(b)===s);return(c==null?void 0:c.name)??"this dataset"},[t,s]),M=te(a,E,d,{actorFilter:o,kindFilter:m,fromTime:h,toTime:g});return{datasets:t,datasetsLoading:r,datasetId:s,setDatasetId:i,limit:d,setLimit:n,actorFilter:o,setActorFilter:x,kindFilter:m,setKindFilter:y,fromTime:h,setFromTime:u,toTime:g,setToTime:p,data:a,isLoading:k,error:L,load:N,summary:R,actorOptions:P,kindOptions:D,...M}}const be=()=>{const t=xe(),{load:r,isLoading:s,datasetId:i,data:d,error:n,summary:o,historyScopeText:x,historyMetaText:m}=t;return e.jsxs("div",{className:"p-6 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2",children:[e.jsx(Q,{className:"w-6 h-6 text-violet-500"}),"Pipeline Audit Log"]}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Chronological history of canvas saves. Each entry shows who, when, and which nodes changed vs. the previous save."})]}),e.jsxs("button",{type:"button",onClick:()=>void r(),disabled:s||!i,className:"inline-flex items-center gap-2 px-3 py-2 text-sm font-medium rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 hover:bg-gray-50 dark:hover:bg-slate-700 disabled:opacity-50",children:[e.jsx(W,{className:`w-4 h-4 ${s?"animate-spin":""}`}),"Refresh"]})]}),e.jsx(ae,{state:t}),d&&e.jsx("p",{className:"mb-4 text-xs text-gray-500 dark:text-gray-400",children:"Actor, action kind and time filters apply across the full history before the page limit."}),n&&e.jsxs("div",{className:"mb-4 flex items-start gap-2 p-3 rounded border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm",children:[e.jsx(X,{className:"w-4 h-4 shrink-0 mt-0.5"}),e.jsx("span",{children:n})]}),e.jsx(ce,{summary:o}),e.jsx(le,{state:t}),x&&e.jsxs("p",{className:"mt-3 text-xs text-gray-500 dark:text-gray-400 text-center",children:[x," ",m]})]})};export{be as AuditLogPage}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{A as H,y as O,z as U,t as q}from"./index-DYMv5Ibu.js";import{a as l,w as G,l as K,H as B,C as V,x as $,G as Y,y as C,M as z,z as I,D as J,E as Q,c as W,f as X}from"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";const S=t=>String(t.id);function Z({actorFilter:t,kindFilter:r,fromTime:s,toTime:i}){return{...t!=="all"?{actor:t}:{},...r!=="all"?{kind:r}:{},...s?{createdAfter:s}:{},...i?{createdBefore:i}:{}}}function ee(t){if(!t)return null;const r=t.entries,s=new Set(r.map(o=>o.user_id!==null?`u${o.user_id}`:"anon"));let i=0,d=0,n=0;for(const o of r)i+=o.diff.nodes_added.length,d+=o.diff.nodes_removed.length,n+=o.diff.nodes_modified.length;return{saves:r.length,users:s.size,added:i,removed:d,modified:n}}function te(t,r,s,i){const{actorFilter:d,kindFilter:n,fromTime:o,toTime:x}=i,m=(t==null?void 0:t.entries)??[],y=d!=="all"||n!=="all"||o!==""||x!=="",h=(t==null?void 0:t.total)??0,u=(t==null?void 0:t.total_unfiltered)??0,g=m.length,p=`${s}`,a=t?y?`Showing ${g} of ${h} matching saves for ${r}. History total ${u}.`:`Showing ${g} of ${u} saves for ${r}.`:null,j=t?`Page limit ${p}. Newest first. Retention is not reported by the API. Filters are applied across the full history, not just this page.`:null,k=se(t,g,u,r,p);return{filteredEntries:m,historyScopeText:a,historyMetaText:j,emptyStateText:k}}function se(t,r,s,i,d){return t&&r===0?s===0?`No saves recorded for ${i} yet. The audit API shows the newest ${d} saves first, but this dataset currently has no history. Retention is not reported by the API.`:`No audit records match the current filters for ${i}. Filters were applied across all ${s} saves, so widening them is the only way to see more. Retention is not reported by the API.`:null}const re=[25,50,100,200],ae=({state:t})=>{const{actorFilter:r,setActorFilter:s,kindFilter:i,setKindFilter:d,fromTime:n,setFromTime:o,toTime:x,setToTime:m,limit:y,setLimit:h,data:u,actorOptions:g,kindOptions:p}=t;return e.jsxs("div",{className:"flex flex-wrap items-end gap-4 mb-4",children:[e.jsx(de,{state:t}),e.jsxs("div",{className:"min-w-[220px]",children:[e.jsx("label",{htmlFor:"audit-actor",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Actor"}),e.jsxs("select",{id:"audit-actor",value:r,onChange:a=>s(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50",children:[e.jsx("option",{value:"all",children:"All actors"}),g.userIds.map(a=>e.jsxs("option",{value:a,children:["user #",a]},a)),g.hasAnonymous&&e.jsx("option",{value:H,children:"anonymous"})]})]}),e.jsxs("div",{className:"min-w-[180px]",children:[e.jsx("label",{htmlFor:"audit-kind",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Action kind"}),e.jsxs("select",{id:"audit-kind",value:i,onChange:a=>d(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50",children:[e.jsx("option",{value:"all",children:"All kinds"}),p.map(a=>e.jsx("option",{value:a,children:a},a))]})]}),e.jsxs("div",{className:"min-w-[190px]",children:[e.jsx("label",{htmlFor:"audit-from",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"From time"}),e.jsx("input",{id:"audit-from",type:"datetime-local",value:n,onChange:a=>o(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50"})]}),e.jsxs("div",{className:"min-w-[190px]",children:[e.jsx("label",{htmlFor:"audit-to",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"To time"}),e.jsx("input",{id:"audit-to",type:"datetime-local",value:x,onChange:a=>m(a.target.value),disabled:!u,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Limit"}),e.jsx("div",{className:"inline-flex rounded border border-gray-300 dark:border-gray-600 overflow-hidden",children:re.map(a=>e.jsx("button",{type:"button",onClick:()=>h(a),className:`px-3 py-2 text-xs font-medium ${y===a?"bg-violet-500 text-white":"bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-slate-700"}`,children:a},a))})]})]})},de=({state:t})=>{const{datasets:r,datasetsLoading:s,datasetId:i,setDatasetId:d}=t;return e.jsxs("div",{className:"flex-1 min-w-[240px]",children:[e.jsx("label",{htmlFor:"audit-dataset",className:"block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1",children:"Dataset"}),e.jsx("select",{id:"audit-dataset",value:i,onChange:n=>d(n.target.value),disabled:s||!r||r.length===0,className:"w-full px-3 py-2 text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 text-gray-900 dark:text-gray-100 disabled:opacity-50",children:!r||r.length===0?e.jsx("option",{value:"",children:s?"Loading…":"No datasets"}):r.map(n=>{const o=S(n),x=o.length>8?o.slice(0,8):o;return e.jsxs("option",{value:o,children:[n.name," (",x,")"]},o)})})]})},ie=t=>{try{return new Date(t).toLocaleString()}catch{return t}},w=({icon:t,label:r,count:s,tone:i})=>{if(s===0)return null;const d=i==="add"?"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-800":i==="remove"?"bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300 dark:border-rose-800":"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300 dark:border-amber-800";return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded border text-[11px] font-medium ${d}`,title:`${s} ${r}`,children:[t,s," ",r]})},A=({title:t,items:r,tone:s})=>{if(r.length===0)return null;const i=s==="add"?"text-emerald-600 dark:text-emerald-400":s==="remove"?"text-rose-600 dark:text-rose-400":"text-amber-600 dark:text-amber-400";return e.jsxs("div",{children:[e.jsxs("div",{className:`text-[11px] font-semibold uppercase tracking-wide mb-1 ${i}`,children:[t," (",r.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:r.map(d=>e.jsx("code",{className:"text-[11px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-slate-800 text-gray-700 dark:text-gray-300 font-mono",children:d},d))})]})},oe=({entry:t,isFirst:r})=>{const[s,i]=l.useState(!1),{diff:d}=t,n=d.nodes_added.length+d.nodes_removed.length+d.nodes_modified.length,o=r&&d.nodes_removed.length===0&&d.nodes_modified.length===0;return e.jsxs("div",{className:"border-b border-gray-200 dark:border-gray-700 last:border-b-0",children:[e.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:"w-full flex items-start gap-3 p-3 text-left hover:bg-gray-50 dark:hover:bg-slate-800/50 transition-colors",children:[e.jsx("div",{className:"pt-0.5 text-gray-400",children:s?e.jsx(G,{size:16}):e.jsx(K,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs font-mono text-gray-500 dark:text-gray-400",children:[e.jsx(B,{size:11}),"v",t.version_int]}),e.jsx("span",{className:"text-sm font-medium text-gray-800 dark:text-gray-100 truncate",children:t.name}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded uppercase font-semibold ${t.kind==="auto"?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300":"bg-gray-100 text-gray-700 dark:bg-slate-700 dark:text-gray-300"}`,children:t.kind}),o&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded uppercase font-semibold bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",children:"initial"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-gray-500 dark:text-gray-400",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(V,{size:11}),ie(t.created_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx($,{size:11}),t.user_id!==null?`user #${t.user_id}`:"anonymous"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Y,{size:11}),t.node_count," nodes / ",t.edge_count," edges"]})]}),t.note&&e.jsxs("div",{className:"mt-1 text-xs text-gray-600 dark:text-gray-300 italic truncate",children:["“",t.note,"”"]}),!o&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(w,{icon:e.jsx(C,{size:10}),label:"added",count:d.nodes_added.length,tone:"add"}),e.jsx(w,{icon:e.jsx(z,{size:10}),label:"removed",count:d.nodes_removed.length,tone:"remove"}),e.jsx(w,{icon:e.jsx(I,{size:10}),label:"modified",count:d.nodes_modified.length,tone:"modify"}),n===0&&e.jsx("span",{className:"text-[11px] text-gray-400 italic",children:"no node-level changes"})]})]})]}),e.jsx(ne,{expanded:s,diff:d,totalChanged:n})]})},ne=({expanded:t,diff:r,totalChanged:s})=>e.jsx(e.Fragment,{children:t&&s>0&&e.jsxs("div",{className:"px-10 pb-3 pt-1 space-y-2 bg-gray-50/60 dark:bg-slate-900/40",children:[e.jsx(A,{title:"Added",items:r.nodes_added,tone:"add"}),e.jsx(A,{title:"Removed",items:r.nodes_removed,tone:"remove"}),e.jsx(A,{title:"Modified",items:r.nodes_modified,tone:"modify"})]})}),le=({state:t})=>{const{isLoading:r,datasetId:s,data:i,emptyStateText:d,filteredEntries:n}=t;return e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden",children:r?e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:"Loading audit trail…"}):s?!i||i.entries.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:d}):n.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:d}):e.jsx("div",{children:n.map((o,x)=>e.jsx(oe,{entry:o,isFirst:x===n.length-1},o.id))}):e.jsx("div",{className:"p-8 text-center text-sm text-gray-500 dark:text-gray-400",children:"Pick a dataset to view its save history."})})},ce=({summary:t})=>e.jsx(e.Fragment,{children:t&&t.saves>0&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mb-4",children:[e.jsx(f,{label:"Saves",value:t.saves,icon:e.jsx(J,{size:14})}),e.jsx(f,{label:"Users",value:t.users,icon:e.jsx($,{size:14})}),e.jsx(f,{label:"Nodes added",value:t.added,icon:e.jsx(C,{size:14}),tone:"add"}),e.jsx(f,{label:"Nodes removed",value:t.removed,icon:e.jsx(z,{size:14}),tone:"remove"}),e.jsx(f,{label:"Nodes modified",value:t.modified,icon:e.jsx(I,{size:14}),tone:"modify"})]})}),f=({label:t,value:r,icon:s,tone:i})=>{const d=i==="add"?"text-emerald-600 dark:text-emerald-400":i==="remove"?"text-rose-600 dark:text-rose-400":i==="modify"?"text-amber-600 dark:text-amber-400":"text-gray-700 dark:text-gray-200";return e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wide text-gray-500 dark:text-gray-400 font-medium",children:[s,t]}),e.jsx("div",{className:`mt-1 text-xl font-semibold ${d}`,children:r})]})};function xe(){const{data:t,isLoading:r}=O(),[s,i]=l.useState(""),[d,n]=l.useState(50),[o,x]=l.useState("all"),[m,y]=l.useState("all"),[h,u]=l.useState(""),[g,p]=l.useState(""),[a,j]=l.useState(null),[k,_]=l.useState(!1),[L,T]=l.useState(null);l.useEffect(()=>{if(!s&&t&&t.length>0){const c=t[0];c&&i(S(c))}},[t,s]);const v=l.useRef(0),N=l.useCallback(async()=>{if(!s)return;const c=++v.current;_(!0),T(null);try{const b=await U.audit(s,d,Z({actorFilter:o,kindFilter:m,fromTime:h,toTime:g}));if(c!==v.current)return;j(b)}catch(b){if(c!==v.current)return;const F=b.message||"Failed to load audit trail";T(F),q.error(F)}finally{c===v.current&&_(!1)}},[s,d,o,m,h,g]);l.useEffect(()=>{N()},[N]);const R=l.useMemo(()=>ee(a),[a]),P=l.useMemo(()=>{var c,b;return{hasAnonymous:((c=a==null?void 0:a.facets)==null?void 0:c.has_anonymous_actor)??!1,userIds:((b=a==null?void 0:a.facets)==null?void 0:b.actors)??[]}},[a]),D=l.useMemo(()=>{var c;return((c=a==null?void 0:a.facets)==null?void 0:c.kinds)??[]},[a]),E=l.useMemo(()=>{const c=t==null?void 0:t.find(b=>S(b)===s);return(c==null?void 0:c.name)??"this dataset"},[t,s]),M=te(a,E,d,{actorFilter:o,kindFilter:m,fromTime:h,toTime:g});return{datasets:t,datasetsLoading:r,datasetId:s,setDatasetId:i,limit:d,setLimit:n,actorFilter:o,setActorFilter:x,kindFilter:m,setKindFilter:y,fromTime:h,setFromTime:u,toTime:g,setToTime:p,data:a,isLoading:k,error:L,load:N,summary:R,actorOptions:P,kindOptions:D,...M}}const be=()=>{const t=xe(),{load:r,isLoading:s,datasetId:i,data:d,error:n,summary:o,historyScopeText:x,historyMetaText:m}=t;return e.jsxs("div",{className:"p-6 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2",children:[e.jsx(Q,{className:"w-6 h-6 text-violet-500"}),"Pipeline Audit Log"]}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Chronological history of canvas saves. Each entry shows who, when, and which nodes changed vs. the previous save."})]}),e.jsxs("button",{type:"button",onClick:()=>void r(),disabled:s||!i,className:"inline-flex items-center gap-2 px-3 py-2 text-sm font-medium rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800 hover:bg-gray-50 dark:hover:bg-slate-700 disabled:opacity-50",children:[e.jsx(W,{className:`w-4 h-4 ${s?"animate-spin":""}`}),"Refresh"]})]}),e.jsx(ae,{state:t}),d&&e.jsx("p",{className:"mb-4 text-xs text-gray-500 dark:text-gray-400",children:"Actor, action kind and time filters apply across the full history before the page limit."}),n&&e.jsxs("div",{className:"mb-4 flex items-start gap-2 p-3 rounded border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm",children:[e.jsx(X,{className:"w-4 h-4 shrink-0 mt-0.5"}),e.jsx("span",{children:n})]}),e.jsx(ce,{summary:o}),e.jsx(le,{state:t}),x&&e.jsxs("p",{className:"mt-3 text-xs text-gray-500 dark:text-gray-400 text-center",children:[x," ",m]})]})};export{be as AuditLogPage}; diff --git a/static/ml_canvas/assets/BaseModelParamsEditor-CrBgCypf.js b/static/ml_canvas/assets/BaseModelParamsEditor-CyS6uUs-.js similarity index 98% rename from static/ml_canvas/assets/BaseModelParamsEditor-CrBgCypf.js rename to static/ml_canvas/assets/BaseModelParamsEditor-CyS6uUs-.js index 1645668e5..ebb5b8f35 100644 --- a/static/ml_canvas/assets/BaseModelParamsEditor-CrBgCypf.js +++ b/static/ml_canvas/assets/BaseModelParamsEditor-CyS6uUs-.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as b,k as j,l as v}from"./vendor-utils-_6D5wMFs.js";import{j as k}from"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";const N={classification:{logistic_regression:"logistic_regression",random_forest:"random_forest_classifier",extra_trees:"extra_trees_classifier",gradient_boosting:"gradient_boosting_classifier",hist_gradient_boosting:"hist_gradient_boosting_classifier",adaboost:"adaboost_classifier",decision_tree:"decision_tree_classifier",gaussian_nb:"gaussian_nb",sgd_classifier:"sgd_classifier",svc:"svc",knn:"k_neighbors_classifier",xgboost:"xgboost_classifier",lightgbm:"lgbm_classifier"},regression:{linear_regression:"linear_regression",ridge:"ridge_regression",lasso:"lasso_regression",elasticnet:"elasticnet_regression",random_forest:"random_forest_regressor",extra_trees:"extra_trees_regressor",gradient_boosting:"gradient_boosting_regressor",hist_gradient_boosting:"hist_gradient_boosting_regressor",adaboost:"adaboost_regressor",decision_tree:"decision_tree_regressor",svr:"svr",knn:"k_neighbors_regressor",xgboost:"xgboost_regressor",lightgbm:"lgbm_regressor"}};function h(l,r){return l.type==="number"?r===""?void 0:Number(r):l.type==="boolean"?r==="true":r===""?void 0:r}function S({id:l,def:r,value:o,onChange:u}){const n=o??"",g="w-full border border-gray-300 dark:border-gray-600 rounded p-1.5 text-xs bg-white dark:bg-gray-800 dark:text-gray-100";return r.type==="select"&&r.options?e.jsxs("select",{id:l,className:g,value:String(n),onChange:t=>{u(h(r,t.target.value))},children:[e.jsx("option",{value:"",children:"default"}),r.options.map(t=>e.jsx("option",{value:String(t.value),children:t.label},String(t.value)))]}):r.type==="boolean"?e.jsxs("select",{id:l,className:g,value:n===""?"":String(n),onChange:t=>{u(t.target.value===""?void 0:t.target.value==="true")},children:[e.jsx("option",{value:"",children:"default"}),e.jsx("option",{value:"true",children:"True"}),e.jsx("option",{value:"false",children:"False"})]}):e.jsx("input",{id:l,type:"number",className:g,min:r.min,max:r.max,step:r.step,value:String(n),placeholder:"default",onChange:t=>{u(h(r,t.target.value))}})}function y({label:l,defs:r,values:o,onParam:u}){const[n,g]=b.useState(!1),t=b.useId(),x=Object.keys(o).length,_=r.filter(i=>i.type!=="multiselect");return e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":n,"aria-controls":`${t}-params`,onClick:()=>{g(!n)},className:"w-full flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800/50 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:[e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:l}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[x>0&&e.jsxs("span",{className:"text-[10px] text-purple-600 dark:text-purple-300",children:[x," set"]}),e.jsx(v,{className:`w-3.5 h-3.5 text-gray-400 transition-transform ${n?"rotate-90":""}`})]})]}),n&&e.jsxs("div",{id:`${t}-params`,role:"group","aria-label":l,className:"p-2 grid grid-cols-2 gap-2 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700",children:[_.length===0&&e.jsx("p",{className:"col-span-2 text-[11px] text-gray-400",children:"No tunable parameters."}),_.map(i=>e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${t}-${i.name}`,className:"block text-[10px] text-gray-500 mb-0.5 truncate",title:i.description,children:i.label}),e.jsx(S,{id:`${t}-${i.name}`,def:i,value:o[i.name],onChange:m=>{u(i.name,m)}})]},i.name))]})]})}function C({task:l,baseEstimators:r,finalEstimator:o,optionLabels:u,baseParams:n,finalParams:g,onChange:t}){const[x,_]=b.useState({}),i=b.useMemo(()=>{const s=new Set(r);return o&&s.add(o),Array.from(s)},[r,o]);b.useEffect(()=>{let s=!1;const c=i.filter(a=>!(a in x));if(c.length!==0)return Promise.all(c.map(async a=>{const d=N[l][a];if(!d)return[a,[]];try{const p=await k.getHyperparameters(d);return[a,p]}catch{return[a,[]]}})).then(a=>{s||_(d=>({...d,...Object.fromEntries(a)}))}),()=>{s=!0}},[i,l,x]);const m=(s,c,a)=>{const d={...n[s]??{}};a===void 0||a===""?delete d[c]:d[c]=a;const p={...n};Object.keys(d).length===0?delete p[s]:p[s]=d,t(p,g)},f=(s,c)=>{const a={...g};c===void 0||c===""?delete a[s]:a[s]=c,t(n,a)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(j,{className:"w-3.5 h-3.5 text-purple-500"}),e.jsx("span",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:"Optional — leave blank to use each model's defaults."})]}),r.map(s=>e.jsx(y,{label:u[s]??s,defs:x[s]??[],values:n[s]??{},onParam:(c,a)=>{m(s,c,a)}},s)),o&&e.jsx(y,{label:`Final · ${u[o]??o}`,defs:x[o]??[],values:g,onParam:f},`final-${o}`)]})}export{C as BaseModelParamsEditor}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as b,k as j,l as v}from"./vendor-utils-_6D5wMFs.js";import{j as k}from"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";const N={classification:{logistic_regression:"logistic_regression",random_forest:"random_forest_classifier",extra_trees:"extra_trees_classifier",gradient_boosting:"gradient_boosting_classifier",hist_gradient_boosting:"hist_gradient_boosting_classifier",adaboost:"adaboost_classifier",decision_tree:"decision_tree_classifier",gaussian_nb:"gaussian_nb",sgd_classifier:"sgd_classifier",svc:"svc",knn:"k_neighbors_classifier",xgboost:"xgboost_classifier",lightgbm:"lgbm_classifier"},regression:{linear_regression:"linear_regression",ridge:"ridge_regression",lasso:"lasso_regression",elasticnet:"elasticnet_regression",random_forest:"random_forest_regressor",extra_trees:"extra_trees_regressor",gradient_boosting:"gradient_boosting_regressor",hist_gradient_boosting:"hist_gradient_boosting_regressor",adaboost:"adaboost_regressor",decision_tree:"decision_tree_regressor",svr:"svr",knn:"k_neighbors_regressor",xgboost:"xgboost_regressor",lightgbm:"lgbm_regressor"}};function h(l,r){return l.type==="number"?r===""?void 0:Number(r):l.type==="boolean"?r==="true":r===""?void 0:r}function S({id:l,def:r,value:o,onChange:u}){const n=o??"",g="w-full border border-gray-300 dark:border-gray-600 rounded p-1.5 text-xs bg-white dark:bg-gray-800 dark:text-gray-100";return r.type==="select"&&r.options?e.jsxs("select",{id:l,className:g,value:String(n),onChange:t=>{u(h(r,t.target.value))},children:[e.jsx("option",{value:"",children:"default"}),r.options.map(t=>e.jsx("option",{value:String(t.value),children:t.label},String(t.value)))]}):r.type==="boolean"?e.jsxs("select",{id:l,className:g,value:n===""?"":String(n),onChange:t=>{u(t.target.value===""?void 0:t.target.value==="true")},children:[e.jsx("option",{value:"",children:"default"}),e.jsx("option",{value:"true",children:"True"}),e.jsx("option",{value:"false",children:"False"})]}):e.jsx("input",{id:l,type:"number",className:g,min:r.min,max:r.max,step:r.step,value:String(n),placeholder:"default",onChange:t=>{u(h(r,t.target.value))}})}function y({label:l,defs:r,values:o,onParam:u}){const[n,g]=b.useState(!1),t=b.useId(),x=Object.keys(o).length,_=r.filter(i=>i.type!=="multiselect");return e.jsxs("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button","aria-expanded":n,"aria-controls":`${t}-params`,onClick:()=>{g(!n)},className:"w-full flex items-center justify-between p-2 bg-gray-50 dark:bg-gray-800/50 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:[e.jsx("span",{className:"text-xs font-medium text-gray-700 dark:text-gray-200",children:l}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[x>0&&e.jsxs("span",{className:"text-[10px] text-purple-600 dark:text-purple-300",children:[x," set"]}),e.jsx(v,{className:`w-3.5 h-3.5 text-gray-400 transition-transform ${n?"rotate-90":""}`})]})]}),n&&e.jsxs("div",{id:`${t}-params`,role:"group","aria-label":l,className:"p-2 grid grid-cols-2 gap-2 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700",children:[_.length===0&&e.jsx("p",{className:"col-span-2 text-[11px] text-gray-400",children:"No tunable parameters."}),_.map(i=>e.jsxs("div",{children:[e.jsx("label",{htmlFor:`${t}-${i.name}`,className:"block text-[10px] text-gray-500 mb-0.5 truncate",title:i.description,children:i.label}),e.jsx(S,{id:`${t}-${i.name}`,def:i,value:o[i.name],onChange:m=>{u(i.name,m)}})]},i.name))]})]})}function C({task:l,baseEstimators:r,finalEstimator:o,optionLabels:u,baseParams:n,finalParams:g,onChange:t}){const[x,_]=b.useState({}),i=b.useMemo(()=>{const s=new Set(r);return o&&s.add(o),Array.from(s)},[r,o]);b.useEffect(()=>{let s=!1;const c=i.filter(a=>!(a in x));if(c.length!==0)return Promise.all(c.map(async a=>{const d=N[l][a];if(!d)return[a,[]];try{const p=await k.getHyperparameters(d);return[a,p]}catch{return[a,[]]}})).then(a=>{s||_(d=>({...d,...Object.fromEntries(a)}))}),()=>{s=!0}},[i,l,x]);const m=(s,c,a)=>{const d={...n[s]??{}};a===void 0||a===""?delete d[c]:d[c]=a;const p={...n};Object.keys(d).length===0?delete p[s]:p[s]=d,t(p,g)},f=(s,c)=>{const a={...g};c===void 0||c===""?delete a[s]:a[s]=c,t(n,a)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(j,{className:"w-3.5 h-3.5 text-purple-500"}),e.jsx("span",{className:"text-[11px] text-gray-500 dark:text-gray-400",children:"Optional — leave blank to use each model's defaults."})]}),r.map(s=>e.jsx(y,{label:u[s]??s,defs:x[s]??[],values:n[s]??{},onParam:(c,a)=>{m(s,c,a)}},s)),o&&e.jsx(y,{label:`Final · ${u[o]??o}`,defs:x[o]??[],values:g,onParam:f},`final-${o}`)]})}export{C as BaseModelParamsEditor}; diff --git a/static/ml_canvas/assets/DataDriftPage-Dpmcy0d5.js b/static/ml_canvas/assets/DataDriftPage-BjX1Ahxl.js similarity index 99% rename from static/ml_canvas/assets/DataDriftPage-Dpmcy0d5.js rename to static/ml_canvas/assets/DataDriftPage-BjX1Ahxl.js index 385d24740..ecb8c9dfc 100644 --- a/static/ml_canvas/assets/DataDriftPage-Dpmcy0d5.js +++ b/static/ml_canvas/assets/DataDriftPage-BjX1Ahxl.js @@ -1,2 +1,2 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a0 as fe,j as T,a1 as je,f as W,D as ke,x as ye,C as ve,a2 as Ne,a as u,T as M,S as Z,a3 as we,X as A,_ as _e,b as V,e as P,N as Se,a4 as Ce,w as L,a5 as De,a6 as Re,a7 as ze,a8 as Y,a9 as Ee,aa as Le,ab as ee,ac as C,ad as Te,ae as Ae,U as Fe,af as $e,ag as Me,z as Pe,ah as Oe,ai as Ie,aj as Ke,O as Ue,c as He,ak as qe}from"./vendor-utils-_6D5wMFs.js";import{DEFAULT_DRIFT_THRESHOLDS as $,driftThresholdError as Be}from"./driftThresholds-BnFBRCeO.js";import{R as F,b as We,C as Ve,M as Ye,L as Xe,E as te,m as D,u as Je}from"./index-BXksgzya.js";import{R as se,ag as Ge,C as re,X as ae,Y as ne,T as le,ah as ie,ai as X,B as Qe,h as J}from"./vendor-charts-CwfdE1jD.js";import{F as G}from"./FormField-BxGvOnTr.js";const Ze={none:{label:"No drift",classes:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400 border-green-200 dark:border-green-800"},warning:{label:"Warning",classes:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400 border-amber-200 dark:border-amber-800"},critical:{label:"Critical",classes:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400 border-red-200 dark:border-red-800"}},oe=({severity:t})=>{const s=Ze[t],r=t==="critical"?fe:t==="warning"?T:je;return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-xs font-medium ${s.classes}`,children:[e.jsx(r,{size:12,"aria-hidden":"true"}),s.label]})},et={new:{label:"New",classes:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400 border-blue-200 dark:border-blue-800"},acknowledged:{label:"Acknowledged",classes:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400 border-purple-200 dark:border-purple-800"},resolved:{label:"Resolved",classes:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300 border-slate-200 dark:border-slate-700"},reopened:{label:"Reopened",classes:"bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400 border-orange-200 dark:border-orange-800"}},O=({status:t})=>{const s=et[t];return e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full border text-xs font-medium ${s.classes}`,children:s.label})};function tt({detail:t,filters:s}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(oe,{severity:t.severity}),e.jsx(O,{status:t.status}),t.evaluation_status!=="completed"&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-xs font-medium bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300 border-slate-200 dark:border-slate-700",children:[e.jsx(W,{size:12,"aria-hidden":"true"}),t.evaluation_status==="no_baseline"?"No baseline":"Evaluation failed"]})]}),t.evaluation_status!=="completed"&&t.error_message&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300 text-sm",children:[e.jsx(W,{size:16,className:"shrink-0 mt-0.5","aria-hidden":"true"}),e.jsx("span",{children:t.error_message})]}),e.jsx(st,{detail:t}),e.jsx(rt,{detail:t,filters:s})]})}function st({detail:t}){var s;return e.jsxs("dl",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Detected"}),e.jsx("dd",{className:"font-medium",children:((s=t.created_at)==null?void 0:s.replace("T"," ").slice(0,16))??"Unknown"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Threshold version"}),e.jsxs("dd",{className:"font-medium",children:[t.threshold_version!=null?`v${t.threshold_version}`:"—",t.threshold_version!=null&&e.jsxs("span",{className:"block text-[11px] font-normal text-gray-400",children:["PSI ",t.threshold_psi," · KS ",t.threshold_ks," · Wasserstein"," ",t.threshold_wasserstein," · KL ",t.threshold_kl]})]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Drifted features"}),e.jsx("dd",{className:"font-medium",children:t.drifted_columns_count!=null&&t.total_columns!=null?`${t.drifted_columns_count} / ${t.total_columns}`:"—"})]})]})}function rt({detail:t,filters:s}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[e.jsx(F,{recordRef:{kind:"job",jobId:t.job_id},origin:"/drift",filters:s}),t.model_version&&e.jsx(F,{recordRef:{kind:"modelVersion",jobId:t.job_id,version:t.model_version},origin:"/drift",filters:s}),t.deployment_id!=null&&e.jsx(F,{recordRef:{kind:"deployment",deploymentId:t.deployment_id},origin:"/drift",filters:s})]})}function at({alertId:t,evaluationStatus:s,evidenceRows:r}){return s!=="completed"?null:e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2",children:"Feature evidence"}),r.length===0?e.jsx(We,{title:"No evidence recorded",description:"This alert has no retained per-feature drift evidence."}):e.jsx(Ve,{caption:`Per-feature drift evidence for alert #${t??""}`,filename:`drift-alert-${t??"unknown"}-evidence`,columns:[{key:"column",label:"Feature"},{key:"drifted",label:"Drifted"},{key:"psi",label:"PSI"},{key:"wasserstein",label:"Wasserstein"},{key:"ks_statistic",label:"KS statistic"},{key:"ks_p_value",label:"KS p-value"}],rows:r,defaultOpen:!0})]})}function nt({entries:t}){return e.jsxs(e.Fragment,{children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2 flex items-center gap-1.5",children:[e.jsx(ke,{size:12})," History"]}),t.length===0?e.jsx("p",{className:"text-xs text-gray-400 italic",children:"No disposition changes recorded yet."}):e.jsx("ul",{className:"space-y-1.5",children:t.map((s,r)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-gray-600 dark:text-gray-300",children:[e.jsx(O,{status:s.status}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ye,{size:11})," ",s.actor]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-gray-400",children:[e.jsx(ve,{size:11})," ",s.at.replace("T"," ").slice(0,16)]}),s.note&&e.jsxs("span",{className:"italic",children:['"',s.note,'"']})]},r))})]})}const Q={new:["acknowledge"],acknowledged:["resolve","reopen"],resolved:["reopen"],reopened:["acknowledge"]},lt={acknowledge:"Acknowledge",resolve:"Resolve",reopen:"Reopen"};function it({detail:t,actor:s,note:r,actionError:a,error:n,actionPending:l,setActor:d,setNote:p,handleAction:o}){return e.jsxs("div",{className:"border-t border-gray-200 dark:border-gray-700 pt-4",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2 flex items-center gap-1.5",children:[e.jsx(Ne,{size:13})," Disposition"]}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mb-3",children:t.owner?e.jsxs(e.Fragment,{children:["Currently ",e.jsx("strong",{children:t.status})," by ",e.jsx("strong",{children:t.owner}),"."]}):e.jsx(e.Fragment,{children:"No disposition recorded yet — acknowledge to claim this alert."})}),(Q[t.status]??[]).length>0&&e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(G,{label:"Your name",required:!0,children:x=>e.jsx("input",{...x,type:"text",value:s,onChange:b=>d(b.target.value),placeholder:"e.g. alice",className:"w-full text-sm px-3 py-1.5 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800"})}),e.jsx(G,{label:"Note",hint:"Optional context for the audit trail",children:x=>e.jsx("input",{...x,type:"text",value:r,onChange:b=>p(b.target.value),placeholder:"Optional",className:"w-full text-sm px-3 py-1.5 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800"})})]}),a&&e.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:a}),n&&e.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:n}),e.jsx("div",{className:"flex gap-2",children:(Q[t.status]??[]).map(x=>e.jsx("button",{type:"button",disabled:l,onClick:()=>void o(x),className:"px-3 py-1.5 text-sm font-medium rounded-md action-primary disabled:opacity-50 disabled:cursor-not-allowed",children:lt[x]},x))})]}),e.jsx(nt,{entries:t.disposition_history})]})}function ot(t){return t!=null&&t.column_drifts?Object.entries(t.column_drifts).map(([s,r])=>{const a=Object.fromEntries(r.metrics.map(n=>[n.metric,n.value]));return{column:s,drifted:r.drift_detected?"Yes":"No",psi:a.psi!=null?Number(a.psi.toFixed(4)):null,wasserstein:a.wasserstein_distance!=null?Number(a.wasserstein_distance.toFixed(4)):null,ks_statistic:a.ks_statistic!=null?Number(a.ks_statistic.toFixed(4)):null,ks_p_value:a.ks_test_p_value!=null?Number(a.ks_test_p_value.toFixed(4)):null}}):[]}const dt=({alertId:t,detail:s,loading:r,error:a,actionPending:n,onApplyDisposition:l,onRetry:d,onClose:p,filters:o})=>{const[x,b]=u.useState(""),[h,j]=u.useState(""),[f,m]=u.useState(null),c=u.useRef(0),i=u.useRef(h);i.current=h,u.useEffect(()=>()=>{c.current+=1},[t]);const g=async v=>{if(!x.trim()){m("Enter your name so the disposition records who made it.");return}m(null);const w=c.current;await l(v,x.trim(),h.trim()||void 0)&&w===c.current&&i.current===h&&j("")},k=ot(s);return e.jsxs(Ye,{isOpen:t!==null,onClose:p,title:t!==null?`Drift alert #${t}`:void 0,size:"3xl",children:[r&&e.jsx(Xe,{message:"Loading drift alert…"}),!r&&a&&!s&&e.jsx(te,{error:a,onRetry:d}),!r&&s&&e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(tt,{detail:s,filters:o}),e.jsx(at,{alertId:t,evaluationStatus:s.evaluation_status,evidenceRows:k}),e.jsx(it,{detail:s,actor:x,note:h,actionError:f,error:a,actionPending:n,setActor:b,setNote:j,handleAction:g})]})]})},ct=({history:t,onInvestigate:s})=>t.length===0?null:e.jsxs("div",{className:"bg-white dark:bg-slate-800 rounded-lg shadow border dark:border-slate-700 mt-6",children:[e.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-slate-700",children:e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(M,{size:18})," Alert History",e.jsxs("span",{className:"text-xs font-normal text-gray-400 ml-1",children:["(",t.length," checks)"]})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-xs uppercase tracking-wider text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-slate-700",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Detected"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Severity"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Evaluation"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Threshold"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Owner"}),e.jsx("th",{className:"px-4 py-2 font-medium sr-only",children:"Actions"})]})}),e.jsx("tbody",{children:t.map(r=>{var a;return e.jsxs("tr",{className:"border-b border-gray-100 dark:border-slate-700/60 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 whitespace-nowrap",children:((a=r.created_at)==null?void 0:a.replace("T"," ").slice(0,16))??"Unknown"}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(oe,{severity:r.severity})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(O,{status:r.status})}),e.jsx("td",{className:"px-4 py-2 capitalize",children:r.evaluation_status.replace("_"," ")}),e.jsx("td",{className:"px-4 py-2",children:r.threshold_version!=null?`v${r.threshold_version}`:"—"}),e.jsx("td",{className:"px-4 py-2",children:r.owner??"—"}),e.jsx("td",{className:"px-4 py-2 text-right",children:e.jsxs("button",{type:"button",onClick:()=>s(r.id),className:"inline-flex items-center gap-1 px-2 py-1 rounded text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 text-xs font-medium",children:[e.jsx(Z,{size:12,"aria-hidden":"true"}),"Investigate"]})})]},r.id)})})]})})]}),xt=({showOnlyDrifted:t,onToggleDrifted:s,sortConfig:r,onClearSort:a,onExport:n})=>e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsxs("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors border ${t?"bg-red-50 dark:bg-red-900/30 border-red-200 dark:border-red-700 text-red-700 dark:text-red-300":"border-gray-200 dark:border-slate-600 text-gray-500 dark:text-slate-400 hover:bg-gray-50 dark:hover:bg-slate-700"}`,children:[e.jsx(we,{size:12}),t?"Showing drifted only":"Show only drifted"]}),r&&e.jsxs("button",{onClick:a,className:"flex items-center gap-1 px-2 py-1.5 rounded-md text-xs text-gray-400 hover:text-gray-600 dark:hover:text-slate-300 transition-colors",children:[e.jsx(A,{size:11})," Clear sort"]}),e.jsx("div",{className:"ml-auto",children:e.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border border-gray-200 dark:border-slate-600 text-gray-500 dark:text-slate-400 hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors",title:"Download drift report as CSV",children:[e.jsx(_e,{size:12})," Export CSV"]})})]}),ut=({history:t})=>{if(t.length<=1)return null;const s=[...t].reverse().map(r=>{var l;const a=r.summary?Object.values(r.summary):null,n=a?a.filter(d=>d.drifted).length:null;return{date:((l=r.created_at)==null?void 0:l.split("T")[0])??"",drifted:n,pct:a!=null&&a.length?Math.round((n??0)/a.length*100):null}});return e.jsxs("div",{className:"bg-white dark:bg-slate-800 p-6 rounded-lg shadow border dark:border-slate-700 mt-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4 flex items-center gap-2",children:[e.jsx(M,{size:18})," Drift History",e.jsxs("span",{className:"text-xs font-normal text-gray-400 ml-1",children:["(",t.length," checks)"]})]}),e.jsx("div",{className:"h-[280px]",children:e.jsx(se,{width:"100%",height:"100%",children:e.jsxs(Ge,{data:s,margin:{top:5,right:30,left:0,bottom:5},children:[e.jsx(re,{strokeDasharray:"3 3",className:"stroke-gray-200 dark:stroke-slate-700",vertical:!1}),e.jsx(ae,{dataKey:"date",tick:{fill:"hsl(var(--muted-foreground))",fontSize:11},tickLine:!1,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ne,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:11},tickLine:!1,axisLine:!1}),e.jsx(le,{contentStyle:{backgroundColor:"hsl(var(--popover))",borderColor:"hsl(var(--border))",color:"hsl(var(--popover-foreground))",borderRadius:"6px"},itemStyle:{color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--muted-foreground))"},formatter:(r,a)=>a==="Drifted Features"?[r,a]:a==="Drift %"?[`${r}%`,a]:[r,a]}),e.jsx(ie,{verticalAlign:"top",height:36,iconType:"circle"}),e.jsx(X,{type:"monotone",dataKey:"drifted",name:"Drifted Features",stroke:"#ef4444",strokeWidth:2,dot:{r:3,fill:"#ef4444"}}),e.jsx(X,{type:"monotone",dataKey:"pct",name:"Drift %",stroke:"#f59e0b",strokeWidth:2,dot:{r:3,fill:"#f59e0b"},strokeDasharray:"5 5"})]})})})]})},R=({label:t,tooltip:s,icon:r})=>e.jsxs("div",{className:"group relative flex items-center gap-1 cursor-help",children:[e.jsx("span",{className:"border-b border-dotted border-gray-400",children:t}),r&&e.jsx("span",{className:"text-gray-400",children:r}),e.jsxs("div",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-2 w-64 p-2 bg-slate-900 text-white text-xs rounded shadow-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50 text-center pointer-events-none",children:[s,e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 -mb-1 border-4 border-transparent border-b-slate-900"})]})]});function z(t){return t!=null&&Number.isFinite(t)}const mt=({values:t,threshold:s,width:r=64,height:a=20})=>{if(t.length<2)return e.jsx("span",{className:"text-[10px] text-gray-400",children:"—"});const n=t.filter(z);if(!n.length)return e.jsx("span",{className:"text-[10px] text-gray-400",title:"PSI unavailable for all checks",children:"—"});const l=Math.min(...n),p=Math.max(...n)-l||1,o=[];let x=[];const b=t.map((i,g)=>{if(!z(i))return x=[],null;x.length||o.push(x);const k={x:g/(t.length-1)*r,y:a-(i-l)/p*(a-4)-2};return x.push(`${k.x},${k.y}`),k}),h=t[t.length-1],j=z(h),f=z(s),m=j&&f?h>s?"#ef4444":"#22c55e":"#94a3b8",c=`PSI history: ${t.length-n.length} missing checks; latest PSI ${j?h:"unavailable"}; threshold ${f?s:"unavailable"}`;return e.jsxs("svg",{width:r,height:a,className:"inline-block",role:"img","aria-label":c,children:[e.jsx("title",{children:c}),o.map((i,g)=>e.jsx("polyline",{points:i.join(" "),fill:"none",stroke:"#3b82f6",strokeWidth:"1.5",strokeLinejoin:"round"},g)),b.map((i,g)=>i&&e.jsx("circle",{cx:i.x,cy:i.y,r:"2",fill:g===t.length-1?m:"#3b82f6"},g))]})},pt={wasserstein:"wasserstein_distance",psi:"psi",kl:"kl_divergence",ks:"ks_statistic"},ht=(t,s,r)=>{const a=(n,l)=>{var d;return((d=n.metrics.find(p=>p.metric===l||l==="psi"&&p.metric==="psi_categorical"))==null?void 0:d.value)??0};return[...t].sort((n,l)=>{let d=0;switch(s.key){case"column":d=n.column.localeCompare(l.column);break;case"status":d=(n.drift_detected?1:0)-(l.drift_detected?1:0);break;case"risk":d=((r==null?void 0:r[n.column])??0)-((r==null?void 0:r[l.column])??0);break;default:{const p=pt[s.key];p&&(d=a(n,p)-a(l,p))}}return s.dir==="asc"?d:-d})};function gt(t,s,r){let a=Object.values(t.column_drifts);return s&&(a=a.filter(n=>n.drift_detected)),r&&(a=ht(a,r,t.feature_importances)),a}const bt=({active:t,dir:s})=>t?s==="asc"?e.jsx(Re,{size:11}):e.jsx(ze,{size:11}):e.jsx(De,{size:11,className:"opacity-30"}),ft=({distribution:t})=>e.jsxs("div",{className:"h-[350px] w-full bg-white dark:bg-slate-800 p-6 rounded border dark:border-slate-700 shadow-sm",children:[e.jsxs("h4",{className:"text-sm font-semibold mb-6 flex items-center gap-2 text-slate-700 dark:text-slate-300",children:[e.jsx(ee,{size:16})," Distribution Comparison"]}),e.jsx(se,{width:"100%",height:"85%",children:e.jsxs(Qe,{data:t.bins,margin:{top:5,right:30,left:20,bottom:5},children:[e.jsx(re,{strokeDasharray:"3 3",className:"stroke-gray-200 dark:stroke-slate-700",vertical:!1}),e.jsx(ae,{dataKey:s=>`${s.bin_start.toFixed(2)}`,className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ne,{className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1}),e.jsx(le,{cursor:{fill:"rgba(0,0,0,0.05)"},contentStyle:{backgroundColor:"hsl(var(--popover))",borderColor:"hsl(var(--border))",color:"hsl(var(--popover-foreground))",borderRadius:"6px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},itemStyle:{color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--muted-foreground))",marginBottom:"0.5rem"}}),e.jsx(ie,{verticalAlign:"top",height:36,iconType:"circle"}),e.jsx(J,{dataKey:"reference_count",name:"Reference (Training)",fill:"#94a3b8",radius:[4,4,0,0],barSize:30}),e.jsx(J,{dataKey:"current_count",name:"Current (Production)",fill:"#3b82f6",radius:[4,4,0,0],barSize:30})]})})]}),jt=({importance:t,rank:s,drifted:r,maxImportance:a})=>{if(t==null)return e.jsx("span",{className:"text-xs text-gray-400",children:"—"});const n=r&&s!=null&&s<=5,l=r&&s!=null&&s<=15&&!n;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[n?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-semibold bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300",children:[e.jsx(Y,{size:12})," High"]}):l?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-semibold bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300",children:[e.jsx(Y,{size:12})," Medium"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-gray-100 dark:bg-slate-700 text-gray-500 dark:text-slate-400",children:[e.jsx(Ee,{size:12})," Low"]}),e.jsx("div",{className:"w-12 h-1.5 bg-gray-200 dark:bg-slate-700 rounded-full overflow-hidden",title:`Importance: ${(t*100/a).toFixed(0)}%`,children:e.jsx("div",{className:"h-full bg-indigo-500 rounded-full",style:{width:`${a>0?t/a*100:0}%`}})})]})};function E({metric:t,showRawDistance:s=!1}){var a;const r=s&&(t==null?void 0:t.raw_value)!=null?`Raw earth-mover distance: ${t.raw_value.toFixed(4)} in column units`:void 0;return e.jsx("td",{className:`px-6 py-4 whitespace-nowrap tabular-nums ${t!=null&&t.has_drift?"text-red-600 dark:text-red-400 font-bold":""}`,title:r,children:((a=t==null?void 0:t.value)==null?void 0:a.toFixed(4))??"—"})}function kt({col:t,ks:s,ksPValue:r}){return e.jsxs("div",{className:"flex flex-col gap-4",children:[s&&e.jsxs("div",{className:"text-xs text-gray-600 dark:text-slate-400",children:["KS statistic"," ",e.jsx("span",{className:"font-semibold tabular-nums",children:s.value.toFixed(4)})," ","vs threshold ",s.threshold.toFixed(2),r&&e.jsxs(e.Fragment,{children:[" ","· p-value"," ",e.jsx("span",{className:"tabular-nums",children:r.value<.001?"< 0.001":r.value.toFixed(3)})," ","(diagnostic only — drift is decided on the statistic)"]})]}),t.suggestions&&t.suggestions.length>0&&e.jsx("div",{className:"bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded border border-yellow-200 dark:border-yellow-800",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Le,{size:16,className:"mt-0.5 shrink-0 text-yellow-600 dark:text-yellow-400"}),e.jsx("ul",{className:"list-disc list-inside text-sm text-yellow-800 dark:text-yellow-200",children:t.suggestions.map((a,n)=>e.jsx("li",{children:a},n))})]})}),t.distribution&&e.jsx(ft,{distribution:t.distribution})]})}function yt({col:t,fi:s,isExpanded:r,maxImportance:a,toggleRow:n,hasSparklines:l,columnSparklines:d,colSpan:p}){const o=t.metrics.find(c=>c.metric==="wasserstein_distance"),x=t.metrics.find(c=>c.metric==="psi"||c.metric==="psi_categorical"),b=t.metrics.find(c=>c.metric==="kl_divergence"),h=t.metrics.find(c=>c.metric==="ks_statistic"),j=t.metrics.find(c=>c.metric==="ks_test_p_value"),f=s==null?void 0:s[t.column],m=s?Object.values(s).filter(c=>c>(f??0)).length+1:null;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:t.drift_detected?"bg-red-50 dark:bg-red-900/10":"",children:[e.jsx("td",{className:"px-6 py-4 whitespace-nowrap font-medium",children:t.column}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:t.drift_detected?e.jsxs("span",{className:"text-red-600 dark:text-red-400 flex items-center gap-1",children:[e.jsx(Se,{size:16})," Drifted"]}):e.jsxs("span",{className:"text-green-600 dark:text-green-400 flex items-center gap-1",children:[e.jsx(P,{size:16})," Stable"]})}),e.jsx(E,{metric:o,showRawDistance:!0}),e.jsx(E,{metric:x}),e.jsx(E,{metric:b}),e.jsx(E,{metric:h}),s&&e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(jt,{importance:f,rank:m,drifted:t.drift_detected,maxImportance:a})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsxs("button",{onClick:()=>n(t.column),className:"text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 flex items-center gap-1 text-sm",children:[r?e.jsx(Ce,{size:16}):e.jsx(L,{size:16}),r?"Hide":"Details"]})}),l&&e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(mt,{values:d[t.column]??[],threshold:x==null?void 0:x.threshold})})]}),r&&e.jsx("tr",{children:e.jsx("td",{colSpan:p,className:"px-6 py-4 bg-gray-50 dark:bg-slate-900/50",children:e.jsx(kt,{col:t,ks:h,ksPValue:j})})})]})}const vt=({report:t,showOnlyDrifted:s,sortConfig:r,onSort:a,columnSparklines:n})=>{const[l,d]=u.useState({});V.useEffect(()=>{d({})},[t]),V.useEffect(()=>{const c=i=>{i.key==="Escape"&&d({})};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[]);const p=c=>d(i=>({...i,[c]:!i[c]})),o=t.feature_importances,x=o?Math.max(...Object.values(o)):0,b=Object.keys(n).length>0,h=gt(t,s,r),j=(o?8:7)+(b?1:0),f=t.missing_columns.length>0||t.new_columns.length>0,m=(c,i)=>e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider cursor-pointer select-none hover:text-gray-700 dark:hover:text-slate-300",onClick:()=>a(c),children:e.jsxs("span",{className:"flex items-center gap-1",children:[i,e.jsx(bt,{active:(r==null?void 0:r.key)===c,dir:r==null?void 0:r.dir})]})});return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-gray-200 dark:divide-slate-700",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-slate-900",children:e.jsxs("tr",{children:[m("column","Column"),m("status","Status"),m("wasserstein",e.jsx(R,{label:"Wasserstein",tooltip:"Measures distance between distributions, normalized by the reference column's standard deviation so the threshold is scale-free. Lower is better. < 0.1 usually means stable.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),m("psi",e.jsx(R,{label:"PSI",tooltip:"Population Stability Index. < 0.1: Stable, < 0.2: Minor Drift, > 0.2: Significant Drift.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),m("kl",e.jsx(R,{label:"KL Div",tooltip:"Kullback-Leibler Divergence. Measures how one probability distribution diverts from a second.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),m("ks",e.jsx(R,{label:"KS Stat",tooltip:"Kolmogorov-Smirnov statistic — maximum distance between the two cumulative distributions (0–1). Unlike the p-value it does not shrink with sample size; values above the threshold (default 0.1) indicate drift.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),o&&m("risk",e.jsx(R,{label:"Risk",tooltip:"Combines drift status with feature importance. High = drifted + important feature. Helps prioritize which drifts to investigate.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:"Actions"}),b&&e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(M,{size:11})," Trend"]})})]})}),e.jsx("tbody",{className:"bg-white dark:bg-slate-800 divide-y divide-gray-200 dark:divide-slate-700",children:h.length===0&&s?e.jsx("tr",{children:e.jsxs("td",{colSpan:j,className:"px-6 py-8 text-center text-gray-500 dark:text-slate-400 text-sm",children:[e.jsx(P,{size:20,className:"inline mr-2 text-green-500"}),f?"No distribution drift among shared columns — see the schema drift above.":"No drifted columns found — all features are stable."]})}):h.map(c=>e.jsx(yt,{col:c,fi:o,isExpanded:l[c.column],maxImportance:x,toggleRow:p,hasSparklines:b,columnSparklines:n,colSpan:j},c.column))})]})})},Nt=()=>e.jsx("div",{className:"bg-white dark:bg-slate-800 rounded-lg shadow border dark:border-slate-700 p-12 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3 text-gray-500 dark:text-slate-400",children:[e.jsx(Te,{size:48,strokeWidth:1.2}),e.jsx("h2",{className:"text-lg font-medium text-gray-500 dark:text-slate-400",children:"No Drift Report Yet"}),e.jsxs("p",{className:"text-sm max-w-md",children:["Select a reference model from the dropdown above, upload current production data (CSV or Parquet), and click ",e.jsx("strong",{children:"Run Analysis"})," to compare distributions."]})]})}),wt=({file:t,onFileChange:s,invalid:r})=>{const a=u.useRef(null),n=l=>{l.target.files&&l.target.files[0]&&s(l.target.files[0])};return e.jsxs("div",{className:"flex flex-col gap-1 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("input",{ref:a,type:"file",className:"hidden",onChange:n,accept:".csv,.parquet","aria-label":"Upload current data file (CSV or Parquet)"}),t?e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2.5 border border-gray-200 dark:border-slate-600 rounded-md text-sm bg-gray-50 dark:bg-slate-900",children:[e.jsx(Ae,{size:14,className:"text-green-500 shrink-0"}),e.jsx("span",{className:"text-slate-700 dark:text-slate-300 truncate max-w-[180px]",children:t.name}),e.jsx("button",{type:"button",onClick:()=>s(null),"aria-label":`Remove ${t.name}`,className:"text-gray-400 hover:text-red-500 transition-colors ml-1",children:e.jsx(A,{size:14})})]}):e.jsxs("button",{type:"button",onClick:()=>{var l;return(l=a.current)==null?void 0:l.click()},"aria-describedby":r?"file-uploader-error":void 0,className:`flex items-center gap-2 px-3 py-2.5 border border-dashed rounded-md text-sm transition-colors ${r?"border-red-400 dark:border-red-500 text-red-600 dark:text-red-400 hover:border-red-500":"border-gray-300 dark:border-slate-600 text-gray-500 dark:text-gray-400 hover:border-blue-400 hover:text-blue-500 dark:hover:border-blue-500"}`,children:[e.jsx(Fe,{size:15}),"Upload CSV / Parquet"]})]}),r&&!t&&e.jsx("span",{id:"file-uploader-error",className:"text-[11px] text-red-600 dark:text-red-400",children:"Current data file is required."})]})};function _t({triggerRef:t,open:s,listboxId:r,invalid:a,selectedJob:n,selectedJobData:l,onSelect:d,onToggle:p}){return e.jsxs("button",{ref:t,type:"button","aria-haspopup":"listbox","aria-expanded":s,"aria-controls":r,onClick:()=>{p()},className:`w-full flex items-center gap-2 px-3 py-2.5 border rounded-md text-sm transition-colors ${a?"border-red-400 dark:border-red-500 hover:border-red-500":n?"border-blue-300 dark:border-blue-700 bg-blue-50/50 dark:bg-blue-900/20":"border-gray-200 dark:border-slate-600 hover:border-gray-300 dark:hover:border-slate-500"}`,"aria-describedby":a?"job-selector-error":void 0,children:[e.jsx($e,{size:15,className:"shrink-0 text-gray-400"}),e.jsx("span",{className:`truncate ${n?"text-slate-800 dark:text-slate-200":"text-gray-400"}`,children:l?`${l.dataset_name} (${l.job_id.slice(0,8)})`:"Select reference model..."}),n&&e.jsx("span",{role:"button",tabIndex:0,"aria-label":"Clear selected reference model",title:"Clear selection",onClick:o=>{o.stopPropagation(),d("")},onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.stopPropagation(),o.preventDefault(),d(""))},className:"ml-auto shrink-0 p-0.5 rounded hover:bg-black/5 dark:hover:bg-white/10 text-gray-400 hover:text-gray-600 dark:hover:text-slate-300",children:e.jsx(A,{size:13})}),e.jsx(L,{size:14,className:`${n?"":"ml-auto"} shrink-0 text-gray-400 transition-transform ${s?"rotate-180":""}`})]})}const St=({jobs:t,selectedJob:s,onSelect:r,invalid:a})=>{const[n,l]=u.useState(!1),[d,p]=u.useState(""),o=u.useRef(null),x=u.useRef(null),b="job-selector-listbox";u.useEffect(()=>{const m=c=>{o.current&&!o.current.contains(c.target)&&l(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),u.useEffect(()=>{if(!n)return;const m=c=>{var i;c.key==="Escape"&&(l(!1),(i=x.current)==null||i.focus())};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);const h=u.useMemo(()=>{if(!d)return t;const m=d.toLowerCase();return t.filter(c=>{var i,g,k;return c.dataset_name.toLowerCase().includes(m)||c.job_id.toLowerCase().includes(m)||((i=c.description)==null?void 0:i.toLowerCase().includes(m))||((g=c.model_type)==null?void 0:g.toLowerCase().includes(m))||((k=c.target_column)==null?void 0:k.toLowerCase().includes(m))})},[d,t]),j=u.useMemo(()=>{var c;const m={};for(const i of h){const g=((c=i.created_at)==null?void 0:c.split(" ")[0])||"Unknown";m[g]||(m[g]=[]),m[g].push(i)}return Object.entries(m).sort(([i],[g])=>g.localeCompare(i))},[h]),f=u.useMemo(()=>t.find(m=>m.job_id===s),[t,s]);return e.jsxs("div",{ref:o,className:"relative flex-1 min-w-0",children:[e.jsx(_t,{triggerRef:x,open:n,listboxId:b,invalid:a,selectedJob:s,selectedJobData:f,onSelect:r,onToggle:()=>{l(!n),p("")}}),a&&!s&&e.jsx("span",{id:"job-selector-error",className:"block mt-1 text-[11px] text-red-600 dark:text-red-400",children:"Reference job is required."}),n&&e.jsxs("div",{id:b,role:"listbox","aria-label":"Reference model jobs",className:"absolute z-50 left-0 right-0 mt-1 bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-600 rounded-md shadow-lg overflow-hidden",children:[e.jsx("div",{className:"p-2 border-b border-gray-100 dark:border-slate-700",children:e.jsxs("div",{className:"relative",children:[e.jsx(Z,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none z-10",size:14}),e.jsx("input",{type:"text",autoFocus:!0,placeholder:"Search jobs...",value:d,onChange:m=>p(m.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm border border-gray-200 dark:border-slate-600 rounded bg-gray-50 dark:bg-slate-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-blue-500"})]})}),e.jsx("div",{className:"max-h-72 overflow-y-auto",children:h.length===0?e.jsx("div",{className:"p-4 text-center text-gray-400 text-sm",children:"No jobs found"}):j.map(([m,c])=>e.jsxs("div",{children:[e.jsx("div",{className:"sticky top-0 px-3 py-1.5 text-[11px] font-semibold text-gray-500 dark:text-slate-400 bg-gray-50 dark:bg-slate-900/80 uppercase tracking-wider border-b border-gray-100 dark:border-slate-700",children:m}),c.map(i=>e.jsxs("button",{type:"button",role:"option","aria-selected":s===i.job_id,onClick:()=>{r(i.job_id),l(!1)},className:`w-full text-left px-3 py-2.5 text-sm transition-colors ${s===i.job_id?"bg-blue-50 dark:bg-blue-900/30":"hover:bg-gray-50 dark:hover:bg-slate-700/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:i.dataset_name}),e.jsx("span",{className:"text-[11px] text-gray-400 font-mono shrink-0",children:i.job_id.slice(0,8)}),i.model_type&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-300 shrink-0",children:i.model_type}),i.best_metric&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-900/40 text-green-600 dark:text-green-300 shrink-0 ml-auto tabular-nums truncate max-w-[140px]",title:i.best_metric,children:i.best_metric.split(" | ")[0]})]}),(i.target_column||i.description)&&e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 text-[11px] text-gray-500 dark:text-slate-400",children:[i.target_column&&e.jsxs("span",{children:["target: ",i.target_column]}),i.description&&e.jsxs("span",{className:"truncate italic",children:["— ",i.description]})]})]},i.job_id))]},m))})]})]})},Ct=({missingColumns:t,newColumns:s})=>{const r=t.filter(n=>n.trim()!==""),a=s.filter(n=>n.trim()!=="");return r.length===0&&a.length===0?null:e.jsxs("div",{className:"mb-6 grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.length>0&&e.jsxs("details",{className:"group bg-red-50 dark:bg-red-900/20 rounded border border-red-200 dark:border-red-800",children:[e.jsxs("summary",{className:"font-semibold text-red-800 dark:text-red-200 p-4 flex items-center gap-2 cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden",children:[e.jsx(L,{size:14,className:"transition-transform group-open:rotate-180 shrink-0"}),e.jsx(T,{size:16,className:"shrink-0"})," Missing Columns",e.jsx("span",{className:"ml-auto text-xs font-normal bg-red-200 dark:bg-red-800 px-2 py-0.5 rounded-full",children:r.length})]}),e.jsxs("div",{className:"px-4 pb-4",children:[e.jsx("p",{className:"text-[11px] text-red-600/70 dark:text-red-300/60 mb-2",children:"Columns present in reference (training) data but missing from your uploaded file."}),e.jsx("ul",{className:"list-disc list-inside text-sm text-red-700 dark:text-red-300",children:r.map(n=>e.jsx("li",{children:n},n))})]})]}),a.length>0&&e.jsxs("details",{className:"group bg-blue-50 dark:bg-blue-900/20 rounded border border-blue-200 dark:border-blue-800",children:[e.jsxs("summary",{className:"font-semibold text-blue-800 dark:text-blue-200 p-4 flex items-center gap-2 cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden",children:[e.jsx(L,{size:14,className:"transition-transform group-open:rotate-180 shrink-0"}),e.jsx(C,{size:16,className:"shrink-0"})," Extra Columns",e.jsx("span",{className:"ml-auto text-xs font-normal bg-blue-200 dark:bg-blue-800 px-2 py-0.5 rounded-full",children:a.length})]}),e.jsxs("div",{className:"px-4 pb-4",children:[e.jsx("p",{className:"text-[11px] text-blue-600/70 dark:text-blue-300/60 mb-2",children:"Columns in your uploaded file that were not in the training reference. These are excluded from distribution metrics but reported as schema changes. The model target is excluded from both checks."}),e.jsx("ul",{className:"list-disc list-inside text-sm text-blue-700 dark:text-blue-300",children:a.map(n=>e.jsx("li",{children:n},n))})]})]})]})},Dt=({job:t,onUpdateDescription:s})=>{const[r,a]=u.useState(!1),[n,l]=u.useState("");u.useEffect(()=>{a(!1)},[t.job_id]);const d=async()=>{await s(n),a(!1)};return e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-4 pb-3 text-xs text-gray-500 dark:text-slate-400",children:[t.model_type&&e.jsx("span",{className:"px-2 py-0.5 rounded bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-300 font-medium",children:t.model_type}),t.target_column&&e.jsxs("span",{children:["Target:"," ",e.jsx("span",{className:"font-medium text-slate-600 dark:text-slate-300",children:t.target_column})]}),t.n_features!=null&&e.jsxs("span",{children:[t.n_features," features"]}),t.n_rows!=null&&e.jsxs("span",{children:[t.n_rows.toLocaleString()," rows"]}),t.best_metric&&e.jsx("span",{className:"px-2 py-0.5 rounded bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-300 font-medium tabular-nums",children:t.best_metric}),e.jsx("span",{className:"border-l border-gray-200 dark:border-slate-700 h-3"}),r?e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("input",{autoFocus:!0,value:n,onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&d(),p.key==="Escape"&&a(!1)},placeholder:"Add a description...",className:"flex-1 min-w-0 px-2 py-0.5 text-xs border border-gray-200 dark:border-slate-600 rounded bg-white dark:bg-slate-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-blue-500"}),e.jsx("button",{onClick:()=>void d(),className:"text-green-500 hover:text-green-600",children:e.jsx(Me,{size:13})}),e.jsx("button",{onClick:()=>a(!1),className:"text-gray-400 hover:text-red-500",children:e.jsx(A,{size:13})})]}):e.jsxs("button",{onClick:()=>{l(t.description||""),a(!0)},className:"flex items-center gap-1 hover:text-blue-500 transition-colors group",children:[e.jsx(Pe,{size:11,className:"opacity-50 group-hover:opacity-100"}),e.jsx("span",{className:t.description?"":"italic text-gray-400",children:t.description||"Add description..."})]})]})};function Rt(t){const s=Object.values(t.column_drifts),r=s.length,a=s.filter(o=>o.drift_detected).length,n=s.flatMap(o=>{var b;const x=(b=o.metrics.find(h=>(h.metric==="psi"||h.metric==="psi_categorical")&&Number.isFinite(h.value)))==null?void 0:b.value;return x==null?[]:[{column:o.column,psi:x}]}),l=n.length>0?n.reduce((o,x)=>o+x.psi,0)/n.length:null,d=n.sort((o,x)=>x.psi-o.psi)[0],p=r>0?Math.round(a/r*100):0;return{totalCols:r,driftedCount:a,avgPsi:l,mostDrifted:d,driftedPct:p}}function zt(t){return t==null?"No PSI available":t<.1?"Stable":t<.2?"Minor drift":"Significant drift"}const Et=({report:t})=>{const{totalCols:s,driftedCount:r,avgPsi:a,mostDrifted:n,driftedPct:l}=Rt(t);return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-gray-50 dark:bg-slate-900/50 rounded-lg p-4 border dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[e.jsx(Oe,{size:13})," Total Columns"]}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:s}),e.jsxs("div",{className:"text-[11px] text-gray-400 mt-0.5",children:["Ref: ",t.reference_rows.toLocaleString()," rows | Cur: ",t.current_rows.toLocaleString()," rows"]})]}),e.jsxs("div",{className:`rounded-lg p-4 border ${r>0?"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800":"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[r>0?e.jsx(T,{size:13}):e.jsx(P,{size:13})," Drifted"]}),e.jsxs("div",{className:"text-2xl font-bold tabular-nums",children:[r," ",e.jsxs("span",{className:"text-sm font-normal text-gray-400",children:["/ ",s]})]}),e.jsxs("div",{className:"text-[11px] text-gray-400 mt-0.5",children:[l,"% of features"]})]}),e.jsxs("div",{className:"bg-gray-50 dark:bg-slate-900/50 rounded-lg p-4 border dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[e.jsx(Ie,{size:13})," Avg PSI"]}),e.jsx("div",{className:`text-2xl font-bold tabular-nums ${(a??0)>.2?"text-red-600 dark:text-red-400":(a??0)>.1?"text-amber-600 dark:text-amber-400":""}`,children:(a==null?void 0:a.toFixed(4))??"—"}),e.jsx("div",{className:"text-[11px] text-gray-400 mt-0.5",children:zt(a)})]}),e.jsxs("div",{className:"bg-gray-50 dark:bg-slate-900/50 rounded-lg p-4 border dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[e.jsx(Ke,{size:13})," Most Drifted"]}),e.jsx("div",{className:"text-lg font-bold truncate",title:n==null?void 0:n.column,children:(n==null?void 0:n.column)??"—"}),e.jsxs("div",{className:"text-[11px] text-gray-400 mt-0.5",children:["PSI: ",(n==null?void 0:n.psi.toFixed(4))??"—"]})]})]})},Lt=[{key:"psi",label:"PSI",metrics:["psi","psi_categorical"]},{key:"ks",label:"KS statistic",metrics:["ks_statistic"]},{key:"wasserstein",label:"Wasserstein",metrics:["wasserstein_distance"]},{key:"kl",label:"KL Div",metrics:["kl_divergence"]}],Tt=({thresholds:t,onChange:s,report:r})=>{const[a,n]=u.useState({}),[l,d]=u.useState({}),p=o=>{n({}),d({}),s(o)};return e.jsxs("div",{className:"px-4 pb-3 flex flex-wrap items-start gap-4 border-t border-gray-100 dark:border-slate-700 pt-3",children:[Lt.map(({key:o,label:x,metrics:b})=>{const h=a[o],j=l[o],f=[...new Set(Object.values((r==null?void 0:r.column_drifts)??{}).flatMap(i=>i.metrics.filter(g=>b.includes(g.metric)).map(g=>g.threshold)))],m=t[o]??(f.length?f.join(", "):$[o]),c=t[o]!=null?"override":f.length?"saved report":"default";return e.jsxs("div",{className:"text-xs text-gray-600 dark:text-slate-400",children:[e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"font-medium",children:x}),e.jsx("input",{type:"number",value:h??t[o]??"",min:0,max:o==="ks"?1:void 0,step:"any","aria-invalid":!!j,onChange:i=>{const g=i.target.value;n(w=>({...w,[o]:g}));const k=g.trim()?Number(g):void 0,v=i.target.validity.badInput?"Threshold must be a finite number.":k===void 0?null:Be(o,k);d(w=>({...w,[o]:v})),v||s({...t,[o]:k})},className:"w-20 px-2 py-1 border rounded bg-white dark:bg-slate-900 dark:text-white"})]}),e.jsxs("p",{className:"mt-1",children:["Effective ",x,": ",m," (",c,")"]}),j&&e.jsxs("p",{role:"alert",className:"max-w-48 text-red-600",children:[j," Not applied."]})]},o)}),e.jsx("button",{onClick:()=>p($),className:"text-xs underline",children:"Reset defaults"}),e.jsx("button",{onClick:()=>p({}),className:"text-xs underline",children:"Remove overrides"}),e.jsx("p",{className:"w-full text-xs text-gray-500",children:"Clearing a field restores its saved report threshold, or the default before analysis. Reset defaults applies defaults as overrides. New analyses use defaults for cleared fields."})]})};function At(t,s){var a,n;return(t&&typeof t=="object"&&"response"in t?(n=(a=t.response)==null?void 0:a.data)==null?void 0:n.detail:void 0)||`Failed to ${s} the drift alert.`}function Ft(t){const[s,r]=u.useState(null),[a,n]=u.useState(!1),[l,d]=u.useState(null),[p,o]=u.useState(!1),x=u.useRef(0),b=u.useRef(0),h=u.useCallback(async()=>{const f=++x.current;if(t==null){r(null),n(!1),d(null);return}n(!0),d(null);try{const m=await D.getDriftAlert(t);f===x.current&&r(m)}catch{f===x.current&&d("Failed to load drift alert detail.")}finally{f===x.current&&n(!1)}},[t]);u.useEffect(()=>(r(null),o(!1),h(),()=>{x.current+=1,b.current+=1}),[h]);const j=u.useCallback(async(f,m,c)=>{if(t==null)return null;const i=++b.current;o(!0),d(null);try{const g=await D.updateDriftAlertDisposition(t,f,m,c);return i!==b.current?null:(x.current+=1,r(g),n(!1),d(null),g)}catch(g){return i===b.current&&d(At(g,f)),null}finally{i===b.current&&o(!1)}},[t]);return{detail:s,loading:a,error:l,actionPending:p,refresh:h,applyDisposition:j}}function $t(t){const[s,r]=u.useState([]),a=u.useRef(0),n=u.useCallback(()=>{const d=++a.current;if(!t){r([]);return}D.getDriftHistory(t).then(p=>{d===a.current&&r(p)}).catch(()=>{d===a.current&&r([])})},[t]);u.useEffect(()=>(r([]),n(),()=>{a.current+=1}),[n]);const l=u.useMemo(()=>{if(s.length<2)return{};const d=[...s].reverse(),p=new Set(d.flatMap(o=>Object.keys(o.summary??{})));return Object.fromEntries([...p].map(o=>[o,d.map(x=>{var h,j;const b=(j=(h=x.summary)==null?void 0:h[o])==null?void 0:j.psi;return typeof b=="number"&&Number.isFinite(b)?b:null})]))},[s]);return{driftHistory:s,columnSparklines:l,refreshHistory:n}}function Mt(){const[t,s]=u.useState([]),[r,a]=u.useState(!1),n=u.useCallback(async()=>{a(!0);try{const d=await D.getJobs();s(d)}catch(d){console.error("Failed to fetch jobs",d)}finally{a(!1)}},[]);u.useEffect(()=>{n()},[n]);const l=u.useCallback(async(d,p)=>{try{await D.updateJobDescription(d,p),s(o=>o.map(x=>x.job_id===d?{...x,description:p}:x))}catch(o){console.error("Failed to save description",o)}},[]);return{jobs:t,refreshing:r,refresh:n,updateJobDescription:l}}function Pt(t,s){switch(t){case"psi":case"psi_categorical":return s.psi;case"ks_statistic":return s.ks;case"wasserstein_distance":return s.wasserstein;case"kl_divergence":return s.kl;default:return}}function Ot(t,s,r){let a=t.has_drift;const n=Pt(t.metric,r);if(n!=null&&(a=t.value>n),t.metric==="ks_test_p_value"){const l=s.metrics.find(d=>d.metric==="ks_statistic");l!=null&&(a=l.value>(r.ks??l.threshold))}return{...t,threshold:n??t.threshold,has_drift:a}}function It(t){const[s,r]=u.useState(null),[a,n]=u.useState(!1),[l,d]=u.useState(null),[p,o]=u.useState(null),x=u.useCallback(async({selectedJob:h,file:j,job:f,thresholds:m})=>{var c;n(!0),d(null),o(null);try{const i=await D.calculateDrift(h,j,f==null?void 0:f.dataset_name,m);return r(i),i}catch(i){const g=i&&typeof i=="object"&&"response"in i?i.response:void 0,k=(c=g==null?void 0:g.data)==null?void 0:c.detail;return d(k||"Failed to calculate drift."),o((g==null?void 0:g.status)===404?"no_baseline":"failed"),null}finally{n(!1)}},[]),b=u.useMemo(()=>{if(!s)return null;const h=t,j={};let f=0;for(const[c,i]of Object.entries(s.column_drifts)){const g=i.metrics.map(v=>Ot(v,i,h)),k=g.some(v=>v.has_drift);k&&f++,j[c]={...i,metrics:g,drift_detected:k}}const m=s.missing_columns.length+s.new_columns.length;return{...s,column_drifts:j,drifted_columns_count:f+m}},[s,t]);return{report:s,evaluatedReport:b,loading:a,error:l,errorKind:p,setError:d,calculate:x}}function Kt(){const[t,s]=u.useState(null),r=u.useCallback(n=>{s(l=>(l==null?void 0:l.key)===n?l.dir==="asc"?{key:n,dir:"desc"}:null:{key:n,dir:"asc"})},[]),a=u.useCallback(()=>s(null),[]);return{sortConfig:t,handleSort:r,clearSort:a}}function Ut(t,s,r,a){return t&&s==null?"Unknown":r&&a!=null?a<=5?"High":a<=15?"Medium":"Low":t?"Low":""}function Ht(t,s){const r=t.feature_importances,a=["Column","Status","Wasserstein","PSI","KL Divergence","KS Statistic","KS P-Value",...r?["Importance","Risk"]:[]],n=Object.values(t.column_drifts).map(x=>{const b=m=>{var c,i;return((i=(c=x.metrics.find(g=>g.metric===m||m==="psi"&&g.metric==="psi_categorical"))==null?void 0:c.value)==null?void 0:i.toFixed(6))??""},h=r==null?void 0:r[x.column],j=r&&h!=null?Object.values(r).filter(m=>m>h).length+1:null,f=Ut(r,h,x.drift_detected,j);return[x.column,x.drift_detected?"Drifted":"Stable",b("wasserstein_distance"),b("psi"),b("kl_divergence"),b("ks_statistic"),b("ks_test_p_value"),...r?[(h==null?void 0:h.toFixed(6))??"",f]:[]]}),l=[a,...n].map(x=>x.map(b=>`"${b.replace(/"/g,'""')}"`).join(",")).join(` +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a0 as fe,j as T,a1 as je,f as W,D as ke,x as ye,C as ve,a2 as Ne,a as u,T as M,S as Z,a3 as we,X as A,_ as _e,b as V,e as P,N as Se,a4 as Ce,w as L,a5 as De,a6 as Re,a7 as ze,a8 as Y,a9 as Ee,aa as Le,ab as ee,ac as C,ad as Te,ae as Ae,U as Fe,af as $e,ag as Me,z as Pe,ah as Oe,ai as Ie,aj as Ke,O as Ue,c as He,ak as qe}from"./vendor-utils-_6D5wMFs.js";import{DEFAULT_DRIFT_THRESHOLDS as $,driftThresholdError as Be}from"./driftThresholds-BnFBRCeO.js";import{R as F,b as We,C as Ve,M as Ye,L as Xe,E as te,m as D,u as Je}from"./index-DYMv5Ibu.js";import{R as se,ag as Ge,C as re,X as ae,Y as ne,T as le,ah as ie,ai as X,B as Qe,h as J}from"./vendor-charts-CwfdE1jD.js";import{F as G}from"./FormField-BxGvOnTr.js";const Ze={none:{label:"No drift",classes:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400 border-green-200 dark:border-green-800"},warning:{label:"Warning",classes:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400 border-amber-200 dark:border-amber-800"},critical:{label:"Critical",classes:"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400 border-red-200 dark:border-red-800"}},oe=({severity:t})=>{const s=Ze[t],r=t==="critical"?fe:t==="warning"?T:je;return e.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-xs font-medium ${s.classes}`,children:[e.jsx(r,{size:12,"aria-hidden":"true"}),s.label]})},et={new:{label:"New",classes:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400 border-blue-200 dark:border-blue-800"},acknowledged:{label:"Acknowledged",classes:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400 border-purple-200 dark:border-purple-800"},resolved:{label:"Resolved",classes:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300 border-slate-200 dark:border-slate-700"},reopened:{label:"Reopened",classes:"bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400 border-orange-200 dark:border-orange-800"}},O=({status:t})=>{const s=et[t];return e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full border text-xs font-medium ${s.classes}`,children:s.label})};function tt({detail:t,filters:s}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(oe,{severity:t.severity}),e.jsx(O,{status:t.status}),t.evaluation_status!=="completed"&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-xs font-medium bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300 border-slate-200 dark:border-slate-700",children:[e.jsx(W,{size:12,"aria-hidden":"true"}),t.evaluation_status==="no_baseline"?"No baseline":"Evaluation failed"]})]}),t.evaluation_status!=="completed"&&t.error_message&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300 text-sm",children:[e.jsx(W,{size:16,className:"shrink-0 mt-0.5","aria-hidden":"true"}),e.jsx("span",{children:t.error_message})]}),e.jsx(st,{detail:t}),e.jsx(rt,{detail:t,filters:s})]})}function st({detail:t}){var s;return e.jsxs("dl",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Detected"}),e.jsx("dd",{className:"font-medium",children:((s=t.created_at)==null?void 0:s.replace("T"," ").slice(0,16))??"Unknown"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Threshold version"}),e.jsxs("dd",{className:"font-medium",children:[t.threshold_version!=null?`v${t.threshold_version}`:"—",t.threshold_version!=null&&e.jsxs("span",{className:"block text-[11px] font-normal text-gray-400",children:["PSI ",t.threshold_psi," · KS ",t.threshold_ks," · Wasserstein"," ",t.threshold_wasserstein," · KL ",t.threshold_kl]})]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Drifted features"}),e.jsx("dd",{className:"font-medium",children:t.drifted_columns_count!=null&&t.total_columns!=null?`${t.drifted_columns_count} / ${t.total_columns}`:"—"})]})]})}function rt({detail:t,filters:s}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[e.jsx(F,{recordRef:{kind:"job",jobId:t.job_id},origin:"/drift",filters:s}),t.model_version&&e.jsx(F,{recordRef:{kind:"modelVersion",jobId:t.job_id,version:t.model_version},origin:"/drift",filters:s}),t.deployment_id!=null&&e.jsx(F,{recordRef:{kind:"deployment",deploymentId:t.deployment_id},origin:"/drift",filters:s})]})}function at({alertId:t,evaluationStatus:s,evidenceRows:r}){return s!=="completed"?null:e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2",children:"Feature evidence"}),r.length===0?e.jsx(We,{title:"No evidence recorded",description:"This alert has no retained per-feature drift evidence."}):e.jsx(Ve,{caption:`Per-feature drift evidence for alert #${t??""}`,filename:`drift-alert-${t??"unknown"}-evidence`,columns:[{key:"column",label:"Feature"},{key:"drifted",label:"Drifted"},{key:"psi",label:"PSI"},{key:"wasserstein",label:"Wasserstein"},{key:"ks_statistic",label:"KS statistic"},{key:"ks_p_value",label:"KS p-value"}],rows:r,defaultOpen:!0})]})}function nt({entries:t}){return e.jsxs(e.Fragment,{children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2 flex items-center gap-1.5",children:[e.jsx(ke,{size:12})," History"]}),t.length===0?e.jsx("p",{className:"text-xs text-gray-400 italic",children:"No disposition changes recorded yet."}):e.jsx("ul",{className:"space-y-1.5",children:t.map((s,r)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-gray-600 dark:text-gray-300",children:[e.jsx(O,{status:s.status}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ye,{size:11})," ",s.actor]}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-gray-400",children:[e.jsx(ve,{size:11})," ",s.at.replace("T"," ").slice(0,16)]}),s.note&&e.jsxs("span",{className:"italic",children:['"',s.note,'"']})]},r))})]})}const Q={new:["acknowledge"],acknowledged:["resolve","reopen"],resolved:["reopen"],reopened:["acknowledge"]},lt={acknowledge:"Acknowledge",resolve:"Resolve",reopen:"Reopen"};function it({detail:t,actor:s,note:r,actionError:a,error:n,actionPending:l,setActor:d,setNote:p,handleAction:o}){return e.jsxs("div",{className:"border-t border-gray-200 dark:border-gray-700 pt-4",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2 flex items-center gap-1.5",children:[e.jsx(Ne,{size:13})," Disposition"]}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300 mb-3",children:t.owner?e.jsxs(e.Fragment,{children:["Currently ",e.jsx("strong",{children:t.status})," by ",e.jsx("strong",{children:t.owner}),"."]}):e.jsx(e.Fragment,{children:"No disposition recorded yet — acknowledge to claim this alert."})}),(Q[t.status]??[]).length>0&&e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(G,{label:"Your name",required:!0,children:x=>e.jsx("input",{...x,type:"text",value:s,onChange:b=>d(b.target.value),placeholder:"e.g. alice",className:"w-full text-sm px-3 py-1.5 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800"})}),e.jsx(G,{label:"Note",hint:"Optional context for the audit trail",children:x=>e.jsx("input",{...x,type:"text",value:r,onChange:b=>p(b.target.value),placeholder:"Optional",className:"w-full text-sm px-3 py-1.5 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-slate-800"})})]}),a&&e.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:a}),n&&e.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:n}),e.jsx("div",{className:"flex gap-2",children:(Q[t.status]??[]).map(x=>e.jsx("button",{type:"button",disabled:l,onClick:()=>void o(x),className:"px-3 py-1.5 text-sm font-medium rounded-md action-primary disabled:opacity-50 disabled:cursor-not-allowed",children:lt[x]},x))})]}),e.jsx(nt,{entries:t.disposition_history})]})}function ot(t){return t!=null&&t.column_drifts?Object.entries(t.column_drifts).map(([s,r])=>{const a=Object.fromEntries(r.metrics.map(n=>[n.metric,n.value]));return{column:s,drifted:r.drift_detected?"Yes":"No",psi:a.psi!=null?Number(a.psi.toFixed(4)):null,wasserstein:a.wasserstein_distance!=null?Number(a.wasserstein_distance.toFixed(4)):null,ks_statistic:a.ks_statistic!=null?Number(a.ks_statistic.toFixed(4)):null,ks_p_value:a.ks_test_p_value!=null?Number(a.ks_test_p_value.toFixed(4)):null}}):[]}const dt=({alertId:t,detail:s,loading:r,error:a,actionPending:n,onApplyDisposition:l,onRetry:d,onClose:p,filters:o})=>{const[x,b]=u.useState(""),[h,j]=u.useState(""),[f,m]=u.useState(null),c=u.useRef(0),i=u.useRef(h);i.current=h,u.useEffect(()=>()=>{c.current+=1},[t]);const g=async v=>{if(!x.trim()){m("Enter your name so the disposition records who made it.");return}m(null);const w=c.current;await l(v,x.trim(),h.trim()||void 0)&&w===c.current&&i.current===h&&j("")},k=ot(s);return e.jsxs(Ye,{isOpen:t!==null,onClose:p,title:t!==null?`Drift alert #${t}`:void 0,size:"3xl",children:[r&&e.jsx(Xe,{message:"Loading drift alert…"}),!r&&a&&!s&&e.jsx(te,{error:a,onRetry:d}),!r&&s&&e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(tt,{detail:s,filters:o}),e.jsx(at,{alertId:t,evaluationStatus:s.evaluation_status,evidenceRows:k}),e.jsx(it,{detail:s,actor:x,note:h,actionError:f,error:a,actionPending:n,setActor:b,setNote:j,handleAction:g})]})]})},ct=({history:t,onInvestigate:s})=>t.length===0?null:e.jsxs("div",{className:"bg-white dark:bg-slate-800 rounded-lg shadow border dark:border-slate-700 mt-6",children:[e.jsx("div",{className:"p-4 border-b border-gray-200 dark:border-slate-700",children:e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(M,{size:18})," Alert History",e.jsxs("span",{className:"text-xs font-normal text-gray-400 ml-1",children:["(",t.length," checks)"]})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-xs uppercase tracking-wider text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-slate-700",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Detected"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Severity"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Evaluation"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Threshold"}),e.jsx("th",{className:"px-4 py-2 font-medium",children:"Owner"}),e.jsx("th",{className:"px-4 py-2 font-medium sr-only",children:"Actions"})]})}),e.jsx("tbody",{children:t.map(r=>{var a;return e.jsxs("tr",{className:"border-b border-gray-100 dark:border-slate-700/60 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 whitespace-nowrap",children:((a=r.created_at)==null?void 0:a.replace("T"," ").slice(0,16))??"Unknown"}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(oe,{severity:r.severity})}),e.jsx("td",{className:"px-4 py-2",children:e.jsx(O,{status:r.status})}),e.jsx("td",{className:"px-4 py-2 capitalize",children:r.evaluation_status.replace("_"," ")}),e.jsx("td",{className:"px-4 py-2",children:r.threshold_version!=null?`v${r.threshold_version}`:"—"}),e.jsx("td",{className:"px-4 py-2",children:r.owner??"—"}),e.jsx("td",{className:"px-4 py-2 text-right",children:e.jsxs("button",{type:"button",onClick:()=>s(r.id),className:"inline-flex items-center gap-1 px-2 py-1 rounded text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 text-xs font-medium",children:[e.jsx(Z,{size:12,"aria-hidden":"true"}),"Investigate"]})})]},r.id)})})]})})]}),xt=({showOnlyDrifted:t,onToggleDrifted:s,sortConfig:r,onClearSort:a,onExport:n})=>e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsxs("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors border ${t?"bg-red-50 dark:bg-red-900/30 border-red-200 dark:border-red-700 text-red-700 dark:text-red-300":"border-gray-200 dark:border-slate-600 text-gray-500 dark:text-slate-400 hover:bg-gray-50 dark:hover:bg-slate-700"}`,children:[e.jsx(we,{size:12}),t?"Showing drifted only":"Show only drifted"]}),r&&e.jsxs("button",{onClick:a,className:"flex items-center gap-1 px-2 py-1.5 rounded-md text-xs text-gray-400 hover:text-gray-600 dark:hover:text-slate-300 transition-colors",children:[e.jsx(A,{size:11})," Clear sort"]}),e.jsx("div",{className:"ml-auto",children:e.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border border-gray-200 dark:border-slate-600 text-gray-500 dark:text-slate-400 hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors",title:"Download drift report as CSV",children:[e.jsx(_e,{size:12})," Export CSV"]})})]}),ut=({history:t})=>{if(t.length<=1)return null;const s=[...t].reverse().map(r=>{var l;const a=r.summary?Object.values(r.summary):null,n=a?a.filter(d=>d.drifted).length:null;return{date:((l=r.created_at)==null?void 0:l.split("T")[0])??"",drifted:n,pct:a!=null&&a.length?Math.round((n??0)/a.length*100):null}});return e.jsxs("div",{className:"bg-white dark:bg-slate-800 p-6 rounded-lg shadow border dark:border-slate-700 mt-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4 flex items-center gap-2",children:[e.jsx(M,{size:18})," Drift History",e.jsxs("span",{className:"text-xs font-normal text-gray-400 ml-1",children:["(",t.length," checks)"]})]}),e.jsx("div",{className:"h-[280px]",children:e.jsx(se,{width:"100%",height:"100%",children:e.jsxs(Ge,{data:s,margin:{top:5,right:30,left:0,bottom:5},children:[e.jsx(re,{strokeDasharray:"3 3",className:"stroke-gray-200 dark:stroke-slate-700",vertical:!1}),e.jsx(ae,{dataKey:"date",tick:{fill:"hsl(var(--muted-foreground))",fontSize:11},tickLine:!1,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ne,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:11},tickLine:!1,axisLine:!1}),e.jsx(le,{contentStyle:{backgroundColor:"hsl(var(--popover))",borderColor:"hsl(var(--border))",color:"hsl(var(--popover-foreground))",borderRadius:"6px"},itemStyle:{color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--muted-foreground))"},formatter:(r,a)=>a==="Drifted Features"?[r,a]:a==="Drift %"?[`${r}%`,a]:[r,a]}),e.jsx(ie,{verticalAlign:"top",height:36,iconType:"circle"}),e.jsx(X,{type:"monotone",dataKey:"drifted",name:"Drifted Features",stroke:"#ef4444",strokeWidth:2,dot:{r:3,fill:"#ef4444"}}),e.jsx(X,{type:"monotone",dataKey:"pct",name:"Drift %",stroke:"#f59e0b",strokeWidth:2,dot:{r:3,fill:"#f59e0b"},strokeDasharray:"5 5"})]})})})]})},R=({label:t,tooltip:s,icon:r})=>e.jsxs("div",{className:"group relative flex items-center gap-1 cursor-help",children:[e.jsx("span",{className:"border-b border-dotted border-gray-400",children:t}),r&&e.jsx("span",{className:"text-gray-400",children:r}),e.jsxs("div",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-2 w-64 p-2 bg-slate-900 text-white text-xs rounded shadow-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all z-50 text-center pointer-events-none",children:[s,e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 -mb-1 border-4 border-transparent border-b-slate-900"})]})]});function z(t){return t!=null&&Number.isFinite(t)}const mt=({values:t,threshold:s,width:r=64,height:a=20})=>{if(t.length<2)return e.jsx("span",{className:"text-[10px] text-gray-400",children:"—"});const n=t.filter(z);if(!n.length)return e.jsx("span",{className:"text-[10px] text-gray-400",title:"PSI unavailable for all checks",children:"—"});const l=Math.min(...n),p=Math.max(...n)-l||1,o=[];let x=[];const b=t.map((i,g)=>{if(!z(i))return x=[],null;x.length||o.push(x);const k={x:g/(t.length-1)*r,y:a-(i-l)/p*(a-4)-2};return x.push(`${k.x},${k.y}`),k}),h=t[t.length-1],j=z(h),f=z(s),m=j&&f?h>s?"#ef4444":"#22c55e":"#94a3b8",c=`PSI history: ${t.length-n.length} missing checks; latest PSI ${j?h:"unavailable"}; threshold ${f?s:"unavailable"}`;return e.jsxs("svg",{width:r,height:a,className:"inline-block",role:"img","aria-label":c,children:[e.jsx("title",{children:c}),o.map((i,g)=>e.jsx("polyline",{points:i.join(" "),fill:"none",stroke:"#3b82f6",strokeWidth:"1.5",strokeLinejoin:"round"},g)),b.map((i,g)=>i&&e.jsx("circle",{cx:i.x,cy:i.y,r:"2",fill:g===t.length-1?m:"#3b82f6"},g))]})},pt={wasserstein:"wasserstein_distance",psi:"psi",kl:"kl_divergence",ks:"ks_statistic"},ht=(t,s,r)=>{const a=(n,l)=>{var d;return((d=n.metrics.find(p=>p.metric===l||l==="psi"&&p.metric==="psi_categorical"))==null?void 0:d.value)??0};return[...t].sort((n,l)=>{let d=0;switch(s.key){case"column":d=n.column.localeCompare(l.column);break;case"status":d=(n.drift_detected?1:0)-(l.drift_detected?1:0);break;case"risk":d=((r==null?void 0:r[n.column])??0)-((r==null?void 0:r[l.column])??0);break;default:{const p=pt[s.key];p&&(d=a(n,p)-a(l,p))}}return s.dir==="asc"?d:-d})};function gt(t,s,r){let a=Object.values(t.column_drifts);return s&&(a=a.filter(n=>n.drift_detected)),r&&(a=ht(a,r,t.feature_importances)),a}const bt=({active:t,dir:s})=>t?s==="asc"?e.jsx(Re,{size:11}):e.jsx(ze,{size:11}):e.jsx(De,{size:11,className:"opacity-30"}),ft=({distribution:t})=>e.jsxs("div",{className:"h-[350px] w-full bg-white dark:bg-slate-800 p-6 rounded border dark:border-slate-700 shadow-sm",children:[e.jsxs("h4",{className:"text-sm font-semibold mb-6 flex items-center gap-2 text-slate-700 dark:text-slate-300",children:[e.jsx(ee,{size:16})," Distribution Comparison"]}),e.jsx(se,{width:"100%",height:"85%",children:e.jsxs(Qe,{data:t.bins,margin:{top:5,right:30,left:20,bottom:5},children:[e.jsx(re,{strokeDasharray:"3 3",className:"stroke-gray-200 dark:stroke-slate-700",vertical:!1}),e.jsx(ae,{dataKey:s=>`${s.bin_start.toFixed(2)}`,className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ne,{className:"text-xs",tick:{fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1}),e.jsx(le,{cursor:{fill:"rgba(0,0,0,0.05)"},contentStyle:{backgroundColor:"hsl(var(--popover))",borderColor:"hsl(var(--border))",color:"hsl(var(--popover-foreground))",borderRadius:"6px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},itemStyle:{color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--muted-foreground))",marginBottom:"0.5rem"}}),e.jsx(ie,{verticalAlign:"top",height:36,iconType:"circle"}),e.jsx(J,{dataKey:"reference_count",name:"Reference (Training)",fill:"#94a3b8",radius:[4,4,0,0],barSize:30}),e.jsx(J,{dataKey:"current_count",name:"Current (Production)",fill:"#3b82f6",radius:[4,4,0,0],barSize:30})]})})]}),jt=({importance:t,rank:s,drifted:r,maxImportance:a})=>{if(t==null)return e.jsx("span",{className:"text-xs text-gray-400",children:"—"});const n=r&&s!=null&&s<=5,l=r&&s!=null&&s<=15&&!n;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[n?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-semibold bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300",children:[e.jsx(Y,{size:12})," High"]}):l?e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-semibold bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300",children:[e.jsx(Y,{size:12})," Medium"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-gray-100 dark:bg-slate-700 text-gray-500 dark:text-slate-400",children:[e.jsx(Ee,{size:12})," Low"]}),e.jsx("div",{className:"w-12 h-1.5 bg-gray-200 dark:bg-slate-700 rounded-full overflow-hidden",title:`Importance: ${(t*100/a).toFixed(0)}%`,children:e.jsx("div",{className:"h-full bg-indigo-500 rounded-full",style:{width:`${a>0?t/a*100:0}%`}})})]})};function E({metric:t,showRawDistance:s=!1}){var a;const r=s&&(t==null?void 0:t.raw_value)!=null?`Raw earth-mover distance: ${t.raw_value.toFixed(4)} in column units`:void 0;return e.jsx("td",{className:`px-6 py-4 whitespace-nowrap tabular-nums ${t!=null&&t.has_drift?"text-red-600 dark:text-red-400 font-bold":""}`,title:r,children:((a=t==null?void 0:t.value)==null?void 0:a.toFixed(4))??"—"})}function kt({col:t,ks:s,ksPValue:r}){return e.jsxs("div",{className:"flex flex-col gap-4",children:[s&&e.jsxs("div",{className:"text-xs text-gray-600 dark:text-slate-400",children:["KS statistic"," ",e.jsx("span",{className:"font-semibold tabular-nums",children:s.value.toFixed(4)})," ","vs threshold ",s.threshold.toFixed(2),r&&e.jsxs(e.Fragment,{children:[" ","· p-value"," ",e.jsx("span",{className:"tabular-nums",children:r.value<.001?"< 0.001":r.value.toFixed(3)})," ","(diagnostic only — drift is decided on the statistic)"]})]}),t.suggestions&&t.suggestions.length>0&&e.jsx("div",{className:"bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded border border-yellow-200 dark:border-yellow-800",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Le,{size:16,className:"mt-0.5 shrink-0 text-yellow-600 dark:text-yellow-400"}),e.jsx("ul",{className:"list-disc list-inside text-sm text-yellow-800 dark:text-yellow-200",children:t.suggestions.map((a,n)=>e.jsx("li",{children:a},n))})]})}),t.distribution&&e.jsx(ft,{distribution:t.distribution})]})}function yt({col:t,fi:s,isExpanded:r,maxImportance:a,toggleRow:n,hasSparklines:l,columnSparklines:d,colSpan:p}){const o=t.metrics.find(c=>c.metric==="wasserstein_distance"),x=t.metrics.find(c=>c.metric==="psi"||c.metric==="psi_categorical"),b=t.metrics.find(c=>c.metric==="kl_divergence"),h=t.metrics.find(c=>c.metric==="ks_statistic"),j=t.metrics.find(c=>c.metric==="ks_test_p_value"),f=s==null?void 0:s[t.column],m=s?Object.values(s).filter(c=>c>(f??0)).length+1:null;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:t.drift_detected?"bg-red-50 dark:bg-red-900/10":"",children:[e.jsx("td",{className:"px-6 py-4 whitespace-nowrap font-medium",children:t.column}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:t.drift_detected?e.jsxs("span",{className:"text-red-600 dark:text-red-400 flex items-center gap-1",children:[e.jsx(Se,{size:16})," Drifted"]}):e.jsxs("span",{className:"text-green-600 dark:text-green-400 flex items-center gap-1",children:[e.jsx(P,{size:16})," Stable"]})}),e.jsx(E,{metric:o,showRawDistance:!0}),e.jsx(E,{metric:x}),e.jsx(E,{metric:b}),e.jsx(E,{metric:h}),s&&e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(jt,{importance:f,rank:m,drifted:t.drift_detected,maxImportance:a})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsxs("button",{onClick:()=>n(t.column),className:"text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 flex items-center gap-1 text-sm",children:[r?e.jsx(Ce,{size:16}):e.jsx(L,{size:16}),r?"Hide":"Details"]})}),l&&e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx(mt,{values:d[t.column]??[],threshold:x==null?void 0:x.threshold})})]}),r&&e.jsx("tr",{children:e.jsx("td",{colSpan:p,className:"px-6 py-4 bg-gray-50 dark:bg-slate-900/50",children:e.jsx(kt,{col:t,ks:h,ksPValue:j})})})]})}const vt=({report:t,showOnlyDrifted:s,sortConfig:r,onSort:a,columnSparklines:n})=>{const[l,d]=u.useState({});V.useEffect(()=>{d({})},[t]),V.useEffect(()=>{const c=i=>{i.key==="Escape"&&d({})};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[]);const p=c=>d(i=>({...i,[c]:!i[c]})),o=t.feature_importances,x=o?Math.max(...Object.values(o)):0,b=Object.keys(n).length>0,h=gt(t,s,r),j=(o?8:7)+(b?1:0),f=t.missing_columns.length>0||t.new_columns.length>0,m=(c,i)=>e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider cursor-pointer select-none hover:text-gray-700 dark:hover:text-slate-300",onClick:()=>a(c),children:e.jsxs("span",{className:"flex items-center gap-1",children:[i,e.jsx(bt,{active:(r==null?void 0:r.key)===c,dir:r==null?void 0:r.dir})]})});return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-gray-200 dark:divide-slate-700",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-slate-900",children:e.jsxs("tr",{children:[m("column","Column"),m("status","Status"),m("wasserstein",e.jsx(R,{label:"Wasserstein",tooltip:"Measures distance between distributions, normalized by the reference column's standard deviation so the threshold is scale-free. Lower is better. < 0.1 usually means stable.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),m("psi",e.jsx(R,{label:"PSI",tooltip:"Population Stability Index. < 0.1: Stable, < 0.2: Minor Drift, > 0.2: Significant Drift.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),m("kl",e.jsx(R,{label:"KL Div",tooltip:"Kullback-Leibler Divergence. Measures how one probability distribution diverts from a second.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),m("ks",e.jsx(R,{label:"KS Stat",tooltip:"Kolmogorov-Smirnov statistic — maximum distance between the two cumulative distributions (0–1). Unlike the p-value it does not shrink with sample size; values above the threshold (default 0.1) indicate drift.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),o&&m("risk",e.jsx(R,{label:"Risk",tooltip:"Combines drift status with feature importance. High = drifted + important feature. Helps prioritize which drifts to investigate.",icon:e.jsx(C,{className:"w-3 h-3 text-slate-400"})})),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:"Actions"}),b&&e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(M,{size:11})," Trend"]})})]})}),e.jsx("tbody",{className:"bg-white dark:bg-slate-800 divide-y divide-gray-200 dark:divide-slate-700",children:h.length===0&&s?e.jsx("tr",{children:e.jsxs("td",{colSpan:j,className:"px-6 py-8 text-center text-gray-500 dark:text-slate-400 text-sm",children:[e.jsx(P,{size:20,className:"inline mr-2 text-green-500"}),f?"No distribution drift among shared columns — see the schema drift above.":"No drifted columns found — all features are stable."]})}):h.map(c=>e.jsx(yt,{col:c,fi:o,isExpanded:l[c.column],maxImportance:x,toggleRow:p,hasSparklines:b,columnSparklines:n,colSpan:j},c.column))})]})})},Nt=()=>e.jsx("div",{className:"bg-white dark:bg-slate-800 rounded-lg shadow border dark:border-slate-700 p-12 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3 text-gray-500 dark:text-slate-400",children:[e.jsx(Te,{size:48,strokeWidth:1.2}),e.jsx("h2",{className:"text-lg font-medium text-gray-500 dark:text-slate-400",children:"No Drift Report Yet"}),e.jsxs("p",{className:"text-sm max-w-md",children:["Select a reference model from the dropdown above, upload current production data (CSV or Parquet), and click ",e.jsx("strong",{children:"Run Analysis"})," to compare distributions."]})]})}),wt=({file:t,onFileChange:s,invalid:r})=>{const a=u.useRef(null),n=l=>{l.target.files&&l.target.files[0]&&s(l.target.files[0])};return e.jsxs("div",{className:"flex flex-col gap-1 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("input",{ref:a,type:"file",className:"hidden",onChange:n,accept:".csv,.parquet","aria-label":"Upload current data file (CSV or Parquet)"}),t?e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2.5 border border-gray-200 dark:border-slate-600 rounded-md text-sm bg-gray-50 dark:bg-slate-900",children:[e.jsx(Ae,{size:14,className:"text-green-500 shrink-0"}),e.jsx("span",{className:"text-slate-700 dark:text-slate-300 truncate max-w-[180px]",children:t.name}),e.jsx("button",{type:"button",onClick:()=>s(null),"aria-label":`Remove ${t.name}`,className:"text-gray-400 hover:text-red-500 transition-colors ml-1",children:e.jsx(A,{size:14})})]}):e.jsxs("button",{type:"button",onClick:()=>{var l;return(l=a.current)==null?void 0:l.click()},"aria-describedby":r?"file-uploader-error":void 0,className:`flex items-center gap-2 px-3 py-2.5 border border-dashed rounded-md text-sm transition-colors ${r?"border-red-400 dark:border-red-500 text-red-600 dark:text-red-400 hover:border-red-500":"border-gray-300 dark:border-slate-600 text-gray-500 dark:text-gray-400 hover:border-blue-400 hover:text-blue-500 dark:hover:border-blue-500"}`,children:[e.jsx(Fe,{size:15}),"Upload CSV / Parquet"]})]}),r&&!t&&e.jsx("span",{id:"file-uploader-error",className:"text-[11px] text-red-600 dark:text-red-400",children:"Current data file is required."})]})};function _t({triggerRef:t,open:s,listboxId:r,invalid:a,selectedJob:n,selectedJobData:l,onSelect:d,onToggle:p}){return e.jsxs("button",{ref:t,type:"button","aria-haspopup":"listbox","aria-expanded":s,"aria-controls":r,onClick:()=>{p()},className:`w-full flex items-center gap-2 px-3 py-2.5 border rounded-md text-sm transition-colors ${a?"border-red-400 dark:border-red-500 hover:border-red-500":n?"border-blue-300 dark:border-blue-700 bg-blue-50/50 dark:bg-blue-900/20":"border-gray-200 dark:border-slate-600 hover:border-gray-300 dark:hover:border-slate-500"}`,"aria-describedby":a?"job-selector-error":void 0,children:[e.jsx($e,{size:15,className:"shrink-0 text-gray-400"}),e.jsx("span",{className:`truncate ${n?"text-slate-800 dark:text-slate-200":"text-gray-400"}`,children:l?`${l.dataset_name} (${l.job_id.slice(0,8)})`:"Select reference model..."}),n&&e.jsx("span",{role:"button",tabIndex:0,"aria-label":"Clear selected reference model",title:"Clear selection",onClick:o=>{o.stopPropagation(),d("")},onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.stopPropagation(),o.preventDefault(),d(""))},className:"ml-auto shrink-0 p-0.5 rounded hover:bg-black/5 dark:hover:bg-white/10 text-gray-400 hover:text-gray-600 dark:hover:text-slate-300",children:e.jsx(A,{size:13})}),e.jsx(L,{size:14,className:`${n?"":"ml-auto"} shrink-0 text-gray-400 transition-transform ${s?"rotate-180":""}`})]})}const St=({jobs:t,selectedJob:s,onSelect:r,invalid:a})=>{const[n,l]=u.useState(!1),[d,p]=u.useState(""),o=u.useRef(null),x=u.useRef(null),b="job-selector-listbox";u.useEffect(()=>{const m=c=>{o.current&&!o.current.contains(c.target)&&l(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]),u.useEffect(()=>{if(!n)return;const m=c=>{var i;c.key==="Escape"&&(l(!1),(i=x.current)==null||i.focus())};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);const h=u.useMemo(()=>{if(!d)return t;const m=d.toLowerCase();return t.filter(c=>{var i,g,k;return c.dataset_name.toLowerCase().includes(m)||c.job_id.toLowerCase().includes(m)||((i=c.description)==null?void 0:i.toLowerCase().includes(m))||((g=c.model_type)==null?void 0:g.toLowerCase().includes(m))||((k=c.target_column)==null?void 0:k.toLowerCase().includes(m))})},[d,t]),j=u.useMemo(()=>{var c;const m={};for(const i of h){const g=((c=i.created_at)==null?void 0:c.split(" ")[0])||"Unknown";m[g]||(m[g]=[]),m[g].push(i)}return Object.entries(m).sort(([i],[g])=>g.localeCompare(i))},[h]),f=u.useMemo(()=>t.find(m=>m.job_id===s),[t,s]);return e.jsxs("div",{ref:o,className:"relative flex-1 min-w-0",children:[e.jsx(_t,{triggerRef:x,open:n,listboxId:b,invalid:a,selectedJob:s,selectedJobData:f,onSelect:r,onToggle:()=>{l(!n),p("")}}),a&&!s&&e.jsx("span",{id:"job-selector-error",className:"block mt-1 text-[11px] text-red-600 dark:text-red-400",children:"Reference job is required."}),n&&e.jsxs("div",{id:b,role:"listbox","aria-label":"Reference model jobs",className:"absolute z-50 left-0 right-0 mt-1 bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-600 rounded-md shadow-lg overflow-hidden",children:[e.jsx("div",{className:"p-2 border-b border-gray-100 dark:border-slate-700",children:e.jsxs("div",{className:"relative",children:[e.jsx(Z,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none z-10",size:14}),e.jsx("input",{type:"text",autoFocus:!0,placeholder:"Search jobs...",value:d,onChange:m=>p(m.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm border border-gray-200 dark:border-slate-600 rounded bg-gray-50 dark:bg-slate-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-blue-500"})]})}),e.jsx("div",{className:"max-h-72 overflow-y-auto",children:h.length===0?e.jsx("div",{className:"p-4 text-center text-gray-400 text-sm",children:"No jobs found"}):j.map(([m,c])=>e.jsxs("div",{children:[e.jsx("div",{className:"sticky top-0 px-3 py-1.5 text-[11px] font-semibold text-gray-500 dark:text-slate-400 bg-gray-50 dark:bg-slate-900/80 uppercase tracking-wider border-b border-gray-100 dark:border-slate-700",children:m}),c.map(i=>e.jsxs("button",{type:"button",role:"option","aria-selected":s===i.job_id,onClick:()=>{r(i.job_id),l(!1)},className:`w-full text-left px-3 py-2.5 text-sm transition-colors ${s===i.job_id?"bg-blue-50 dark:bg-blue-900/30":"hover:bg-gray-50 dark:hover:bg-slate-700/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:i.dataset_name}),e.jsx("span",{className:"text-[11px] text-gray-400 font-mono shrink-0",children:i.job_id.slice(0,8)}),i.model_type&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-100 dark:bg-indigo-900/40 text-indigo-600 dark:text-indigo-300 shrink-0",children:i.model_type}),i.best_metric&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-900/40 text-green-600 dark:text-green-300 shrink-0 ml-auto tabular-nums truncate max-w-[140px]",title:i.best_metric,children:i.best_metric.split(" | ")[0]})]}),(i.target_column||i.description)&&e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 text-[11px] text-gray-500 dark:text-slate-400",children:[i.target_column&&e.jsxs("span",{children:["target: ",i.target_column]}),i.description&&e.jsxs("span",{className:"truncate italic",children:["— ",i.description]})]})]},i.job_id))]},m))})]})]})},Ct=({missingColumns:t,newColumns:s})=>{const r=t.filter(n=>n.trim()!==""),a=s.filter(n=>n.trim()!=="");return r.length===0&&a.length===0?null:e.jsxs("div",{className:"mb-6 grid grid-cols-1 md:grid-cols-2 gap-4",children:[r.length>0&&e.jsxs("details",{className:"group bg-red-50 dark:bg-red-900/20 rounded border border-red-200 dark:border-red-800",children:[e.jsxs("summary",{className:"font-semibold text-red-800 dark:text-red-200 p-4 flex items-center gap-2 cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden",children:[e.jsx(L,{size:14,className:"transition-transform group-open:rotate-180 shrink-0"}),e.jsx(T,{size:16,className:"shrink-0"})," Missing Columns",e.jsx("span",{className:"ml-auto text-xs font-normal bg-red-200 dark:bg-red-800 px-2 py-0.5 rounded-full",children:r.length})]}),e.jsxs("div",{className:"px-4 pb-4",children:[e.jsx("p",{className:"text-[11px] text-red-600/70 dark:text-red-300/60 mb-2",children:"Columns present in reference (training) data but missing from your uploaded file."}),e.jsx("ul",{className:"list-disc list-inside text-sm text-red-700 dark:text-red-300",children:r.map(n=>e.jsx("li",{children:n},n))})]})]}),a.length>0&&e.jsxs("details",{className:"group bg-blue-50 dark:bg-blue-900/20 rounded border border-blue-200 dark:border-blue-800",children:[e.jsxs("summary",{className:"font-semibold text-blue-800 dark:text-blue-200 p-4 flex items-center gap-2 cursor-pointer select-none list-none [&::-webkit-details-marker]:hidden",children:[e.jsx(L,{size:14,className:"transition-transform group-open:rotate-180 shrink-0"}),e.jsx(C,{size:16,className:"shrink-0"})," Extra Columns",e.jsx("span",{className:"ml-auto text-xs font-normal bg-blue-200 dark:bg-blue-800 px-2 py-0.5 rounded-full",children:a.length})]}),e.jsxs("div",{className:"px-4 pb-4",children:[e.jsx("p",{className:"text-[11px] text-blue-600/70 dark:text-blue-300/60 mb-2",children:"Columns in your uploaded file that were not in the training reference. These are excluded from distribution metrics but reported as schema changes. The model target is excluded from both checks."}),e.jsx("ul",{className:"list-disc list-inside text-sm text-blue-700 dark:text-blue-300",children:a.map(n=>e.jsx("li",{children:n},n))})]})]})]})},Dt=({job:t,onUpdateDescription:s})=>{const[r,a]=u.useState(!1),[n,l]=u.useState("");u.useEffect(()=>{a(!1)},[t.job_id]);const d=async()=>{await s(n),a(!1)};return e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-4 pb-3 text-xs text-gray-500 dark:text-slate-400",children:[t.model_type&&e.jsx("span",{className:"px-2 py-0.5 rounded bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-300 font-medium",children:t.model_type}),t.target_column&&e.jsxs("span",{children:["Target:"," ",e.jsx("span",{className:"font-medium text-slate-600 dark:text-slate-300",children:t.target_column})]}),t.n_features!=null&&e.jsxs("span",{children:[t.n_features," features"]}),t.n_rows!=null&&e.jsxs("span",{children:[t.n_rows.toLocaleString()," rows"]}),t.best_metric&&e.jsx("span",{className:"px-2 py-0.5 rounded bg-green-50 dark:bg-green-900/30 text-green-600 dark:text-green-300 font-medium tabular-nums",children:t.best_metric}),e.jsx("span",{className:"border-l border-gray-200 dark:border-slate-700 h-3"}),r?e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("input",{autoFocus:!0,value:n,onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&d(),p.key==="Escape"&&a(!1)},placeholder:"Add a description...",className:"flex-1 min-w-0 px-2 py-0.5 text-xs border border-gray-200 dark:border-slate-600 rounded bg-white dark:bg-slate-900 dark:text-white focus:outline-none focus:ring-1 focus:ring-blue-500"}),e.jsx("button",{onClick:()=>void d(),className:"text-green-500 hover:text-green-600",children:e.jsx(Me,{size:13})}),e.jsx("button",{onClick:()=>a(!1),className:"text-gray-400 hover:text-red-500",children:e.jsx(A,{size:13})})]}):e.jsxs("button",{onClick:()=>{l(t.description||""),a(!0)},className:"flex items-center gap-1 hover:text-blue-500 transition-colors group",children:[e.jsx(Pe,{size:11,className:"opacity-50 group-hover:opacity-100"}),e.jsx("span",{className:t.description?"":"italic text-gray-400",children:t.description||"Add description..."})]})]})};function Rt(t){const s=Object.values(t.column_drifts),r=s.length,a=s.filter(o=>o.drift_detected).length,n=s.flatMap(o=>{var b;const x=(b=o.metrics.find(h=>(h.metric==="psi"||h.metric==="psi_categorical")&&Number.isFinite(h.value)))==null?void 0:b.value;return x==null?[]:[{column:o.column,psi:x}]}),l=n.length>0?n.reduce((o,x)=>o+x.psi,0)/n.length:null,d=n.sort((o,x)=>x.psi-o.psi)[0],p=r>0?Math.round(a/r*100):0;return{totalCols:r,driftedCount:a,avgPsi:l,mostDrifted:d,driftedPct:p}}function zt(t){return t==null?"No PSI available":t<.1?"Stable":t<.2?"Minor drift":"Significant drift"}const Et=({report:t})=>{const{totalCols:s,driftedCount:r,avgPsi:a,mostDrifted:n,driftedPct:l}=Rt(t);return e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-6",children:[e.jsxs("div",{className:"bg-gray-50 dark:bg-slate-900/50 rounded-lg p-4 border dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[e.jsx(Oe,{size:13})," Total Columns"]}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:s}),e.jsxs("div",{className:"text-[11px] text-gray-400 mt-0.5",children:["Ref: ",t.reference_rows.toLocaleString()," rows | Cur: ",t.current_rows.toLocaleString()," rows"]})]}),e.jsxs("div",{className:`rounded-lg p-4 border ${r>0?"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800":"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[r>0?e.jsx(T,{size:13}):e.jsx(P,{size:13})," Drifted"]}),e.jsxs("div",{className:"text-2xl font-bold tabular-nums",children:[r," ",e.jsxs("span",{className:"text-sm font-normal text-gray-400",children:["/ ",s]})]}),e.jsxs("div",{className:"text-[11px] text-gray-400 mt-0.5",children:[l,"% of features"]})]}),e.jsxs("div",{className:"bg-gray-50 dark:bg-slate-900/50 rounded-lg p-4 border dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[e.jsx(Ie,{size:13})," Avg PSI"]}),e.jsx("div",{className:`text-2xl font-bold tabular-nums ${(a??0)>.2?"text-red-600 dark:text-red-400":(a??0)>.1?"text-amber-600 dark:text-amber-400":""}`,children:(a==null?void 0:a.toFixed(4))??"—"}),e.jsx("div",{className:"text-[11px] text-gray-400 mt-0.5",children:zt(a)})]}),e.jsxs("div",{className:"bg-gray-50 dark:bg-slate-900/50 rounded-lg p-4 border dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500 dark:text-slate-400 mb-1",children:[e.jsx(Ke,{size:13})," Most Drifted"]}),e.jsx("div",{className:"text-lg font-bold truncate",title:n==null?void 0:n.column,children:(n==null?void 0:n.column)??"—"}),e.jsxs("div",{className:"text-[11px] text-gray-400 mt-0.5",children:["PSI: ",(n==null?void 0:n.psi.toFixed(4))??"—"]})]})]})},Lt=[{key:"psi",label:"PSI",metrics:["psi","psi_categorical"]},{key:"ks",label:"KS statistic",metrics:["ks_statistic"]},{key:"wasserstein",label:"Wasserstein",metrics:["wasserstein_distance"]},{key:"kl",label:"KL Div",metrics:["kl_divergence"]}],Tt=({thresholds:t,onChange:s,report:r})=>{const[a,n]=u.useState({}),[l,d]=u.useState({}),p=o=>{n({}),d({}),s(o)};return e.jsxs("div",{className:"px-4 pb-3 flex flex-wrap items-start gap-4 border-t border-gray-100 dark:border-slate-700 pt-3",children:[Lt.map(({key:o,label:x,metrics:b})=>{const h=a[o],j=l[o],f=[...new Set(Object.values((r==null?void 0:r.column_drifts)??{}).flatMap(i=>i.metrics.filter(g=>b.includes(g.metric)).map(g=>g.threshold)))],m=t[o]??(f.length?f.join(", "):$[o]),c=t[o]!=null?"override":f.length?"saved report":"default";return e.jsxs("div",{className:"text-xs text-gray-600 dark:text-slate-400",children:[e.jsxs("label",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"font-medium",children:x}),e.jsx("input",{type:"number",value:h??t[o]??"",min:0,max:o==="ks"?1:void 0,step:"any","aria-invalid":!!j,onChange:i=>{const g=i.target.value;n(w=>({...w,[o]:g}));const k=g.trim()?Number(g):void 0,v=i.target.validity.badInput?"Threshold must be a finite number.":k===void 0?null:Be(o,k);d(w=>({...w,[o]:v})),v||s({...t,[o]:k})},className:"w-20 px-2 py-1 border rounded bg-white dark:bg-slate-900 dark:text-white"})]}),e.jsxs("p",{className:"mt-1",children:["Effective ",x,": ",m," (",c,")"]}),j&&e.jsxs("p",{role:"alert",className:"max-w-48 text-red-600",children:[j," Not applied."]})]},o)}),e.jsx("button",{onClick:()=>p($),className:"text-xs underline",children:"Reset defaults"}),e.jsx("button",{onClick:()=>p({}),className:"text-xs underline",children:"Remove overrides"}),e.jsx("p",{className:"w-full text-xs text-gray-500",children:"Clearing a field restores its saved report threshold, or the default before analysis. Reset defaults applies defaults as overrides. New analyses use defaults for cleared fields."})]})};function At(t,s){var a,n;return(t&&typeof t=="object"&&"response"in t?(n=(a=t.response)==null?void 0:a.data)==null?void 0:n.detail:void 0)||`Failed to ${s} the drift alert.`}function Ft(t){const[s,r]=u.useState(null),[a,n]=u.useState(!1),[l,d]=u.useState(null),[p,o]=u.useState(!1),x=u.useRef(0),b=u.useRef(0),h=u.useCallback(async()=>{const f=++x.current;if(t==null){r(null),n(!1),d(null);return}n(!0),d(null);try{const m=await D.getDriftAlert(t);f===x.current&&r(m)}catch{f===x.current&&d("Failed to load drift alert detail.")}finally{f===x.current&&n(!1)}},[t]);u.useEffect(()=>(r(null),o(!1),h(),()=>{x.current+=1,b.current+=1}),[h]);const j=u.useCallback(async(f,m,c)=>{if(t==null)return null;const i=++b.current;o(!0),d(null);try{const g=await D.updateDriftAlertDisposition(t,f,m,c);return i!==b.current?null:(x.current+=1,r(g),n(!1),d(null),g)}catch(g){return i===b.current&&d(At(g,f)),null}finally{i===b.current&&o(!1)}},[t]);return{detail:s,loading:a,error:l,actionPending:p,refresh:h,applyDisposition:j}}function $t(t){const[s,r]=u.useState([]),a=u.useRef(0),n=u.useCallback(()=>{const d=++a.current;if(!t){r([]);return}D.getDriftHistory(t).then(p=>{d===a.current&&r(p)}).catch(()=>{d===a.current&&r([])})},[t]);u.useEffect(()=>(r([]),n(),()=>{a.current+=1}),[n]);const l=u.useMemo(()=>{if(s.length<2)return{};const d=[...s].reverse(),p=new Set(d.flatMap(o=>Object.keys(o.summary??{})));return Object.fromEntries([...p].map(o=>[o,d.map(x=>{var h,j;const b=(j=(h=x.summary)==null?void 0:h[o])==null?void 0:j.psi;return typeof b=="number"&&Number.isFinite(b)?b:null})]))},[s]);return{driftHistory:s,columnSparklines:l,refreshHistory:n}}function Mt(){const[t,s]=u.useState([]),[r,a]=u.useState(!1),n=u.useCallback(async()=>{a(!0);try{const d=await D.getJobs();s(d)}catch(d){console.error("Failed to fetch jobs",d)}finally{a(!1)}},[]);u.useEffect(()=>{n()},[n]);const l=u.useCallback(async(d,p)=>{try{await D.updateJobDescription(d,p),s(o=>o.map(x=>x.job_id===d?{...x,description:p}:x))}catch(o){console.error("Failed to save description",o)}},[]);return{jobs:t,refreshing:r,refresh:n,updateJobDescription:l}}function Pt(t,s){switch(t){case"psi":case"psi_categorical":return s.psi;case"ks_statistic":return s.ks;case"wasserstein_distance":return s.wasserstein;case"kl_divergence":return s.kl;default:return}}function Ot(t,s,r){let a=t.has_drift;const n=Pt(t.metric,r);if(n!=null&&(a=t.value>n),t.metric==="ks_test_p_value"){const l=s.metrics.find(d=>d.metric==="ks_statistic");l!=null&&(a=l.value>(r.ks??l.threshold))}return{...t,threshold:n??t.threshold,has_drift:a}}function It(t){const[s,r]=u.useState(null),[a,n]=u.useState(!1),[l,d]=u.useState(null),[p,o]=u.useState(null),x=u.useCallback(async({selectedJob:h,file:j,job:f,thresholds:m})=>{var c;n(!0),d(null),o(null);try{const i=await D.calculateDrift(h,j,f==null?void 0:f.dataset_name,m);return r(i),i}catch(i){const g=i&&typeof i=="object"&&"response"in i?i.response:void 0,k=(c=g==null?void 0:g.data)==null?void 0:c.detail;return d(k||"Failed to calculate drift."),o((g==null?void 0:g.status)===404?"no_baseline":"failed"),null}finally{n(!1)}},[]),b=u.useMemo(()=>{if(!s)return null;const h=t,j={};let f=0;for(const[c,i]of Object.entries(s.column_drifts)){const g=i.metrics.map(v=>Ot(v,i,h)),k=g.some(v=>v.has_drift);k&&f++,j[c]={...i,metrics:g,drift_detected:k}}const m=s.missing_columns.length+s.new_columns.length;return{...s,column_drifts:j,drifted_columns_count:f+m}},[s,t]);return{report:s,evaluatedReport:b,loading:a,error:l,errorKind:p,setError:d,calculate:x}}function Kt(){const[t,s]=u.useState(null),r=u.useCallback(n=>{s(l=>(l==null?void 0:l.key)===n?l.dir==="asc"?{key:n,dir:"desc"}:null:{key:n,dir:"asc"})},[]),a=u.useCallback(()=>s(null),[]);return{sortConfig:t,handleSort:r,clearSort:a}}function Ut(t,s,r,a){return t&&s==null?"Unknown":r&&a!=null?a<=5?"High":a<=15?"Medium":"Low":t?"Low":""}function Ht(t,s){const r=t.feature_importances,a=["Column","Status","Wasserstein","PSI","KL Divergence","KS Statistic","KS P-Value",...r?["Importance","Risk"]:[]],n=Object.values(t.column_drifts).map(x=>{const b=m=>{var c,i;return((i=(c=x.metrics.find(g=>g.metric===m||m==="psi"&&g.metric==="psi_categorical"))==null?void 0:c.value)==null?void 0:i.toFixed(6))??""},h=r==null?void 0:r[x.column],j=r&&h!=null?Object.values(r).filter(m=>m>h).length+1:null,f=Ut(r,h,x.drift_detected,j);return[x.column,x.drift_detected?"Drifted":"Stable",b("wasserstein_distance"),b("psi"),b("kl_divergence"),b("ks_statistic"),b("ks_test_p_value"),...r?[(h==null?void 0:h.toFixed(6))??"",f]:[]]}),l=[a,...n].map(x=>x.map(b=>`"${b.replace(/"/g,'""')}"`).join(",")).join(` `),d=new Blob([l],{type:"text/csv;charset=utf-8;"}),p=URL.createObjectURL(d),o=document.createElement("a");o.href=p,o.download=`drift_report_${s??"export"}_${new Date().toISOString().slice(0,10)}.csv`,o.click(),URL.revokeObjectURL(p)}function qt({jobs:t,selectedJob:s,setSelectedJob:r,file:a,setFile:n,submitAttempted:l,loading:d,refreshing:p,showThresholds:o,onCalculate:x,onRefresh:b,onToggleThresholds:h}){return e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 p-4",children:[e.jsx(St,{jobs:t,selectedJob:s,onSelect:r,invalid:l&&!s}),e.jsx(wt,{file:a,onFileChange:n,invalid:l&&!a}),e.jsxs("button",{onClick:x,disabled:d||!s||!a,className:"flex items-center justify-center gap-2 px-5 py-2.5 action-primary rounded-md text-sm font-medium disabled:opacity-40 disabled:cursor-not-allowed transition-colors shrink-0",children:[d?e.jsx(Ue,{className:"animate-spin",size:16}):e.jsx(ee,{size:16}),d?"Analyzing...":"Run Analysis"]}),e.jsx("button",{onClick:b,className:"p-2.5 rounded-md hover:bg-gray-100 dark:hover:bg-slate-700 text-gray-400 transition-colors shrink-0",title:"Refresh jobs",children:e.jsx(He,{size:16,className:p?"animate-spin":""})}),e.jsx("button",{onClick:h,className:`p-2.5 rounded-md transition-colors shrink-0 ${o?"bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400":"hover:bg-gray-100 dark:hover:bg-slate-700 text-gray-400"}`,title:"Drift thresholds",children:e.jsx(qe,{size:16})})]})}function Bt({error:t,errorKind:s,onRetry:r}){return e.jsxs(e.Fragment,{children:[t&&s&&e.jsx("div",{className:"mx-4 mb-4",children:e.jsx(te,{error:s==="no_baseline"?`No baseline reference is available for this job yet. ${t}`:t,onRetry:r})}),t&&!s&&e.jsxs("div",{className:"mx-4 mb-4 p-3 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-200 rounded-md flex items-center gap-2 border border-red-200 dark:border-red-800 text-sm",children:[e.jsx(T,{size:16,className:"shrink-0"}),t]})]})}const Qt=()=>{const[t,s]=Je(),r=Number(t.get("investigate")),[a,n]=u.useState(""),[l,d]=u.useState(null),[p,o]=u.useState($),[x,b]=u.useState(!1),[h,j]=u.useState(!1),[f,m]=u.useState(!1),[c,i]=u.useState(Number.isFinite(r)&&r>0?r:null),{jobs:g,refreshing:k,refresh:v,updateJobDescription:w}=Mt(),{report:I,evaluatedReport:N,loading:K,error:U,errorKind:de,setError:ce,calculate:xe}=It(p),{driftHistory:H,columnSparklines:ue,refreshHistory:me}=$t(a),{sortConfig:q,handleSort:pe,clearSort:he}=Kt(),S=Ft(c);u.useEffect(()=>{const y=new URLSearchParams(t);c!=null?y.set("investigate",String(c)):y.delete("investigate"),s(y,{replace:!0})},[c]);const _=u.useMemo(()=>g.find(y=>y.job_id===a),[g,a]),B=async()=>{if(!a||!l){m(!0),ce("Please select a Reference Job and upload Current Data.");return}m(!1),await xe({selectedJob:a,file:l,job:_,thresholds:p})&&me()},ge=()=>{N&&Ht(N,_==null?void 0:_.dataset_name)},be=u.useMemo(()=>a?{job:a}:{},[a]);return e.jsxs("div",{className:"p-6 w-full text-slate-900 dark:text-slate-100",children:[e.jsx("div",{className:"flex justify-between items-center mb-6",children:e.jsx("h1",{className:"text-2xl font-bold",children:"Data Drift Analysis"})}),e.jsxs("div",{className:"bg-white dark:bg-slate-800 rounded-lg shadow mb-6 border dark:border-slate-700",children:[e.jsx(qt,{jobs:g,selectedJob:a,setSelectedJob:n,file:l,setFile:d,submitAttempted:f,loading:K,refreshing:k,showThresholds:x,onCalculate:()=>void B(),onRefresh:()=>void v(),onToggleThresholds:()=>b(y=>!y)}),x&&e.jsx(Tt,{thresholds:p,onChange:o,report:I}),_&&e.jsx(Dt,{job:_,onUpdateDescription:y=>w(_.job_id,y)}),e.jsx(Bt,{error:U,errorKind:de,onRetry:()=>void B()})]}),!N&&!K&&!U&&e.jsx(Nt,{}),N&&e.jsxs("div",{className:"bg-white dark:bg-slate-800 p-6 rounded-lg shadow border dark:border-slate-700",children:[e.jsx(Et,{report:N}),e.jsx(Ct,{missingColumns:N.missing_columns,newColumns:N.new_columns}),e.jsx(xt,{showOnlyDrifted:h,onToggleDrifted:()=>j(y=>!y),sortConfig:q,onClearSort:he,onExport:ge}),e.jsx(vt,{report:N,showOnlyDrifted:h,sortConfig:q,onSort:pe,columnSparklines:ue})]}),e.jsx(ut,{history:H}),e.jsx(ct,{history:H,onInvestigate:i}),e.jsx(dt,{alertId:c,detail:S.detail,loading:S.loading,error:S.error,actionPending:S.actionPending,onApplyDisposition:S.applyDisposition,onRetry:()=>void S.refresh(),onClose:()=>i(null),filters:be})]})};export{Qt as DataDriftPage}; diff --git a/static/ml_canvas/assets/DeploymentsPage-DKzmwjpY.js b/static/ml_canvas/assets/DeploymentsPage-BeXYd7e4.js similarity index 99% rename from static/ml_canvas/assets/DeploymentsPage-DKzmwjpY.js rename to static/ml_canvas/assets/DeploymentsPage-BeXYd7e4.js index a262b0ce3..ae48e026a 100644 --- a/static/ml_canvas/assets/DeploymentsPage-DKzmwjpY.js +++ b/static/ml_canvas/assets/DeploymentsPage-BeXYd7e4.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as s,c as T,d as U,C as O,B as q,e as z,P as C}from"./vendor-utils-_6D5wMFs.js";import{u as G,a as K,d as h,p as Q,E as v,L as F,b as W,t as u,R as p}from"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";const X=r=>!r||r.toLowerCase()==="unknown",i=r=>r.version!==void 0&&r.version!==null?`${r.model_type} v${r.version} (job ${r.job_id})`:`${r.model_type} (job ${r.job_id})`,M=({deployment:r})=>{const t=r.version!==void 0&&r.version!==null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs",children:[e.jsx(p,{recordRef:{kind:"job",jobId:r.job_id},label:`Job ${r.job_id.slice(0,8)}`,origin:"/deployments"}),t?e.jsx(p,{recordRef:{kind:"modelVersion",jobId:r.job_id,version:String(r.version)},label:`Version ${r.version}`,origin:"/deployments"}):e.jsx("span",{className:"text-slate-400 italic",title:"No target available",children:"Version unavailable"}),X(r.dataset_id)?e.jsx("span",{className:"text-slate-400 italic",title:"No target available",children:"No dataset available"}):e.jsx(p,{recordRef:{kind:"dataset",datasetId:r.dataset_id},label:"Dataset",origin:"/deployments"}),r.previous_deployment_id!==void 0&&r.previous_deployment_id!==null?e.jsx(p,{recordRef:{kind:"deployment",deploymentId:r.previous_deployment_id},label:`Replaced deployment #${r.previous_deployment_id}`,origin:"/deployments"}):e.jsx("span",{className:"text-slate-400 italic",children:"No prior deployment"})]})},re=()=>{const[r]=G(),[t,P]=s.useState(null),[m,V]=s.useState([]),[n,f]=s.useState(!1),[k,N]=s.useState(null),[w,_]=s.useState(!1),[R,D]=s.useState(null),[$,I]=s.useState(null),[b,S]=s.useState(null),E=K(),o=s.useCallback(async()=>{f(!0),N(null);try{const[a,l]=await Promise.all([h.getActive(),h.getHistory(50,0)]);P(a),V(l)}catch(a){console.error("Failed to load deployments",a),N("Failed to load deployment data.")}finally{f(!1)}},[]);s.useEffect(()=>{o()},[o]);const d=s.useMemo(()=>Q(r),[r]),c=(d==null?void 0:d.ref.kind)==="deployment"?d.ref.deploymentId:null,x=(d==null?void 0:d.ref.kind)==="modelVersion"?d.ref.jobId:null,j=s.useRef(null),y=s.useCallback(a=>c!==null&&a.id===c||x!==null&&a.job_id===x,[c,x]);s.useEffect(()=>{var a;c===null&&x===null||n||(a=j.current)==null||a.scrollIntoView({block:"center",behavior:"smooth"})},[c,x,n,m,t]);const H=async()=>{!t||!await E({title:"Deactivate deployment?",message:`Deactivate ${i(t)}? It will no longer serve predictions.`,confirmLabel:"Deactivate",variant:"danger"})||await A(t)},A=async a=>{I(null),_(!0);try{await h.deactivate(),await o(),u.success("Deployment deactivated",i(a))}catch(l){console.error("Failed to deactivate",l);const g=l.message||"Failed to deactivate deployment.";I(g),u.error(`Failed to deactivate ${i(a)}`,g)}finally{_(!1)}},J=async a=>{await E({title:"Redeploy model?",message:`Redeploy ${i(a)}? This will replace the currently active deployment${t?` (${i(t)})`:""}.`,confirmLabel:"Redeploy"})&&await L(a)},L=async a=>{S(null),D(a.job_id);try{await h.deployModel(a.job_id),await o(),u.success("Model redeployed",i(a))}catch(l){console.error("Failed to redeploy",l);const g=l.message||"Failed to redeploy model.";S({jobId:a.job_id,message:g}),u.error(`Failed to redeploy ${i(a)}`,g)}finally{D(null)}},B=()=>t?e.jsxs("div",{ref:y(t)?j:null,className:`bg-white dark:bg-gray-800 rounded-xl border shadow-sm overflow-hidden ${y(t)?"border-blue-400 dark:border-blue-500 ring-2 ring-blue-200 dark:ring-blue-900":"border-green-200 dark:border-green-900"}`,children:[e.jsxs("div",{className:"p-6 border-b border-gray-100 dark:border-gray-700 flex justify-between items-start",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 bg-green-100 dark:bg-green-900/30 rounded-lg",children:e.jsx(q,{className:"w-8 h-8 text-green-600 dark:text-green-400"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:t.model_type}),e.jsxs("span",{className:"px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 text-xs font-medium rounded-full flex items-center gap-1",children:[e.jsx(z,{className:"w-3 h-3"})," Active"]})]}),e.jsx("div",{className:"mt-1",children:e.jsx(M,{deployment:t})}),e.jsxs("p",{className:"text-xs text-gray-400 mt-2",children:["Deployed: ",new Date(t.created_at).toLocaleString()]})]})]}),e.jsxs("button",{onClick:()=>{H()},disabled:w,className:"flex items-center gap-2 px-4 py-2 bg-red-50 hover:bg-red-100 text-red-600 dark:bg-red-900/20 dark:hover:bg-red-900/30 dark:text-red-400 rounded-lg transition-colors text-sm font-medium disabled:opacity-50",children:[w?e.jsx("div",{className:"w-4 h-4 border-2 border-red-600 border-t-transparent rounded-full animate-spin"}):e.jsx(C,{className:"w-4 h-4"}),"Deactivate"]})]}),$&&e.jsx("div",{className:"border-b border-gray-100 dark:border-gray-700",children:e.jsx(v,{error:`Failed to deactivate ${i(t)}: ${$}`,onRetry:()=>A(t)})}),e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 text-xs font-mono text-gray-500 dark:text-gray-400 break-all",children:["Artifact URI: ",t.artifact_uri]})]}):n?e.jsx(F,{message:"Loading active deployment..."}):e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-dashed border-gray-300 dark:border-gray-700 p-8 text-center",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx(C,{className:"w-6 h-6 text-gray-400"})}),e.jsx("h3",{className:"text-gray-900 dark:text-gray-100 font-medium",children:"No Active Model"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Deploy a model from the Experiments page to see it here."})]});return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 dark:bg-gray-900 overflow-hidden",children:[e.jsxs("div",{className:"bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 p-6 flex justify-between items-center shrink-0",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold text-gray-800 dark:text-gray-100",children:"Model Deployments"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Manage active models and view deployment history"})]}),e.jsx("button",{onClick:()=>{o()},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 transition-colors",title:"Refresh","aria-label":"Refresh deployments",children:e.jsx(T,{className:`w-5 h-5 ${n?"animate-spin":""}`})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8",children:[k&&e.jsx(v,{error:k,onRetry:()=>o()}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-medium text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2",children:[e.jsx(U,{className:"w-5 h-5 text-green-500"}),"Active Deployment"]}),B()]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-medium text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2",children:[e.jsx(O,{className:"w-5 h-5 text-blue-500"}),"Deployment History"]}),b&&e.jsx("div",{className:"mb-4",children:e.jsx(v,{error:`Failed to redeploy job ${b.jobId}: ${b.message}`,onRetry:()=>{const a=m.find(l=>l.job_id===b.jobId);return a?L(a):void 0}})}),e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm text-left",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900/50 text-gray-500 dark:text-gray-400 font-medium border-b border-gray-200 dark:border-gray-700",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3",children:"Status"}),e.jsx("th",{className:"px-6 py-3",children:"Model Type"}),e.jsx("th",{className:"px-6 py-3",children:"Lineage"}),e.jsx("th",{className:"px-6 py-3",children:"Deployed At"}),e.jsx("th",{className:"px-6 py-3 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:m.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,children:n?e.jsx(F,{message:"Loading deployment history..."}):e.jsx(W,{title:"No deployment history found."})})}):m.map(a=>e.jsxs("tr",{ref:y(a)?j:null,className:`hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${y(a)?"bg-blue-50 dark:bg-blue-900/20 ring-1 ring-inset ring-blue-300 dark:ring-blue-700":""}`,children:[e.jsx("td",{className:"px-6 py-4",children:a.is_active?e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500"}),"Active"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400"}),"Inactive"]})}),e.jsx("td",{className:"px-6 py-4 font-medium text-gray-900 dark:text-gray-100",children:a.model_type}),e.jsx("td",{className:"px-6 py-4",children:e.jsx(M,{deployment:a})}),e.jsx("td",{className:"px-6 py-4 text-gray-500 dark:text-gray-400",children:new Date(a.created_at).toLocaleString()}),e.jsx("td",{className:"px-6 py-4 text-right",children:!a.is_active&&e.jsx("button",{onClick:()=>{J(a)},disabled:R===a.job_id,"aria-label":`Redeploy ${i(a)}`,className:"text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 font-medium text-xs disabled:opacity-50",children:R===a.job_id?"Redeploying...":"Redeploy"})})]},a.id))})]})})})]})]})]})};export{re as DeploymentsPage}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as s,c as T,d as U,C as O,B as q,e as z,P as C}from"./vendor-utils-_6D5wMFs.js";import{u as G,a as K,d as h,p as Q,E as v,L as F,b as W,t as u,R as p}from"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";const X=r=>!r||r.toLowerCase()==="unknown",i=r=>r.version!==void 0&&r.version!==null?`${r.model_type} v${r.version} (job ${r.job_id})`:`${r.model_type} (job ${r.job_id})`,M=({deployment:r})=>{const t=r.version!==void 0&&r.version!==null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs",children:[e.jsx(p,{recordRef:{kind:"job",jobId:r.job_id},label:`Job ${r.job_id.slice(0,8)}`,origin:"/deployments"}),t?e.jsx(p,{recordRef:{kind:"modelVersion",jobId:r.job_id,version:String(r.version)},label:`Version ${r.version}`,origin:"/deployments"}):e.jsx("span",{className:"text-slate-400 italic",title:"No target available",children:"Version unavailable"}),X(r.dataset_id)?e.jsx("span",{className:"text-slate-400 italic",title:"No target available",children:"No dataset available"}):e.jsx(p,{recordRef:{kind:"dataset",datasetId:r.dataset_id},label:"Dataset",origin:"/deployments"}),r.previous_deployment_id!==void 0&&r.previous_deployment_id!==null?e.jsx(p,{recordRef:{kind:"deployment",deploymentId:r.previous_deployment_id},label:`Replaced deployment #${r.previous_deployment_id}`,origin:"/deployments"}):e.jsx("span",{className:"text-slate-400 italic",children:"No prior deployment"})]})},re=()=>{const[r]=G(),[t,P]=s.useState(null),[m,V]=s.useState([]),[n,f]=s.useState(!1),[k,N]=s.useState(null),[w,_]=s.useState(!1),[R,D]=s.useState(null),[$,I]=s.useState(null),[b,S]=s.useState(null),E=K(),o=s.useCallback(async()=>{f(!0),N(null);try{const[a,l]=await Promise.all([h.getActive(),h.getHistory(50,0)]);P(a),V(l)}catch(a){console.error("Failed to load deployments",a),N("Failed to load deployment data.")}finally{f(!1)}},[]);s.useEffect(()=>{o()},[o]);const d=s.useMemo(()=>Q(r),[r]),c=(d==null?void 0:d.ref.kind)==="deployment"?d.ref.deploymentId:null,x=(d==null?void 0:d.ref.kind)==="modelVersion"?d.ref.jobId:null,j=s.useRef(null),y=s.useCallback(a=>c!==null&&a.id===c||x!==null&&a.job_id===x,[c,x]);s.useEffect(()=>{var a;c===null&&x===null||n||(a=j.current)==null||a.scrollIntoView({block:"center",behavior:"smooth"})},[c,x,n,m,t]);const H=async()=>{!t||!await E({title:"Deactivate deployment?",message:`Deactivate ${i(t)}? It will no longer serve predictions.`,confirmLabel:"Deactivate",variant:"danger"})||await A(t)},A=async a=>{I(null),_(!0);try{await h.deactivate(),await o(),u.success("Deployment deactivated",i(a))}catch(l){console.error("Failed to deactivate",l);const g=l.message||"Failed to deactivate deployment.";I(g),u.error(`Failed to deactivate ${i(a)}`,g)}finally{_(!1)}},J=async a=>{await E({title:"Redeploy model?",message:`Redeploy ${i(a)}? This will replace the currently active deployment${t?` (${i(t)})`:""}.`,confirmLabel:"Redeploy"})&&await L(a)},L=async a=>{S(null),D(a.job_id);try{await h.deployModel(a.job_id),await o(),u.success("Model redeployed",i(a))}catch(l){console.error("Failed to redeploy",l);const g=l.message||"Failed to redeploy model.";S({jobId:a.job_id,message:g}),u.error(`Failed to redeploy ${i(a)}`,g)}finally{D(null)}},B=()=>t?e.jsxs("div",{ref:y(t)?j:null,className:`bg-white dark:bg-gray-800 rounded-xl border shadow-sm overflow-hidden ${y(t)?"border-blue-400 dark:border-blue-500 ring-2 ring-blue-200 dark:ring-blue-900":"border-green-200 dark:border-green-900"}`,children:[e.jsxs("div",{className:"p-6 border-b border-gray-100 dark:border-gray-700 flex justify-between items-start",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 bg-green-100 dark:bg-green-900/30 rounded-lg",children:e.jsx(q,{className:"w-8 h-8 text-green-600 dark:text-green-400"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"text-xl font-semibold text-gray-900 dark:text-gray-100",children:t.model_type}),e.jsxs("span",{className:"px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 text-xs font-medium rounded-full flex items-center gap-1",children:[e.jsx(z,{className:"w-3 h-3"})," Active"]})]}),e.jsx("div",{className:"mt-1",children:e.jsx(M,{deployment:t})}),e.jsxs("p",{className:"text-xs text-gray-400 mt-2",children:["Deployed: ",new Date(t.created_at).toLocaleString()]})]})]}),e.jsxs("button",{onClick:()=>{H()},disabled:w,className:"flex items-center gap-2 px-4 py-2 bg-red-50 hover:bg-red-100 text-red-600 dark:bg-red-900/20 dark:hover:bg-red-900/30 dark:text-red-400 rounded-lg transition-colors text-sm font-medium disabled:opacity-50",children:[w?e.jsx("div",{className:"w-4 h-4 border-2 border-red-600 border-t-transparent rounded-full animate-spin"}):e.jsx(C,{className:"w-4 h-4"}),"Deactivate"]})]}),$&&e.jsx("div",{className:"border-b border-gray-100 dark:border-gray-700",children:e.jsx(v,{error:`Failed to deactivate ${i(t)}: ${$}`,onRetry:()=>A(t)})}),e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 text-xs font-mono text-gray-500 dark:text-gray-400 break-all",children:["Artifact URI: ",t.artifact_uri]})]}):n?e.jsx(F,{message:"Loading active deployment..."}):e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-dashed border-gray-300 dark:border-gray-700 p-8 text-center",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-3",children:e.jsx(C,{className:"w-6 h-6 text-gray-400"})}),e.jsx("h3",{className:"text-gray-900 dark:text-gray-100 font-medium",children:"No Active Model"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Deploy a model from the Experiments page to see it here."})]});return e.jsxs("div",{className:"h-full flex flex-col bg-gray-50 dark:bg-gray-900 overflow-hidden",children:[e.jsxs("div",{className:"bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 p-6 flex justify-between items-center shrink-0",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold text-gray-800 dark:text-gray-100",children:"Model Deployments"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Manage active models and view deployment history"})]}),e.jsx("button",{onClick:()=>{o()},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-500 transition-colors",title:"Refresh","aria-label":"Refresh deployments",children:e.jsx(T,{className:`w-5 h-5 ${n?"animate-spin":""}`})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8",children:[k&&e.jsx(v,{error:k,onRetry:()=>o()}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-medium text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2",children:[e.jsx(U,{className:"w-5 h-5 text-green-500"}),"Active Deployment"]}),B()]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-medium text-gray-800 dark:text-gray-200 mb-4 flex items-center gap-2",children:[e.jsx(O,{className:"w-5 h-5 text-blue-500"}),"Deployment History"]}),b&&e.jsx("div",{className:"mb-4",children:e.jsx(v,{error:`Failed to redeploy job ${b.jobId}: ${b.message}`,onRetry:()=>{const a=m.find(l=>l.job_id===b.jobId);return a?L(a):void 0}})}),e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm text-left",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900/50 text-gray-500 dark:text-gray-400 font-medium border-b border-gray-200 dark:border-gray-700",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3",children:"Status"}),e.jsx("th",{className:"px-6 py-3",children:"Model Type"}),e.jsx("th",{className:"px-6 py-3",children:"Lineage"}),e.jsx("th",{className:"px-6 py-3",children:"Deployed At"}),e.jsx("th",{className:"px-6 py-3 text-right",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-700",children:m.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,children:n?e.jsx(F,{message:"Loading deployment history..."}):e.jsx(W,{title:"No deployment history found."})})}):m.map(a=>e.jsxs("tr",{ref:y(a)?j:null,className:`hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${y(a)?"bg-blue-50 dark:bg-blue-900/20 ring-1 ring-inset ring-blue-300 dark:ring-blue-700":""}`,children:[e.jsx("td",{className:"px-6 py-4",children:a.is_active?e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-green-500"}),"Active"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400"}),"Inactive"]})}),e.jsx("td",{className:"px-6 py-4 font-medium text-gray-900 dark:text-gray-100",children:a.model_type}),e.jsx("td",{className:"px-6 py-4",children:e.jsx(M,{deployment:a})}),e.jsx("td",{className:"px-6 py-4 text-gray-500 dark:text-gray-400",children:new Date(a.created_at).toLocaleString()}),e.jsx("td",{className:"px-6 py-4 text-right",children:!a.is_active&&e.jsx("button",{onClick:()=>{J(a)},disabled:R===a.job_id,"aria-label":`Redeploy ${i(a)}`,className:"text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 font-medium text-xs disabled:opacity-50",children:R===a.job_id?"Redeploying...":"Redeploy"})})]},a.id))})]})})})]})]})]})};export{re as DeploymentsPage}; diff --git a/static/ml_canvas/assets/EDAPage-BYX7As83.js b/static/ml_canvas/assets/EDAPage-D-AvDDu5.js similarity index 99% rename from static/ml_canvas/assets/EDAPage-BYX7As83.js rename to static/ml_canvas/assets/EDAPage-D-AvDDu5.js index 1c626286f..610dc05ce 100644 --- a/static/ml_canvas/assets/EDAPage-BYX7As83.js +++ b/static/ml_canvas/assets/EDAPage-D-AvDDu5.js @@ -1,4 +1,4 @@ -import{j as i,u as nr,a as rr,P as Ct,i as ar,B as or,C as lr,M as hs,H as Zn}from"./vendor-flow-bDma3vSM.js";import{al as wt,a as k,aj as dr,am as cr,O as je,c as ti,Q as po,m as Ci,an as xo,ao as ws,ap as _o,aq as yo,H as vo,ar as bo,C as us,u as wo,as as hr,at as ii,e as ur,f as Gt,af as mr,ah as jo,p as fr,a4 as js,w as Li,X as gr,y as ks,au as ko,av as No,aw as Co,a9 as pr,ax as xr,aa as _r,ab as kt,j as ji,ay as Lo,az as Kt,aA as Lt,aB as ms,aC as Po,aD as fs,l as yr,aE as vr,ac as Pt,g as br,_ as Ne,B as wr,b as Yt,ag as Jt,R as So,aF as Ns,S as To,aG as Eo,h as Mo}from"./vendor-utils-_6D5wMFs.js";import{H as Ao,r as jr,s as kr,q as ls,D as zo,u as Io,t as Qt,a as Oo,M as Do,S as Nr,I as Pi,J as ht,K as Ue,O as be,C as Si,b as ct,P as Cr,T as Ro,U as Bo,W as Fo,X as ki,Y as Lr,Z as gs,_ as ps,$ as xs,a0 as Zo,L as $o,E as Ho}from"./index-BXksgzya.js";import{R as Ze,aj as Wo,ak as Vo,j as Cs,T as qe,ah as Pr,al as qo,am as Uo,an as Go,ao as Ko,ap as Yo,aq as Jo,ar as Qo,r as Xo,B as lt,C as Qe,X as Xe,Y as et,as as Sr,h as Ge,at as el,au as ds,ag as tl,ai as $n,av as Tr}from"./vendor-charts-CwfdE1jD.js";import{F as cs}from"./FormField-BxGvOnTr.js";import{r as il,a as sl}from"./vendor-plotly-Bx-86y5L.js";const jt="/api/eda",Ke={analyze:async(n,l,a,d,h)=>(await wt.post(`${jt}/${n}/analyze`,{target_col:l,exclude_cols:a,filters:d,task_type:h})).data,getLatestReport:async n=>(await wt.get(`${jt}/${n}/latest`)).data,getReport:async n=>(await wt.get(`${jt}/reports/${n}`)).data,cancelJob:async n=>(await wt.post(`${jt}/reports/${n}/cancel`)).data,getHistory:async n=>(await wt.get(`${jt}/${n}/history`)).data,getDecomposition:async(n,l,a,d,h)=>(await wt.post(`${jt}/${n}/decomposition`,{measure_col:l,measure_agg:a,split_col:d,filters:h})).data},Hn={x:"",y:"",z:"",color:"",is3D:!1,isPCA3D:!1},Wn=n=>`${n.column}${n.operator}${JSON.stringify(n.value)}`,nl=(n,l)=>n.length!==l.length?!1:n.every((a,d)=>Wn(a)===Wn(l[d])),ie=Ao((n,l)=>({activeTab:"dashboard",selectedDataset:null,targetCol:"",taskType:"",excludedColsDraft:[],excludedColsApplied:[],filtersDraft:[],filtersApplied:[],scatter:{...Hn},setActiveTab:a=>n({activeTab:a}),setSelectedDataset:a=>n({selectedDataset:a}),setTargetCol:a=>n({targetCol:a}),setTaskType:a=>n({taskType:a}),toggleExclude:(a,d)=>n(h=>{const u=h.excludedColsDraft.includes(a);return d?u?h:{excludedColsDraft:[...h.excludedColsDraft,a]}:u?{excludedColsDraft:h.excludedColsDraft.filter(m=>m!==a)}:h}),setExcludedDraft:a=>n({excludedColsDraft:a}),setExcludedApplied:a=>n({excludedColsApplied:a}),applyExcluded:()=>n({excludedColsApplied:[...l().excludedColsDraft]}),addFilterDraft:a=>n(d=>({filtersDraft:[...d.filtersDraft,a]})),removeFilterDraft:a=>n(d=>({filtersDraft:d.filtersDraft.filter((h,u)=>u!==a)})),clearFiltersDraft:()=>n({filtersDraft:[]}),setFiltersDraft:a=>n({filtersDraft:a}),setFiltersApplied:a=>n({filtersApplied:a}),applyFilters:()=>n(a=>({filtersApplied:[...a.filtersDraft]})),setScatter:a=>n(d=>({scatter:{...d.scatter,...a}})),resetForDataset:()=>n({excludedColsDraft:[],excludedColsApplied:[],filtersDraft:[],filtersApplied:[],targetCol:"",activeTab:"dashboard",scatter:{...Hn}})})),rl=n=>{if(n.excludedColsApplied.length!==n.excludedColsDraft.length)return!0;const l=new Set(n.excludedColsApplied);for(const a of n.excludedColsDraft)if(!l.has(a))return!0;return!1},al=n=>!nl(n.filtersDraft,n.filtersApplied),Ie={datasets:["eda","datasets"],report:n=>["eda","report",n],history:n=>["eda","history",n],reportById:n=>["eda","reportById",n]},ol=n=>{const l=jr();return kr({mutationFn:a=>Ke.cancelJob(a),onSuccess:()=>{l.invalidateQueries({queryKey:Ie.history(n)}),l.invalidateQueries({queryKey:Ie.report(n)})}})};function _s(n){if(n==null)return null;const l=n.trim();if(!/^\d+$/.test(l))return null;const a=Number(l);return a>0?a:null}function ll(n,l,a){const d=_s(n);if(d!==null)return d;if(l!==null)return l;const h=a[0];return h===void 0?null:_s(String(h.id))}function dl(n,l,a){return n===null||!a?!1:!l.some(d=>Number(d.id)===n)}function cl(n,l){return l===null?!1:_s(n)===null}function hl(n){return n.name.trim()||`Dataset ${n.id}`}function ul(n){const l=String(n.id);return l.length<=6?l:l.slice(-6)}function ml(n){const l=n.map(d=>hl(d)),a=new Map;for(const d of l)a.set(d,(a.get(d)??0)+1);return n.map((d,h)=>{const u=l[h];return(a.get(u)??0)>1?{value:d.id,label:`${u} (${ul(d)})`}:{value:d.id,label:u}})}function fl(n){const l=ls({queryKey:Ie.datasets,queryFn:()=>zo.getUsable()}),a=k.useMemo(()=>l.data??[],[l.data]),d=k.useMemo(()=>ml(a),[a]),h=ls({queryKey:Ie.report(n??null),queryFn:async()=>{var _;try{return await Ke.getLatestReport(n)}catch(v){if(((_=v==null?void 0:v.response)==null?void 0:_.status)===404)return null;throw v}},enabled:n!=null,refetchInterval:_=>{const v=_.state.data;return v&&v.status==="PENDING"?3e3:!1}}),u=h.data??null,m=h.isLoading,p=h.isError?"Failed to load report":null,N=ls({queryKey:Ie.history(n??null),queryFn:()=>Ke.getHistory(n),enabled:n!=null,refetchInterval:(u==null?void 0:u.status)==="PENDING"?3e3:!1}).data??[];return{datasetsQuery:l,datasets:a,datasetOptions:d,reportQuery:h,report:u,loading:m,error:p,history:N}}function gl(){const[n,l]=Io(),a=jr(),[d,h]=k.useState(!1),[u,m]=k.useState(!1),[p,g]=k.useState(!1),N=k.useRef(!1),_=k.useRef(null),v=ie(I=>I.activeTab),b=ie(I=>I.setActiveTab),j=ie(I=>I.selectedDataset),C=ie(I=>I.setSelectedDataset),w=ie(I=>I.targetCol),S=ie(I=>I.setTargetCol),E=ie(I=>I.taskType),T=ie(I=>I.setTaskType),O=ie(I=>I.excludedColsDraft),le=ie(I=>I.excludedColsApplied),ge=ie(I=>I.filtersDraft),pe=ie(I=>I.filtersApplied),Pe=ie(I=>I.scatter),xe=ie(I=>I.setScatter),K=ie(rl),Q=ie(al),{datasetsQuery:q,datasets:ee,datasetOptions:R,reportQuery:B,report:F,loading:X,error:re,history:A}=fl(j),ae=kr({mutationFn:I=>Ke.analyze(j,w||void 0,I.excluded,I.filters,E||void 0),onSuccess:()=>{a.invalidateQueries({queryKey:Ie.report(j??null)}),a.invalidateQueries({queryKey:Ie.history(j??null)})},onSettled:()=>{N.current=!1,g(!1)}}),z=ae.isPending||p,H=n.get("dataset_id");k.useEffect(()=>{const I=ll(H,j,ee);I!==j&&C(I)},[H,ee,j,C]),k.useEffect(()=>{if(!cl(H,j))return;const I=new URLSearchParams(n);I.set("dataset_id",String(j)),l(I,{replace:!0})},[H,j,n,l]);const se=dl(j,ee,q.isSuccess);k.useEffect(()=>{ie.getState().resetForDataset(),_.current=null},[j]);const ne=k.useMemo(()=>{const I=F==null?void 0:F.profile_data;if(!I)return null;const he=new Set(O),Se={};return I.columns&&Object.entries(I.columns).forEach(([Ce,ut])=>{he.has(Ce)||(Se[Ce]=ut)}),{...I,columns:Se,excluded_columns:O}},[F==null?void 0:F.profile_data,O]),U=(I,he)=>{if(!j)return;const Se=Array.isArray(I)?I:le,Ce=Array.isArray(he)?he:pe;ae.mutate({excluded:Se,filters:Ce})},W=async I=>{if(j){m(!0);try{const he=await a.fetchQuery({queryKey:Ie.reportById(I),queryFn:()=>Ke.getReport(I)});a.setQueryData(Ie.report(j),he)}catch(he){Qt.error("Failed to load report",String(he))}finally{m(!1)}}},$=(I,he,Se)=>{const Ce={column:I,operator:Se||"==",value:he};ie.getState().addFilterDraft(Ce)},ce=I=>{ie.getState().removeFilterDraft(I)},ye=I=>{const he=ie.getState();he.setFiltersDraft([...he.filtersDraft,...I])},Oe=()=>{ie.getState().setFiltersDraft(pe)},St=()=>{if(N.current||z)return;N.current=!0,g(!0);const I=ie.getState().filtersDraft;ie.getState().applyFilters(),U(void 0,I)},Tt=(I,he)=>{ie.getState().toggleExclude(I,he)},tt=()=>{const I=ie.getState().excludedColsDraft;ie.getState().applyExcluded(),U(I)};k.useEffect(()=>{var I;if(F&&F.profile_data){const he=`${j}:${F.id}:${F.status}`;if(_.current===he)return;_.current=he,S(F.profile_data.target_col??"");const Se=Array.isArray(F.profile_data.excluded_columns)?F.profile_data.excluded_columns:[];ie.getState().setExcludedApplied(Se),ie.getState().setExcludedDraft(Se);const Ce=((I=F.config)==null?void 0:I.filters)??[];ie.getState().setFiltersApplied(Ce),ie.getState().setFiltersDraft(Ce)}},[F,j,S]);const Et=w?A.find(I=>I.target_col===w&&I.status==="COMPLETED"):null;return{searchParams:n,setSearchParams:l,queryClient:a,showHistoryModal:d,setShowHistoryModal:h,isLoadingReport:u,activeTab:v,setActiveTab:b,selectedDataset:j,targetCol:w,setTargetCol:S,taskType:E,setTaskType:T,excludedColsDraft:O,filtersDraft:ge,filtersApplied:pe,scatter:Pe,setScatter:xe,excludedDirty:K,filtersDirty:Q,datasetOptions:R,reportQuery:B,report:F,loading:X,error:re,history:A,analyzeMutation:ae,analyzing:z,selectionUnavailable:se,profileForUi:ne,runAnalysis:U,loadSpecificReport:W,handleAddFilter:$,handleAddFilters:ye,handleRemoveFilter:ce,handleResetFilters:Oe,handleApplyFilters:St,handleToggleExclude:Tt,handleApplyExcluded:tt,existingReport:Et}}function pl(n){return i.jsx(i.Fragment,{children:i.jsxs("header",{className:"flex-none bg-white dark:bg-slate-900 border-b border-gray-200 dark:border-gray-800 px-4 py-2 flex flex-wrap items-center justify-between gap-3 z-20 shadow-sm lg:h-16 lg:flex-nowrap lg:py-0 lg:gap-4",children:[i.jsx(xl,{...n}),i.jsx(_l,{...n}),i.jsx(bl,{...n})]})})}function xl(n){const{report:l,selectionUnavailable:a,selectedDataset:d,searchParams:h,setSearchParams:u,datasetOptions:m}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex items-center gap-4 lg:gap-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-lg font-bold text-gray-900 dark:text-white leading-tight",children:"Exploratory Analysis"}),l&&l.created_at&&i.jsxs("p",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:["Last analyzed: ",new Date(l.created_at).toLocaleString()]})]}),i.jsx("div",{className:"h-8 w-px bg-gray-200 dark:bg-gray-700 mx-2"}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("label",{htmlFor:"eda-toolbar-dataset",className:"text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:"Dataset"}),i.jsxs("select",{id:"eda-toolbar-dataset",value:a?"":d||"",onChange:p=>{const g=new URLSearchParams(h);g.set("dataset_id",p.target.value),u(g)},className:"block w-48 text-sm font-medium bg-transparent border-none p-0 focus:ring-0 text-gray-900 dark:text-white cursor-pointer hover:text-blue-600",children:[i.jsx("option",{value:"",disabled:!0,children:"Select a dataset"}),m.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))]})]})]})})}function _l(n){const{taskType:l,setTaskType:a,report:d}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-wrap items-center gap-3 bg-gray-50 dark:bg-gray-800/50 p-1.5 rounded-lg border border-gray-200 dark:border-gray-700 lg:flex-nowrap lg:gap-4",children:[i.jsx(yl,{...n}),i.jsx("div",{className:"w-px h-8 bg-gray-200 dark:bg-gray-700"}),i.jsxs("div",{className:"flex flex-col px-2",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("label",{htmlFor:"eda-toolbar-task-type",className:"text-[10px] font-medium text-gray-400 uppercase tracking-wider",children:"Task Type"}),i.jsxs("div",{className:"group relative",children:[i.jsx(cr,{className:"w-3 h-3 text-gray-400 cursor-help"}),i.jsx("div",{className:"absolute bottom-full mb-2 w-56 p-2 bg-slate-800 text-white text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-50 pointer-events-none left-1/2 -translate-x-1/2",children:"Force Classification or Regression."})]})]}),i.jsxs("select",{id:"eda-toolbar-task-type",value:l,onChange:h=>a(h.target.value),disabled:!d||!d.profile_data,className:"block w-28 text-sm bg-transparent border-none p-0 focus:ring-0 text-gray-700 dark:text-gray-200 cursor-pointer disabled:opacity-50",children:[i.jsx("option",{value:"",children:"Auto"}),i.jsx("option",{value:"Classification",children:"Classification"}),i.jsx("option",{value:"Regression",children:"Regression"})]})]}),i.jsx(vl,{...n})]})})}function yl(n){const{targetCol:l,setTargetCol:a,report:d,excludedColsDraft:h}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-col px-2",children:[i.jsx("label",{htmlFor:"eda-toolbar-target-column",className:"text-[10px] font-medium text-gray-400 uppercase tracking-wider",children:"Target Column"}),i.jsxs("select",{id:"eda-toolbar-target-column",value:l,onChange:u=>a(u.target.value),disabled:!d||!d.profile_data,className:"block w-36 text-sm bg-transparent border-none p-0 focus:ring-0 text-gray-700 dark:text-gray-200 cursor-pointer disabled:opacity-50",children:[i.jsx("option",{value:"",children:"None"}),d&&d.profile_data&&Object.keys(d.profile_data.columns).filter(u=>!h.includes(u)).map(u=>i.jsx("option",{value:u,children:u},u))]})]})})}function vl(n){const{selectedDataset:l,runAnalysis:a,analyzing:d,existingReport:h}=n;return i.jsx(i.Fragment,{children:i.jsxs("button",{onClick:()=>l&&a(),disabled:!l||d,className:`ml-2 px-3 py-1.5 rounded text-sm font-medium transition-colors flex items-center shadow-sm ${h?"bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200 border border-gray-300 dark:border-gray-600 hover:bg-gray-50":"action-primary border border-transparent"}`,children:[d?i.jsx(je,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ci,{className:"w-4 h-4 mr-2"}),h?"Re-Run":"Analyze"]})})}function bl(n){const{existingReport:l,report:a,loadSpecificReport:d,isLoadingReport:h,setShowHistoryModal:u}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex items-center gap-3",children:[l&&a&&a.id!==l.id&&i.jsxs("button",{onClick:()=>d(l.id),disabled:h,className:"flex items-center px-3 py-1.5 text-xs bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 border border-green-200 dark:border-green-800 rounded-md hover:bg-green-100 dark:hover:bg-green-900/40 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:`Load existing from ${new Date(l.created_at).toLocaleString()}`,children:[h?i.jsx(je,{className:"w-3 h-3 mr-1 animate-spin"}):i.jsx(ti,{className:"w-3 h-3 mr-1"}),"Load Saved"]}),i.jsxs("button",{onClick:()=>u(!0),className:"flex items-center px-3 py-1.5 text-sm font-medium text-gray-600 bg-gray-50 dark:bg-gray-800 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:[i.jsx(po,{className:"w-4 h-4 mr-2"}),"History"]})]})})}function wl(n){const{history:l,report:a,loadSpecificReport:d,isLoadingReport:h}=n;return i.jsx(i.Fragment,{children:l.length>0&&i.jsxs("div",{className:"flex-none bg-white dark:bg-slate-950 border-b border-gray-100 dark:border-gray-800 px-4 py-1.5 flex items-center gap-3 overflow-x-auto z-10 shadow-[0_2px_3px_-1px_rgba(0,0,0,0.02)]",children:[i.jsx("span",{className:"text-[10px] uppercase font-bold text-gray-400 tracking-wider whitespace-nowrap",children:"Recent Targets:"}),i.jsx("div",{className:"flex gap-2",children:Array.from(new Set(l.filter(u=>u.target_col&&u.status==="COMPLETED").map(u=>u.target_col))).slice(0,8).map(u=>{var m;return i.jsxs("button",{onClick:()=>{const p=l.find(g=>g.target_col===u&&g.status==="COMPLETED");p&&d(p.id)},disabled:h,className:`px-2 py-0.5 text-xs rounded-full border transition-colors flex items-center disabled:opacity-50 disabled:cursor-not-allowed ${((m=a==null?void 0:a.profile_data)==null?void 0:m.target_col)===u?"bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800 font-medium":"bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-200"}`,children:[i.jsx(dr,{className:"w-3 h-3 mr-1"}),u]},u)})})]})})}const jl={Numeric:{badgeClass:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",iconColorClass:"text-blue-500",Icon:vo},Categorical:{badgeClass:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300",iconColorClass:"text-purple-500",Icon:yo},Boolean:{badgeClass:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300",iconColorClass:"text-amber-500",Icon:_o},DateTime:{badgeClass:"bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-300",iconColorClass:"text-teal-500",Icon:ws},Text:{badgeClass:"bg-slate-100 text-slate-800 dark:bg-slate-800 dark:text-slate-300",iconColorClass:"text-slate-500",Icon:xo}},kl={badgeClass:"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300",iconColorClass:"text-gray-500",Icon:bo};function Ls(n){return jl[n]??kl}function Nl(n){return Ls(n).badgeClass}function Cl(n){return Ls(n).iconColorClass}function Ll(n){return Ls(n).Icon}const Pl=({isOpen:n,onClose:l,history:a,datasetId:d,onSelect:h,onFetchReport:u,onRefresh:m})=>{const[p,g]=k.useState(null),[N,_]=k.useState(!1),v=k.useRef(0),b=ol(d),j=b.isPending?b.variables??null:null,C=Oo(),w=()=>{g(null),l()},S=async(T,O)=>{if(T.stopPropagation(),!!await C({title:"Cancel analysis?",message:"Are you sure you want to cancel this analysis?",confirmLabel:"Cancel job",variant:"danger"}))try{await b.mutateAsync(O),m&&m()}catch(ge){console.error("Failed to cancel job",ge),Qt.error("Failed to cancel job")}},E=async T=>{const O=++v.current;_(!0);try{const le=await u(T.id);if(O!==v.current)return;g(le)}catch(le){console.error("Failed to load report details",le),O===v.current&&Qt.error("Failed to load job details","Please try again.")}finally{O===v.current&&_(!1)}};return i.jsx(Do,{isOpen:n,onClose:w,size:p?"5xl":"2xl",title:i.jsxs("div",{className:"flex items-center gap-3",children:[p?i.jsx("button",{onClick:()=>g(null),className:"p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-colors","aria-label":"Back to history",children:i.jsx(wo,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})}):i.jsx(us,{className:"w-5 h-5 text-blue-500"}),i.jsx("span",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:p?`Analysis #${p.id} Details`:"Analysis History"})]}),footer:p?i.jsx("div",{className:"flex justify-end",children:i.jsxs("button",{onClick:()=>{h(p),w()},className:"flex items-center px-4 py-2 action-primary rounded-md transition-colors shadow-sm",children:[i.jsx(Ci,{className:"w-4 h-4 mr-2"}),"Load this Report"]})}):i.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 text-center w-full",children:"Select a previous analysis to view details."}),children:i.jsx("div",{className:"p-6",children:p?N?i.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[i.jsx(je,{className:"w-12 h-12 mb-4 animate-spin text-blue-500"}),i.jsx("p",{children:"Loading analysis details..."})]}):i.jsx(El,{selectedJob:p}):a.length===0?i.jsxs("div",{className:"text-center py-12 text-gray-500 dark:text-gray-400",children:[i.jsx(us,{className:"w-12 h-12 mx-auto mb-3 opacity-20"}),i.jsx("p",{children:"No history available for this dataset."})]}):i.jsx("div",{className:"space-y-3",children:a.map(T=>i.jsx(Sl,{job:T,handleJobClick:E,cancelling:j,handleCancel:S},T.id))})})})};function Sl({job:n,handleJobClick:l,cancelling:a,handleCancel:d}){return i.jsxs("div",{...Pi(()=>l(n)),className:"flex items-center justify-between p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-blue-500 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 cursor-pointer transition-all group",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Tl,{status:n.status}),i.jsxs("div",{children:[i.jsxs("div",{className:"font-medium text-gray-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 flex items-center gap-2",children:["Analysis #",n.id,i.jsx(Nr,{status:n.status??"unknown"})]}),i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:n.created_at?new Date(n.created_at).toLocaleString():"—"}),n.target_col&&i.jsxs("div",{className:"text-xs text-gray-400 mt-1 flex items-center gap-1",children:[i.jsx(Ci,{className:"w-3 h-3"})," Target: ",n.target_col,n.task_type&&i.jsx("span",{className:"ml-1 px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-[10px]",children:n.task_type})]})]})]}),i.jsx("div",{className:"text-right flex items-center gap-4",children:(n.status==="PENDING"||n.status==="STARTED"||n.status==="RUNNING")&&i.jsx("button",{onClick:h=>d(h,n.id),disabled:a===n.id,className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-full transition-colors",title:"Cancel Analysis",children:a===n.id?i.jsx(je,{className:"w-4 h-4 animate-spin"}):i.jsx(hr,{className:"w-4 h-4"})})})]})}function Tl({status:n}){return i.jsx("div",{className:`p-2 rounded-full ${n==="COMPLETED"?"bg-green-100 text-green-600 dark:bg-green-900/30 dark:text-green-400":n==="FAILED"?"bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400":n==="CANCELLED"?"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400":"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/30 dark:text-yellow-400"}`,children:n==="COMPLETED"?i.jsx(ur,{className:"w-5 h-5"}):n==="FAILED"?i.jsx(Gt,{className:"w-5 h-5"}):n==="CANCELLED"?i.jsx(hr,{className:"w-5 h-5"}):i.jsx(je,{className:"w-5 h-5 animate-spin"})})}function El({selectedJob:n}){var l,a;return i.jsxs("div",{className:"space-y-8",children:[i.jsx(Ml,{selectedJob:n}),((l=n.profile_data)==null?void 0:l.excluded_columns)&&n.profile_data.excluded_columns.length>0&&i.jsxs("div",{children:[i.jsxs("h3",{className:"text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2",children:[i.jsx(ii,{className:"w-4 h-4 text-gray-500"}),"Excluded Columns (",n.profile_data.excluded_columns.length,")"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:n.profile_data.excluded_columns.map(d=>i.jsx("span",{className:"px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded text-sm line-through",children:d},d))})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-gray-900 dark:text-white mb-3",children:"Variables Overview"}),i.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:i.jsxs("table",{className:"w-full text-sm text-left",children:[i.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900/50 text-gray-500 dark:text-gray-400",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-4 py-3 font-medium",children:"Name"}),i.jsx("th",{className:"px-4 py-3 font-medium",children:"Type"}),i.jsx("th",{className:"px-4 py-3 font-medium",children:"Missing"}),i.jsx("th",{className:"px-4 py-3 font-medium",children:"Distinct"})]})}),i.jsx("tbody",{className:"divide-y divide-gray-200 dark:divide-gray-700",children:((a=n.profile_data)==null?void 0:a.columns)&&Object.values(n.profile_data.columns).map(d=>{var u;const h=Ll(d.dtype);return i.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[i.jsx("td",{className:"px-4 py-3 font-medium text-gray-900 dark:text-white",children:d.name}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(h,{className:`w-4 h-4 ${Cl(d.dtype)}`}),i.jsx("span",{children:d.dtype})]})}),i.jsx("td",{className:"px-4 py-3",children:d.missing_percentage>0?i.jsxs("span",{className:"text-amber-600",children:[d.missing_percentage.toFixed(1),"%"]}):i.jsx("span",{className:"text-green-600",children:"0%"})}),i.jsx("td",{className:"px-4 py-3 text-gray-500 dark:text-gray-400",children:((u=d.categorical_stats)==null?void 0:u.unique_count)||"-"})]},d.name)})})]})})]})]})}function Ml({selectedJob:n}){var l,a,d,h,u,m;return i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1",children:[i.jsx(mr,{className:"w-4 h-4"}),i.jsx("span",{className:"text-xs uppercase font-medium",children:"Rows"})]}),i.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:((a=(l=n.profile_data)==null?void 0:l.row_count)==null?void 0:a.toLocaleString())||"-"})]}),i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1",children:[i.jsx(jo,{className:"w-4 h-4"}),i.jsx("span",{className:"text-xs uppercase font-medium",children:"Columns"})]}),i.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:((h=(d=n.profile_data)==null?void 0:d.column_count)==null?void 0:h.toLocaleString())||"-"})]}),i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1",children:[i.jsx(fr,{className:"w-4 h-4"}),i.jsx("span",{className:"text-xs uppercase font-medium",children:"Missing Cells"})]}),i.jsxs("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:[(m=(u=n.profile_data)==null?void 0:u.missing_cells_percentage)==null?void 0:m.toFixed(1),"%"]})]})]})}function Al(n){const{selectionUnavailable:l,selectedDataset:a,analyzeMutation:d,analyzing:h,runAnalysis:u}=n;return i.jsxs(i.Fragment,{children:[l&&i.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-b border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-200",children:[i.jsx(Gt,{className:"h-4 w-4 shrink-0"}),i.jsxs("span",{className:"flex-1 min-w-[12rem]",children:["Dataset #",a," isn't available for analysis — it may still be processing or have no usable columns. Pick another dataset above to continue."]})]}),d.isError&&i.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-b border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900 dark:bg-red-950/40 dark:text-red-200",children:[i.jsx(Gt,{className:"h-4 w-4 shrink-0"}),i.jsxs("span",{className:"flex-1 min-w-[12rem]",children:["Could not start the analysis: ",d.error instanceof Error?d.error.message:"the request was rejected."," ","Your dataset, target, and filter choices were kept."]}),i.jsxs("button",{onClick:()=>{const m=d.variables;u(m==null?void 0:m.excluded,m==null?void 0:m.filters)},disabled:h,className:"flex items-center rounded-md border border-red-300 px-3 py-1.5 font-medium hover:bg-red-100 disabled:opacity-50 dark:border-red-800 dark:hover:bg-red-900/40",children:[i.jsx(ti,{className:"mr-2 h-4 w-4"}),"Try again"]}),i.jsx("button",{onClick:()=>d.reset(),className:"rounded-md px-2 py-1.5 font-medium underline hover:no-underline",children:"Dismiss"})]})]})}function zl(n){const{showHistoryModal:l,setShowHistoryModal:a,history:d,selectedDataset:h,queryClient:u}=n;return i.jsx(i.Fragment,{children:i.jsx(Pl,{isOpen:l,onClose:()=>a(!1),history:d,datasetId:h??null,onRefresh:()=>u.invalidateQueries({queryKey:Ie.history(h??null)}),onFetchReport:async m=>{const p=await Ke.getReport(m);return{...p,id:p.id??m}},onSelect:m=>{var g;h&&u.setQueryData(Ie.report(h),m);const p=Array.isArray((g=m.profile_data)==null?void 0:g.excluded_columns)?m.profile_data.excluded_columns:[];ie.getState().setExcludedApplied(p),ie.getState().setExcludedDraft(p)}})})}function Il(n,l,a,d){return l?a&&!d?`${n===">"?"Greater than":n==="<"?"Less than":n===">="?"Greater than or equal to":"Less than or equal to"} needs a numeric value`:"":"Enter a filter value"}function Ol(n,l,a){const d=[">","<",">=","<="].includes(l),h=n.trim().length>0,u=l.trim().length>0,m=a.trim().length>0,p=Number.isFinite(Number(a)),g=Il(l,m,d,p);return{hasFilterColumn:h,hasFilterOperator:u,hasFilterValue:m,isComparisonOperator:d,currentFilterValueError:g}}function Dl(n){const[l,a]=k.useState(!1),[d,h]=k.useState(""),[u,m]=k.useState("=="),[p,g]=k.useState(""),[N,_]=k.useState(!1),{hasFilterColumn:v,hasFilterOperator:b,hasFilterValue:j,isComparisonOperator:C,currentFilterValueError:w}=Ol(d,u,p);return{isAddingFilter:l,setIsAddingFilter:a,newFilterCol:d,setNewFilterCol:h,newFilterOp:u,setNewFilterOp:m,newFilterVal:p,setNewFilterVal:g,filterValidationAttempted:N,setFilterValidationAttempted:_,columnError:N&&!v?"Choose a filter column":"",operatorError:N&&!b?"Choose a filter operator":"",valueError:N&&w?w:"",handleAddFilterSubmit:()=>{_(!0),!(!v||!b||!j||w)&&(n(d,C?Number(p):Number.isNaN(Number(p))?p:Number(p),u),a(!1),_(!1),h(""),m("=="),g(""))}}}const Vn=n=>`${n.column}${n.operator}${JSON.stringify(n.value)}`,Rl=(n,l)=>n.length!==l.length?!1:n.every((a,d)=>Vn(a)===Vn(l[d]));function Bl({filtersDraft:n,filtersApplied:l,filtersDirty:a,columns:d,analyzing:h,onRemoveFilter:u,onResetFilters:m,onApplyFilters:p,showFilters:g,setShowFilters:N,form:_}){const v=a||!Rl(n,l);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between w-full mb-2",children:[i.jsxs("button",{onClick:()=>N(!g),className:"flex items-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider hover:text-gray-700 dark:hover:text-gray-300",children:[i.jsxs("span",{children:["Draft Filters (",n.length,")"]}),g?i.jsx(js,{className:"w-3 h-3 ml-1"}):i.jsx(Li,{className:"w-3 h-3 ml-1"})]}),a&&i.jsx("span",{className:"text-[10px] font-medium rounded-full bg-amber-100 text-amber-800 px-2 py-0.5",children:"Pending"})]}),g&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:["Report uses ",l.length," applied filter",l.length===1?"":"s"," until you apply draft changes."]}),i.jsx(Fl,{filtersDraft:n,filtersDirty:a,analyzing:h,onRemoveFilter:u}),i.jsx(Zl,{form:_,columns:d}),i.jsx($l,{disabled:!v||h,onResetFilters:m,onApplyFilters:p})]})]})}function Fl({filtersDraft:n,filtersDirty:l,analyzing:a,onRemoveFilter:d}){return i.jsx(i.Fragment,{children:n.length>0?n.map((h,u)=>i.jsxs("div",{className:`flex items-center justify-between rounded px-2 py-1 text-xs border ${l?"bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-800":"bg-gray-50 dark:bg-gray-900/50 border-gray-200 dark:border-gray-700"}`,children:[i.jsxs("div",{className:"truncate max-w-[140px]",children:[i.jsx("span",{className:"font-medium text-blue-700 dark:text-blue-300",children:h.column}),i.jsx("span",{className:"mx-1 text-gray-500 dark:text-gray-400",children:h.operator}),i.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:String(h.value)})]}),i.jsx("button",{onClick:()=>d(u),className:"text-gray-500 dark:text-gray-400 hover:text-red-500","aria-label":`Remove filter ${u+1}`,disabled:a,children:i.jsx(gr,{className:"w-3 h-3"})})]},u)):i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"No draft filters yet."})})}function Zl({form:n,columns:l}){const{isAddingFilter:a,setIsAddingFilter:d,newFilterCol:h,setNewFilterCol:u,newFilterOp:m,setNewFilterOp:p,newFilterVal:g,setNewFilterVal:N,filterValidationAttempted:_,setFilterValidationAttempted:v,columnError:b,operatorError:j,valueError:C,handleAddFilterSubmit:w}=n;return i.jsx(i.Fragment,{children:a?i.jsxs("div",{className:"bg-white dark:bg-gray-900 p-2 rounded border border-gray-200 dark:border-gray-700 space-y-2 shadow-sm",children:[i.jsx(cs,{label:"Filter column",hideLabel:!0,required:!0,..._?{error:b}:{},children:S=>i.jsxs("select",{...S,value:h,onChange:E=>u(E.target.value),className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",children:[i.jsx("option",{value:"",disabled:!0,children:"Column"}),l.map(E=>i.jsx("option",{value:E,children:E},E))]})}),i.jsxs("div",{className:"flex gap-1",children:[i.jsx(cs,{label:"Filter operator",hideLabel:!0,required:!0,className:"w-1/3",..._?{error:j}:{},children:S=>i.jsxs("select",{...S,value:m,onChange:E=>p(E.target.value),className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",children:[i.jsx("option",{value:"==",children:"=="}),i.jsx("option",{value:"!=",children:"!="}),i.jsx("option",{value:">",children:">"}),i.jsx("option",{value:"<",children:"<"}),i.jsx("option",{value:">=",children:">="}),i.jsx("option",{value:"<=",children:"<="})]})}),i.jsx(cs,{label:"Filter value",hideLabel:!0,required:!0,className:"w-2/3",..._?{error:C}:{},children:S=>i.jsx("input",{...S,type:"text",value:g,onChange:E=>N(E.target.value),placeholder:"Value",className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",onKeyDown:E=>E.key==="Enter"&&w()})})]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{onClick:()=>{d(!1),v(!1),u(""),p("=="),N("")},className:"text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300",children:"Cancel"}),i.jsx("button",{onClick:w,className:"text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700",children:"Save draft"})]})]}):i.jsxs("button",{onClick:()=>d(!0),className:"w-full flex items-center justify-center px-2 py-1 text-xs border border-dashed border-gray-300 dark:border-gray-600 rounded text-gray-500 dark:text-gray-400 hover:text-blue-600 hover:border-blue-300 transition-colors",children:[i.jsx(ks,{className:"w-3 h-3 mr-1"})," Add Filter"]})})}function $l({disabled:n,onResetFilters:l,onApplyFilters:a}){return i.jsxs("div",{className:"flex gap-2 pt-1",children:[i.jsx("button",{onClick:l,disabled:n,className:`flex-1 text-xs px-2 py-1 rounded border transition-colors ${n?"bg-gray-100 dark:bg-gray-800 text-gray-400 border-gray-200 dark:border-gray-700 cursor-not-allowed":"bg-white dark:bg-gray-900 text-gray-600 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800"}`,children:"Reset filters"}),i.jsx("button",{onClick:a,disabled:n,className:`flex-1 text-xs px-2 py-1 rounded border transition-colors ${n?"bg-gray-100 dark:bg-gray-800 text-gray-400 border-gray-200 dark:border-gray-700 cursor-not-allowed":"bg-blue-600 text-white border-blue-700 hover:bg-blue-700"}`,children:"Apply filters"})]})}function Hl({columns:n,excludedCols:l,excludedDirty:a,analyzing:d,onToggleExclude:h,onApplyExcluded:u,showExclusions:m,setShowExclusions:p,isAddingExclusion:g,setIsAddingExclusion:N}){return i.jsxs("div",{children:[i.jsxs("button",{onClick:()=>p(!m),className:"flex items-center justify-between w-full text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2 hover:text-gray-700 dark:hover:text-gray-300",children:[i.jsxs("span",{children:["Excluded (",l.length,")"]}),m?i.jsx(js,{className:"w-3 h-3"}):i.jsx(Li,{className:"w-3 h-3"})]}),m&&i.jsxs("div",{className:"space-y-2",children:[l.map((_,v)=>i.jsxs("div",{className:"flex items-center justify-between bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded px-2 py-1 text-xs",children:[i.jsx("span",{className:"font-medium text-gray-500 dark:text-gray-400 line-through truncate max-w-[140px]",children:_}),i.jsx("button",{onClick:()=>h(_,!1),className:"text-gray-500 dark:text-gray-400 hover:text-green-500",title:"Include back",children:i.jsx(ks,{className:"w-3 h-3"})})]},v)),i.jsx(Wl,{onApplyExcluded:u,excludedDirty:a,analyzing:d}),g?i.jsxs("div",{className:"bg-white dark:bg-gray-900 p-2 rounded border border-gray-200 dark:border-gray-700 space-y-2 shadow-sm",children:[i.jsxs("select",{"aria-label":"Column to exclude from analysis",className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",onChange:_=>{_.target.value&&(h(_.target.value,!0),N(!1))},defaultValue:"",children:[i.jsx("option",{value:"",disabled:!0,children:"Select Column"}),n.filter(_=>!l.includes(_)).map(_=>i.jsx("option",{value:_,children:_},_))]}),i.jsx("button",{onClick:()=>N(!1),className:"w-full text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 text-center",children:"Cancel"})]}):i.jsxs("button",{onClick:()=>N(!0),className:"w-full flex items-center justify-center px-2 py-1 text-xs border border-dashed border-gray-300 dark:border-gray-600 rounded text-gray-500 dark:text-gray-400 hover:text-red-600 hover:border-red-300 transition-colors",children:[i.jsx(ii,{className:"w-3 h-3 mr-1"})," Exclude Column"]})]})]})}function Wl({onApplyExcluded:n,excludedDirty:l,analyzing:a}){return i.jsx("button",{onClick:n,disabled:!l||a,className:`w-full flex items-center justify-center px-2 py-1 text-xs rounded border transition-colors ${l&&!a?"bg-blue-600 text-white border-blue-700 hover:bg-blue-700":"bg-gray-100 dark:bg-gray-800 text-gray-400 border-gray-200 dark:border-gray-700 cursor-not-allowed"}`,title:l?"Apply excluded columns to re-run analysis":"No pending exclusion changes",children:"Apply changes"})}function Vl(n){return[{title:"Overview",items:[{id:"dashboard",label:"Dashboard",icon:Co,show:!0},{id:"pii",label:"PII Review",icon:pr,show:!0},{id:"sample",label:"Sample Data",icon:xr,show:!!n.sample_data},{id:"insights",label:"Smart Insights",icon:_r,show:!0}]},{title:"Univariate Analysis",items:[{id:"variables",label:"Variables",icon:kt,show:!0},{id:"outliers",label:"Outliers",icon:ji,show:!!n.outliers},{id:"target",label:"Target Analysis",icon:dr,show:!!(n.target_col&&n.target_correlations)}]},{title:"Multivariate Analysis",items:[{id:"correlations",label:"Correlations",icon:Lo,show:!!(n.correlations||n.correlations_with_target||n.causal_target_exclusion_reason)},{id:"bivariate",label:"Bivariate",icon:Kt,show:!0},{id:"pca",label:"PCA & Clusters",icon:Lt,show:!!n.pca_data||!!n.clustering}]},{title:"Structure & Causal",items:[{id:"causal",label:"Causal Graph",icon:Lt,show:!!(n.causal_graph||n.causal_target_exclusion_reason)},{id:"rules",label:"Decision Tree",icon:ms,show:!!n.rule_tree},{id:"decomposition",label:"Decomposition",icon:Po,show:!0}]},{title:"Specialized",items:[{id:"timeseries",label:"Time Series",icon:ws,show:!!n.timeseries},{id:"geospatial",label:"Geospatial",icon:fs,show:!!n.geospatial}]}]}function ql({activeTab:n,setActiveTab:l,profile:a,isCollapsed:d,setIsCollapsed:h}){const u=Vl(a);return i.jsxs("div",{className:`flex-1 overflow-y-auto ${d?"p-2":"p-3"}`,children:[i.jsxs("div",{className:`flex items-center ${d?"justify-center":"justify-between"} mb-3`,children:[!d&&i.jsx("h2",{className:"text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:"Analysis Modules"}),i.jsx("button",{onClick:()=>h(!d),className:"p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded text-gray-500 dark:text-gray-400",title:d?"Expand Sidebar":"Collapse Sidebar",children:d?i.jsx(ko,{className:"w-4 h-4"}):i.jsx(No,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"space-y-6",children:u.map((m,p)=>{const g=m.items.filter(N=>N.show);return g.length===0?null:i.jsxs("div",{children:[!d&&i.jsx("h3",{className:"px-2 text-xs font-medium text-gray-500 dark:text-gray-400 mb-2",children:m.title}),i.jsx("div",{className:"space-y-1",children:g.map(N=>i.jsx(Ul,{item:N,activeTab:n,setActiveTab:l,isCollapsed:d},N.id))})]},p)})})]})}function Ul({item:n,activeTab:l,setActiveTab:a,isCollapsed:d}){const h=l===n.id?{button:"bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",icon:"text-blue-500",current:"page"}:{button:"text-gray-600 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700",icon:"text-gray-400",current:void 0};return i.jsxs("button",{onClick:()=>a(n.id),"aria-label":n.label,"aria-current":h.current,title:d?n.label:void 0,className:`w-full flex items-center ${d?"justify-center py-2":"px-2 py-2"} text-sm font-medium rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-gray-800 ${h.button}`,children:[i.jsx(n.icon,{className:`${d?"h-5 w-5":"mr-3 h-4 w-4"} ${h.icon}`}),!d&&i.jsxs(i.Fragment,{children:[n.label,l===n.id&&i.jsx(yr,{className:"ml-auto h-4 w-4 text-blue-400"})]})]})}const Gl=n=>{const[l,a]=k.useState(!0),[d,h]=k.useState(!1),[u,m]=k.useState(!1),p=Dl(n.onAddFilter),[g,N]=k.useState(!1);return i.jsxs("div",{className:`${u?"w-14":"w-60"} bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex-shrink-0 h-full overflow-y-auto flex flex-col transition-all duration-300`,children:[!u&&n.activeTab!=="pii"&&i.jsxs("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700 space-y-3 bg-gray-50/50 dark:bg-gray-900/20",children:[i.jsx(Bl,{...n,showFilters:l,setShowFilters:a,form:p}),i.jsx(Hl,{...n,showExclusions:d,setShowExclusions:h,isAddingExclusion:g,setIsAddingExclusion:N})]}),i.jsx(ql,{activeTab:n.activeTab,setActiveTab:n.setActiveTab,profile:n.profile,isCollapsed:u,setIsCollapsed:m})]})},Kl=({profile:n})=>{if(!n)return null;const l=n.missing_cells_percentage??0,a=n.duplicate_rows??0;return i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Rows"}),i.jsx("div",{className:"text-2xl font-bold",children:(n.row_count??0).toLocaleString()})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Columns"}),i.jsx("div",{className:"text-2xl font-bold",children:n.column_count})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Missing Cells"}),i.jsxs("div",{className:"text-2xl font-bold",children:[l.toFixed(1),"%"]})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Duplicates"}),i.jsx("div",{className:"text-2xl font-bold",children:a})]}),n.vif&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"High VIF Features"}),i.jsx("div",{className:"text-2xl font-bold text-amber-600",children:Object.values(n.vif).filter(d=>d>5).length})]})]})},Yl=({alerts:n})=>{const[l,a]=k.useState(!0);return!n||n.length===0?null:i.jsxs("div",{className:"bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex justify-between items-center cursor-pointer",...Pi(()=>a(!l)),children:[i.jsxs("h3",{className:"font-medium text-amber-800 dark:text-amber-200 flex items-center",children:[i.jsx(Gt,{className:"w-4 h-4 mr-2"}),"Data Quality Alerts (",n.length,")"]}),l?i.jsx(js,{className:"w-4 h-4 text-amber-800 dark:text-amber-200"}):i.jsx(Li,{className:"w-4 h-4 text-amber-800 dark:text-amber-200"})]}),l&&i.jsx("div",{className:"max-h-40 overflow-y-auto pr-2 mt-2 animate-in slide-in-from-top-2 duration-200",children:i.jsx("ul",{className:"space-y-1",children:n.map((d,h)=>i.jsxs("li",{className:"text-sm text-amber-700 dark:text-amber-300 flex items-start",children:[i.jsx("span",{className:"mr-2",children:"•"}),i.jsxs("span",{children:[d.column&&i.jsxs("span",{className:"font-semibold",children:[d.column,": "]}),d.message]})]},h))})})]})},Jl=({profile:n,onToggleExclude:l,excludedCols:a=[]})=>{const d=ht(),h=k.useMemo(()=>{if(!(n!=null&&n.columns))return[];const m={};return Object.values(n.columns).forEach(p=>{m[String(p.dtype)]=(m[String(p.dtype)]||0)+1}),Object.entries(m).map(([p,g])=>({name:p,value:g}))},[n]),u=k.useMemo(()=>n!=null&&n.columns?Object.values(n.columns).filter(m=>m.missing_percentage>0).sort((m,p)=>p.missing_percentage-m.missing_percentage).slice(0,20).map(m=>({name:m.name,value:m.missing_percentage})):[],[n]);return i.jsxs("div",{className:"space-y-6",children:[i.jsx(Kl,{profile:n}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(mr,{className:"w-5 h-5 mr-2 text-blue-500"}),"Column Types"]}),i.jsx("div",{className:"h-64",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(Wo,{children:[i.jsx(Vo,{data:h,cx:"50%",cy:"50%",innerRadius:60,outerRadius:80,fill:"#8884d8",paddingAngle:5,dataKey:"value",children:h.map((m,p)=>i.jsx(Cs,{fill:Ue[p%Ue.length]},`cell-${p}`))}),i.jsx(qe,{contentStyle:d.tooltipContentStyle,itemStyle:d.tooltipItemStyle,labelStyle:d.tooltipLabelStyle}),i.jsx(Pr,{verticalAlign:"bottom",height:36})]})})})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(ji,{className:"w-5 h-5 mr-2 text-amber-500"}),"Top Missing Values"]}),u.length>0?i.jsx("div",{className:"h-64 overflow-y-auto pr-2 space-y-3",children:u.map((m,p)=>{const g=a.includes(m.name);return i.jsxs("div",{className:"flex items-center gap-3 text-sm group",children:[i.jsx("div",{className:"w-32 truncate text-gray-600 dark:text-gray-300 font-medium",title:m.name,children:m.name}),i.jsx("div",{className:"flex-1 h-2 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${m.value}%`,backgroundColor:`hsl(10, 80%, ${60-p*2}%)`}})}),i.jsxs("div",{className:"w-12 text-right text-gray-500 text-xs",children:[m.value.toFixed(1),"%"]}),l&&i.jsx("button",{onClick:()=>l(m.name,!g),className:`p-1.5 rounded-md transition-colors opacity-100 md:opacity-0 md:group-hover:opacity-100 focus:opacity-100 ${g?"bg-red-100 text-red-600 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 opacity-100":"text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 dark:hover:text-gray-300"}`,title:g?"Include Column":"Exclude Column","aria-label":g?"Include Column":"Exclude Column",children:g?i.jsx(ii,{className:"w-4 h-4"}):i.jsx(vr,{className:"w-4 h-4"})})]},p)})}):i.jsxs("div",{className:"h-64 flex flex-col items-center justify-center text-gray-400",children:[i.jsx(fr,{className:"w-12 h-12 mb-2 opacity-20"}),i.jsx("p",{children:"No missing values found!"})]})]})]}),i.jsx(Yl,{alerts:n.alerts??[]})]})},Ql=({profile:n})=>{const l=Array.isArray(n.recommendations)?n.recommendations:[];return i.jsx("div",{className:"mt-4 space-y-6",children:i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(_r,{className:"w-5 h-5 mr-2 text-yellow-500"}),"Smart Recommendations"]}),l.length>0?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:l.map((a,d)=>i.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/10 rounded-lg border border-blue-100 dark:border-blue-800",children:[i.jsxs("div",{className:"flex justify-between items-start mb-2",children:[i.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400 bg-white dark:bg-gray-800 px-2 py-1 rounded border border-blue-100 dark:border-blue-800",children:a.action}),a.column&&i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 font-mono",children:a.column})]}),i.jsx("h4",{className:"font-medium text-gray-900 dark:text-white text-sm mb-1",children:a.reason}),i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:a.suggestion})]},d))}):i.jsx("p",{className:"text-gray-500 dark:text-gray-400 italic",children:"No recommendations were recorded for this report."})]})})};function Xl({alerts:n=[]}){const l=n.filter(d=>d.type==="PII"),a=new Set(l.map(d=>d.column).filter(Boolean)).size;return i.jsxs("section",{id:"eda-pii-review","aria-labelledby":"eda-pii-heading",className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("h2",{id:"eda-pii-heading",className:"flex items-center gap-2 text-xl font-semibold text-gray-900 dark:text-white",children:[i.jsx(pr,{"aria-hidden":"true",className:"h-5 w-5 text-blue-600 dark:text-blue-400"}),"PII review"]}),i.jsx("p",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Review columns that may contain personally identifiable information (PII). Values and samples are not shown here."})]}),i.jsxs("div",{className:"flex gap-3 rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-800 dark:bg-blue-900/20",children:[i.jsx(Pt,{"aria-hidden":"true",className:"mt-0.5 h-5 w-5 shrink-0 text-blue-700 dark:text-blue-300"}),i.jsxs("div",{className:"space-y-1 text-sm text-blue-900 dark:text-blue-100",children:[i.jsx("p",{className:"font-semibold",children:"Advisory heuristics only"}),i.jsx("p",{children:"Matches can be false positives, and detection can miss personal information. Findings do not classify data as legally sensitive or determine compliance. This review does not mask, delete, or block data."})]})]}),l.length===0?i.jsxs("div",{className:"rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800",children:[i.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white",children:"No PII findings recorded"}),i.jsx("p",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"This profile contains no PII alerts. That does not guarantee the dataset is free of personal information."})]}):i.jsxs("div",{className:"overflow-hidden rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800",children:[i.jsxs("div",{className:"border-b border-gray-200 p-4 dark:border-gray-700",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 dark:text-white",children:[l.length," finding",l.length===1?"":"s"," across ",a," flagged column",a===1?"":"s"]}),i.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300",children:"The detector checks email and phone patterns together; it does not report which pattern matched. Findings describe the saved profile, including columns with pending exclusions."})]}),i.jsx("div",{role:"region","aria-label":"PII findings table",tabIndex:0,className:"overflow-x-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-500",children:i.jsxs("table",{className:"w-full min-w-[600px] text-left text-sm",children:[i.jsx("caption",{className:"sr-only",children:"Possible PII findings from this profile"}),i.jsx("thead",{className:"bg-gray-50 text-gray-600 dark:bg-gray-900/50 dark:text-gray-300",children:i.jsxs("tr",{children:[i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Column"}),i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Detector category"}),i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Severity"}),i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Explanation"})]})}),i.jsx("tbody",{className:"divide-y divide-gray-200 dark:divide-gray-700",children:l.map((d,h)=>{const u=d.severity==="error"?"Error":d.severity==="warning"?"Warning":d.severity==="info"?"Info":"Unspecified",m=u==="Error"?"bg-red-50 text-red-800 dark:bg-red-900/30 dark:text-red-200":u==="Warning"?"bg-amber-50 text-amber-800 dark:bg-amber-900/30 dark:text-amber-200":"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200";return i.jsxs("tr",{className:"align-top",children:[i.jsx("th",{scope:"row",className:"max-w-64 break-words px-4 py-4 font-medium text-gray-900 dark:text-white",children:d.column||"Column not specified"}),i.jsx("td",{className:"whitespace-nowrap px-4 py-4 text-gray-700 dark:text-gray-200",children:"Email / phone"}),i.jsx("td",{className:"px-4 py-4",children:i.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${m}`,children:u})}),i.jsx("td",{className:"px-4 py-4 text-gray-600 dark:text-gray-300",children:"Values may match an email address or phone number pattern. Review whether this column is appropriate for your intended use."})]},h)})})]})})]})]})}var ed=il();const Er=br(ed);var td=sl();const id=br(td),sd=id(Er),qn=["circle","square","diamond","cross","x"],nd={circle:"circle",square:"rect",diamond:"rectRot",cross:"cross",x:"crossRot"},rd={circle:"circle",square:"square",diamond:"diamond",cross:"cross",x:"x"},Un=n=>qn[n%qn.length],ad=n=>nd[n],od=n=>rd[n],ld=(n,l)=>{const a=n.localeCompare(l,"en");return a!==0||n===l?a:n{let l="Unlabeled",a=1;for(;n.has(l);)l=a===1?"Unlabeled (missing)":`Unlabeled (missing) ${a}`,a+=1;return l},si=(n,l)=>{if(!l)return[{value:null,label:"Data Points",points:n,color:Ue[0],shape:Un(0)}];const a=new Map;n.forEach(m=>{const p=m[l],g=p==null?null:String(p),N=a.get(g)??[];N.push(m),a.set(g,N)});const d=[...a.keys()].filter(m=>m!==null).sort(ld),h=d.map((m,p)=>({value:m,label:m,points:a.get(m),color:Ue[p%Ue.length],shape:Un(p)})),u=a.get(null);return u&&h.push({value:null,label:dd(new Set(d)),points:u,color:"#6b7280",shape:"cross"}),h},Mr=n=>n.map(({label:l,color:a,shape:d})=>({label:l,color:a,shape:d})),Ar=({data:n,xKey:l,yKey:a,zKey:d,labelKey:h,xLabel:u,yLabel:m,zLabel:p,height:g=600})=>{const N=k.useMemo(()=>si(n,h).map(({label:b,points:j,color:C,shape:w})=>{const S=od(w);return{x:j.map(E=>E[l]??null),y:j.map(E=>E[a]??null),z:j.map(E=>E[d]??null),mode:"markers",type:"scatter3d",name:b,marker:{size:3,opacity:.8,color:C,symbol:S},hovertemplate:`${b}
${u||l}: %{x}
${m||a}: %{y}
${p||d}: %{z}`}}),[n,l,a,d,h,u,m,p]),_=ht();return n.length===0?i.jsx("div",{className:"text-gray-500 text-sm italic p-4 text-center",children:"No data points to display"}):i.jsx("div",{style:{height:g,width:"100%"},children:i.jsx(sd,{data:N,layout:{autosize:!0,height:g,margin:{l:0,r:0,b:0,t:0},paper_bgcolor:_.bgColor,plot_bgcolor:_.bgColor,font:{color:_.textColor},scene:{xaxis:{title:{text:u||l},color:_.axisColor,gridcolor:_.gridColor},yaxis:{title:{text:m||a},color:_.axisColor,gridcolor:_.gridColor},zaxis:{title:{text:p||d},color:_.axisColor,gridcolor:_.gridColor}},showlegend:!1},useResizeHandler:!0,style:{width:"100%",height:"100%"},config:{displayModeBar:!0}})})};Uo.register(Go,Ko,Yo,Jo,Qo);const zr=({data:n,xKey:l,yKey:a,labelKey:d,xLabel:h,yLabel:u,height:m=500})=>{const p=k.useMemo(()=>si(n,d).map(({label:v,points:b,color:j,shape:C})=>({label:v,data:b.map(w=>({x:Number(w[l]),y:Number(w[a]),raw:w})),backgroundColor:j,borderColor:j,pointStyle:ad(C),pointRadius:3,pointHoverRadius:5})),[n,l,a,d]),g=ht(),N={responsive:!0,maintainAspectRatio:!1,scales:{x:{title:{display:!!h,text:h,color:g.axisColor,font:{weight:"bold"}},grid:{color:g.gridColor,lineWidth:1},ticks:{color:g.axisColor}},y:{title:{display:!!u,text:u,color:g.axisColor,font:{weight:"bold"}},grid:{color:g.gridColor,lineWidth:1},ticks:{color:g.axisColor}}},plugins:{tooltip:{callbacks:{label:_=>{const v=_.parsed;let b=_.dataset.label||"";return b&&(b+=": "),b+=`(${v.x}, ${v.y})`,b}}},legend:{display:!1}}};return i.jsx("div",{style:{height:m,width:"100%"},children:i.jsx(qo,{options:N,data:{datasets:p}})})},cd=({shape:n,color:l})=>{const a={width:12,height:12,"aria-hidden":!0};switch(n){case"square":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("rect",{x:"1",y:"1",width:"10",height:"10",fill:l})});case"diamond":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("polygon",{points:"6,0 12,6 6,12 0,6",fill:l})});case"cross":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("path",{d:"M6 1 L6 11 M1 6 L11 6",stroke:l,strokeWidth:2})});case"x":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("path",{d:"M2 2 L10 10 M10 2 L2 10",stroke:l,strokeWidth:2})});case"circle":default:return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("circle",{cx:"6",cy:"6",r:"5",fill:l})})}},Ps=({entries:n,filterThreshold:l=12})=>{const[a,d]=k.useState(""),h=k.useMemo(()=>{if(!a.trim())return n;const m=a.trim().toLowerCase();return n.filter(p=>p.label.toLowerCase().includes(m))},[n,a]);if(n.length===0)return null;const u=n.length>l;return i.jsxs("div",{className:"mt-3 border border-gray-200 dark:border-gray-700 rounded-md p-2",children:[u&&i.jsx("input",{type:"search",value:a,onChange:m=>d(m.target.value),placeholder:`Filter ${n.length} legend groups…`,"aria-label":"Filter legend groups",className:"mb-2 w-full text-xs rounded border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white px-2 py-1"}),i.jsxs("ul",{className:`flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-gray-700 dark:text-gray-300 ${u?"max-h-32 overflow-y-auto":""}`,children:[h.map(m=>i.jsxs("li",{className:"flex items-center gap-1.5",children:[i.jsx(cd,{shape:m.shape,color:m.color}),i.jsx("span",{className:"truncate max-w-[10rem]",title:m.label,children:m.label})]},m.label)),h.length===0&&i.jsxs("li",{className:"italic text-gray-500 dark:text-gray-400",children:["No groups match “",a,"”."]})]})]})},hd=({profile:n,downloadChart:l})=>{var d;const a=n.clustering;return a?i.jsxs("div",{className:"mt-4 space-y-6",id:"clustering-chart",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Lt,{className:"w-5 h-5 mr-2 text-rose-500"}),"Post-Hoc Clustering (Segmentation)",i.jsx(be,{text:"Automatically groups data points into distinct clusters (segments) based on similarity. Useful for finding natural groups like 'High Spenders' or 'At Risk' users."})]}),i.jsx("button",{onClick:()=>l("clustering-chart","clustering-summary","Clustering Summary",`${a.n_clusters} Clusters Found`),className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300",title:"Download Summary","aria-label":"Download Summary",children:i.jsx(Ne,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:i.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:i.jsxs("div",{className:"p-4 bg-purple-50 dark:bg-purple-900/10 rounded-lg border border-purple-100 dark:border-purple-800",children:[i.jsx("h4",{className:"text-sm font-semibold text-purple-900 dark:text-purple-100 mb-2",children:"Algorithm Summary"}),i.jsxs("div",{className:"space-y-1 text-sm text-purple-700 dark:text-purple-300",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{children:"Method:"}),i.jsx("span",{className:"font-medium",children:a.method})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{children:"Metric (Inertia):"}),i.jsx("span",{className:"font-medium",children:((d=a.inertia)==null?void 0:d.toFixed(1))??"N/A"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{children:"Clusters:"}),i.jsx("span",{className:"font-medium",children:a.n_clusters})]})]})]})}),i.jsx("h4",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mt-4",children:"Cluster Profiles (Centroids)"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:a.clusters.map(h=>i.jsxs("div",{className:"p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("span",{className:"font-bold text-gray-900 dark:text-white flex items-center",children:[i.jsx("span",{className:"w-3 h-3 rounded-full mr-2",style:{backgroundColor:ud(h.cluster_id)}}),"Cluster ",h.cluster_id]}),i.jsxs("span",{className:"text-xs px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded-full text-gray-600 dark:text-gray-300",children:[h.percentage.toFixed(1),"% (",h.size,")"]})]}),i.jsxs("div",{className:"space-y-1",children:[Object.entries(h.center).sort(([,u],[,m])=>Math.abs(m??0)-Math.abs(u??0)).slice(0,5).map(([u,m])=>i.jsxs("div",{className:"flex justify-between text-xs",children:[i.jsx("span",{className:"text-gray-500 dark:text-gray-400 truncate w-24",title:u,children:u}),i.jsx("span",{className:"font-mono text-gray-700 dark:text-gray-200",children:(m==null?void 0:m.toFixed(2))??"N/A"})]},u)),Object.keys(h.center).length>5&&i.jsxs("div",{className:"text-xs text-center text-gray-400 italic pt-1",children:["+ ",Object.keys(h.center).length-5," more features"]})]})]},h.cluster_id))})]})})]}),i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-lg text-sm border border-blue-100 dark:border-blue-800",children:[i.jsx(Pt,{className:"w-5 h-5 flex-shrink-0 mt-0.5"}),i.jsx("div",{children:"This summary shows the clustering method, inertia and cluster profiles. Each profile lists up to five centroid feature values, ordered by absolute magnitude."})]})]}):i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm flex flex-col items-center justify-center text-gray-500 min-h-[300px]",children:[i.jsx(Lt,{className:"w-12 h-12 mb-4 opacity-20"}),i.jsx("p",{children:"Clustering analysis not available."}),i.jsx("p",{className:"text-sm mt-2",children:"No clustering results were recorded for this report."})]})},ud=n=>Ue[n%Ue.length];function md({components:n,isPCA3D:l}){return i.jsx(i.Fragment,{children:n&&n.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-gray-100 mb-3",children:"Principal Component Composition"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:n.slice(0,l?3:2).map(a=>i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-3 rounded-md border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex justify-between items-center border-b border-gray-200 dark:border-gray-700 pb-2 mb-2",children:[i.jsx("span",{className:"font-semibold text-gray-800 dark:text-gray-200",children:a.component}),i.jsxs("span",{className:"text-xs bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 px-2 py-0.5 rounded-full",children:[(a.explained_variance_ratio*100).toFixed(1),"% Var"]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-wider mb-1",children:"Top Loadings"}),Object.entries(a.top_features||{}).map(([d,h],u)=>i.jsxs("div",{className:"flex justify-between text-xs items-center group",children:[i.jsx("span",{className:"text-gray-600 dark:text-gray-400 truncate mr-2 flex-1",title:d,children:d}),i.jsxs("span",{className:`font-mono text-[10px] ${Number(h)>0?"text-green-600 dark:text-green-400":"text-red-500 dark:text-red-400"}`,children:[Number(h)>0?"+":"",Number(h).toFixed(3)]})]},u))]})]},a.component))})]})})}const fd=({profile:n,isPCA3D:l,setIsPCA3D:a,downloadChart:d})=>{const h=Array.isArray(n.pca_data)&&n.pca_data.length>0,u=h?"Download Chart":"PCA results unavailable",m=k.useMemo(()=>n.pca_data??[],[n.pca_data]),p=k.useMemo(()=>Mr(si(m,"label")),[m]),g=k.useMemo(()=>{const N=[{key:"x",label:"PC1"},{key:"y",label:"PC2"}];return l&&N.push({key:"z",label:"PC3"}),N.push({key:"label",label:"Group"}),N},[l]);return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Kt,{className:"w-5 h-5 mr-2 text-purple-500"}),"Multivariate Structure (PCA)",i.jsx(be,{text:"Reduces data to 2D or 3D. Points closer together are similar. Colors show clusters or target values."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{disabled:!h,onClick:()=>d("pca-chart","pca-analysis","Multivariate Structure (PCA)",l?"3D Projection":"2D Projection"),className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 disabled:opacity-50",title:u,"aria-label":u,children:i.jsx(Ne,{className:"w-4 h-4"})}),i.jsxs("button",{onClick:()=>a(!l),className:`p-2 rounded-md border transition-colors flex items-center gap-2 text-sm ${l?"bg-blue-50 border-blue-200 text-blue-700 dark:bg-blue-900/20 dark:border-blue-800 dark:text-blue-300":"bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300"}`,children:[i.jsx(wr,{className:"w-4 h-4"}),l?"Switch to 2D":"Switch to 3D"]})]})]}),i.jsx("div",{id:"pca-chart",children:n.pca_data?l?i.jsx(Ar,{data:n.pca_data,xKey:"x",yKey:"y",zKey:"z",labelKey:"label",xLabel:"PC1",yLabel:"PC2",zLabel:"PC3"}):i.jsx(zr,{data:n.pca_data,xKey:"x",yKey:"y",labelKey:"label",xLabel:"Principal Component 1 (PC1)",yLabel:"Principal Component 2 (PC2)"}):i.jsx("div",{className:"h-64 flex items-center justify-center bg-gray-50 dark:bg-gray-900 rounded text-gray-400 text-sm text-center p-4",children:"No PCA projection was recorded for this report."})}),p.length>0&&i.jsx(Ps,{entries:p}),i.jsx(Si,{caption:"PCA projection data",filename:"pca-analysis",columns:g,rows:m}),i.jsxs("div",{className:"mt-6 flex items-start gap-2 bg-blue-50 dark:bg-blue-900/20 p-3 rounded-md border border-blue-100 dark:border-blue-800",children:[i.jsx(Pt,{className:"w-4 h-4 text-blue-500 mt-0.5 shrink-0"}),i.jsxs("div",{className:"text-sm text-blue-700 dark:text-blue-300",children:[i.jsx("p",{className:"font-medium mb-1",children:"About this visualization"}),i.jsxs("p",{children:["This chart shows a ",l?"3D":"2D"," projection of your data using Principal Component Analysis (PCA). Points that are close together share similar characteristics across all numeric features."]}),i.jsxs("p",{className:"mt-1 text-xs opacity-80",children:["* For performance, this visualization uses a random sample of up to ",i.jsx("strong",{children:"5,000 points"}),"."]})]})]}),i.jsx(md,{components:n.pca_components,isPCA3D:l})]}),i.jsx(hd,{profile:n,downloadChart:d})]})};function Ir(n,l){const a=k.useRef(l);k.useEffect(function(){l!==a.current&&n.attributionControl!=null&&(a.current!=null&&n.attributionControl.removeAttribution(a.current),l!=null&&n.attributionControl.addAttribution(l)),a.current=l},[n,l])}function gd(n,l,a){l.center!==a.center&&n.setLatLng(l.center),l.radius!=null&&l.radius!==a.radius&&n.setRadius(l.radius)}const pd=1;function xd(n){return Object.freeze({__version:pd,map:n})}function _d(n,l){return Object.freeze({...n,...l})}const Or=k.createContext(null),Dr=Or.Provider;function Ss(){const n=k.useContext(Or);if(n==null)throw new Error("No context provided: useLeafletContext() can only be used in a descendant of ");return n}function yd(n){function l(a,d){const{instance:h,context:u}=n(a).current;return k.useImperativeHandle(d,()=>h),a.children==null?null:Yt.createElement(Dr,{value:u},a.children)}return k.forwardRef(l)}function vd(n){function l(a,d){const[h,u]=k.useState(!1),{instance:m}=n(a,u).current;k.useImperativeHandle(d,()=>m),k.useEffect(function(){h&&m.update()},[m,h,a.children]);const p=m._contentNode;return p?Xo.createPortal(a.children,p):null}return k.forwardRef(l)}function bd(n){function l(a,d){const{instance:h}=n(a).current;return k.useImperativeHandle(d,()=>h),null}return k.forwardRef(l)}function Ts(n,l){const a=k.useRef();k.useEffect(function(){return l!=null&&n.instance.on(l),a.current=l,function(){a.current!=null&&n.instance.off(a.current),a.current=null}},[n,l])}function Ti(n,l){const a=n.pane??l.pane;return a?{...n,pane:a}:n}function wd(n,l){return function(d,h){const u=Ss(),m=n(Ti(d,u),u);return Ir(u.map,d.attribution),Ts(m.current,d.eventHandlers),l(m.current,u,d,h),m}}var Ut={exports:{}};/* @preserve +import{j as i,u as nr,a as rr,P as Ct,i as ar,B as or,C as lr,M as hs,H as Zn}from"./vendor-flow-bDma3vSM.js";import{al as wt,a as k,aj as dr,am as cr,O as je,c as ti,Q as po,m as Ci,an as xo,ao as ws,ap as _o,aq as yo,H as vo,ar as bo,C as us,u as wo,as as hr,at as ii,e as ur,f as Gt,af as mr,ah as jo,p as fr,a4 as js,w as Li,X as gr,y as ks,au as ko,av as No,aw as Co,a9 as pr,ax as xr,aa as _r,ab as kt,j as ji,ay as Lo,az as Kt,aA as Lt,aB as ms,aC as Po,aD as fs,l as yr,aE as vr,ac as Pt,g as br,_ as Ne,B as wr,b as Yt,ag as Jt,R as So,aF as Ns,S as To,aG as Eo,h as Mo}from"./vendor-utils-_6D5wMFs.js";import{H as Ao,r as jr,s as kr,q as ls,D as zo,u as Io,t as Qt,a as Oo,M as Do,S as Nr,I as Pi,J as ht,K as Ue,O as be,C as Si,b as ct,P as Cr,T as Ro,U as Bo,W as Fo,X as ki,Y as Lr,Z as gs,_ as ps,$ as xs,a0 as Zo,L as $o,E as Ho}from"./index-DYMv5Ibu.js";import{R as Ze,aj as Wo,ak as Vo,j as Cs,T as qe,ah as Pr,al as qo,am as Uo,an as Go,ao as Ko,ap as Yo,aq as Jo,ar as Qo,r as Xo,B as lt,C as Qe,X as Xe,Y as et,as as Sr,h as Ge,at as el,au as ds,ag as tl,ai as $n,av as Tr}from"./vendor-charts-CwfdE1jD.js";import{F as cs}from"./FormField-BxGvOnTr.js";import{r as il,a as sl}from"./vendor-plotly-Bx-86y5L.js";const jt="/api/eda",Ke={analyze:async(n,l,a,d,h)=>(await wt.post(`${jt}/${n}/analyze`,{target_col:l,exclude_cols:a,filters:d,task_type:h})).data,getLatestReport:async n=>(await wt.get(`${jt}/${n}/latest`)).data,getReport:async n=>(await wt.get(`${jt}/reports/${n}`)).data,cancelJob:async n=>(await wt.post(`${jt}/reports/${n}/cancel`)).data,getHistory:async n=>(await wt.get(`${jt}/${n}/history`)).data,getDecomposition:async(n,l,a,d,h)=>(await wt.post(`${jt}/${n}/decomposition`,{measure_col:l,measure_agg:a,split_col:d,filters:h})).data},Hn={x:"",y:"",z:"",color:"",is3D:!1,isPCA3D:!1},Wn=n=>`${n.column}${n.operator}${JSON.stringify(n.value)}`,nl=(n,l)=>n.length!==l.length?!1:n.every((a,d)=>Wn(a)===Wn(l[d])),ie=Ao((n,l)=>({activeTab:"dashboard",selectedDataset:null,targetCol:"",taskType:"",excludedColsDraft:[],excludedColsApplied:[],filtersDraft:[],filtersApplied:[],scatter:{...Hn},setActiveTab:a=>n({activeTab:a}),setSelectedDataset:a=>n({selectedDataset:a}),setTargetCol:a=>n({targetCol:a}),setTaskType:a=>n({taskType:a}),toggleExclude:(a,d)=>n(h=>{const u=h.excludedColsDraft.includes(a);return d?u?h:{excludedColsDraft:[...h.excludedColsDraft,a]}:u?{excludedColsDraft:h.excludedColsDraft.filter(m=>m!==a)}:h}),setExcludedDraft:a=>n({excludedColsDraft:a}),setExcludedApplied:a=>n({excludedColsApplied:a}),applyExcluded:()=>n({excludedColsApplied:[...l().excludedColsDraft]}),addFilterDraft:a=>n(d=>({filtersDraft:[...d.filtersDraft,a]})),removeFilterDraft:a=>n(d=>({filtersDraft:d.filtersDraft.filter((h,u)=>u!==a)})),clearFiltersDraft:()=>n({filtersDraft:[]}),setFiltersDraft:a=>n({filtersDraft:a}),setFiltersApplied:a=>n({filtersApplied:a}),applyFilters:()=>n(a=>({filtersApplied:[...a.filtersDraft]})),setScatter:a=>n(d=>({scatter:{...d.scatter,...a}})),resetForDataset:()=>n({excludedColsDraft:[],excludedColsApplied:[],filtersDraft:[],filtersApplied:[],targetCol:"",activeTab:"dashboard",scatter:{...Hn}})})),rl=n=>{if(n.excludedColsApplied.length!==n.excludedColsDraft.length)return!0;const l=new Set(n.excludedColsApplied);for(const a of n.excludedColsDraft)if(!l.has(a))return!0;return!1},al=n=>!nl(n.filtersDraft,n.filtersApplied),Ie={datasets:["eda","datasets"],report:n=>["eda","report",n],history:n=>["eda","history",n],reportById:n=>["eda","reportById",n]},ol=n=>{const l=jr();return kr({mutationFn:a=>Ke.cancelJob(a),onSuccess:()=>{l.invalidateQueries({queryKey:Ie.history(n)}),l.invalidateQueries({queryKey:Ie.report(n)})}})};function _s(n){if(n==null)return null;const l=n.trim();if(!/^\d+$/.test(l))return null;const a=Number(l);return a>0?a:null}function ll(n,l,a){const d=_s(n);if(d!==null)return d;if(l!==null)return l;const h=a[0];return h===void 0?null:_s(String(h.id))}function dl(n,l,a){return n===null||!a?!1:!l.some(d=>Number(d.id)===n)}function cl(n,l){return l===null?!1:_s(n)===null}function hl(n){return n.name.trim()||`Dataset ${n.id}`}function ul(n){const l=String(n.id);return l.length<=6?l:l.slice(-6)}function ml(n){const l=n.map(d=>hl(d)),a=new Map;for(const d of l)a.set(d,(a.get(d)??0)+1);return n.map((d,h)=>{const u=l[h];return(a.get(u)??0)>1?{value:d.id,label:`${u} (${ul(d)})`}:{value:d.id,label:u}})}function fl(n){const l=ls({queryKey:Ie.datasets,queryFn:()=>zo.getUsable()}),a=k.useMemo(()=>l.data??[],[l.data]),d=k.useMemo(()=>ml(a),[a]),h=ls({queryKey:Ie.report(n??null),queryFn:async()=>{var _;try{return await Ke.getLatestReport(n)}catch(v){if(((_=v==null?void 0:v.response)==null?void 0:_.status)===404)return null;throw v}},enabled:n!=null,refetchInterval:_=>{const v=_.state.data;return v&&v.status==="PENDING"?3e3:!1}}),u=h.data??null,m=h.isLoading,p=h.isError?"Failed to load report":null,N=ls({queryKey:Ie.history(n??null),queryFn:()=>Ke.getHistory(n),enabled:n!=null,refetchInterval:(u==null?void 0:u.status)==="PENDING"?3e3:!1}).data??[];return{datasetsQuery:l,datasets:a,datasetOptions:d,reportQuery:h,report:u,loading:m,error:p,history:N}}function gl(){const[n,l]=Io(),a=jr(),[d,h]=k.useState(!1),[u,m]=k.useState(!1),[p,g]=k.useState(!1),N=k.useRef(!1),_=k.useRef(null),v=ie(I=>I.activeTab),b=ie(I=>I.setActiveTab),j=ie(I=>I.selectedDataset),C=ie(I=>I.setSelectedDataset),w=ie(I=>I.targetCol),S=ie(I=>I.setTargetCol),E=ie(I=>I.taskType),T=ie(I=>I.setTaskType),O=ie(I=>I.excludedColsDraft),le=ie(I=>I.excludedColsApplied),ge=ie(I=>I.filtersDraft),pe=ie(I=>I.filtersApplied),Pe=ie(I=>I.scatter),xe=ie(I=>I.setScatter),K=ie(rl),Q=ie(al),{datasetsQuery:q,datasets:ee,datasetOptions:R,reportQuery:B,report:F,loading:X,error:re,history:A}=fl(j),ae=kr({mutationFn:I=>Ke.analyze(j,w||void 0,I.excluded,I.filters,E||void 0),onSuccess:()=>{a.invalidateQueries({queryKey:Ie.report(j??null)}),a.invalidateQueries({queryKey:Ie.history(j??null)})},onSettled:()=>{N.current=!1,g(!1)}}),z=ae.isPending||p,H=n.get("dataset_id");k.useEffect(()=>{const I=ll(H,j,ee);I!==j&&C(I)},[H,ee,j,C]),k.useEffect(()=>{if(!cl(H,j))return;const I=new URLSearchParams(n);I.set("dataset_id",String(j)),l(I,{replace:!0})},[H,j,n,l]);const se=dl(j,ee,q.isSuccess);k.useEffect(()=>{ie.getState().resetForDataset(),_.current=null},[j]);const ne=k.useMemo(()=>{const I=F==null?void 0:F.profile_data;if(!I)return null;const he=new Set(O),Se={};return I.columns&&Object.entries(I.columns).forEach(([Ce,ut])=>{he.has(Ce)||(Se[Ce]=ut)}),{...I,columns:Se,excluded_columns:O}},[F==null?void 0:F.profile_data,O]),U=(I,he)=>{if(!j)return;const Se=Array.isArray(I)?I:le,Ce=Array.isArray(he)?he:pe;ae.mutate({excluded:Se,filters:Ce})},W=async I=>{if(j){m(!0);try{const he=await a.fetchQuery({queryKey:Ie.reportById(I),queryFn:()=>Ke.getReport(I)});a.setQueryData(Ie.report(j),he)}catch(he){Qt.error("Failed to load report",String(he))}finally{m(!1)}}},$=(I,he,Se)=>{const Ce={column:I,operator:Se||"==",value:he};ie.getState().addFilterDraft(Ce)},ce=I=>{ie.getState().removeFilterDraft(I)},ye=I=>{const he=ie.getState();he.setFiltersDraft([...he.filtersDraft,...I])},Oe=()=>{ie.getState().setFiltersDraft(pe)},St=()=>{if(N.current||z)return;N.current=!0,g(!0);const I=ie.getState().filtersDraft;ie.getState().applyFilters(),U(void 0,I)},Tt=(I,he)=>{ie.getState().toggleExclude(I,he)},tt=()=>{const I=ie.getState().excludedColsDraft;ie.getState().applyExcluded(),U(I)};k.useEffect(()=>{var I;if(F&&F.profile_data){const he=`${j}:${F.id}:${F.status}`;if(_.current===he)return;_.current=he,S(F.profile_data.target_col??"");const Se=Array.isArray(F.profile_data.excluded_columns)?F.profile_data.excluded_columns:[];ie.getState().setExcludedApplied(Se),ie.getState().setExcludedDraft(Se);const Ce=((I=F.config)==null?void 0:I.filters)??[];ie.getState().setFiltersApplied(Ce),ie.getState().setFiltersDraft(Ce)}},[F,j,S]);const Et=w?A.find(I=>I.target_col===w&&I.status==="COMPLETED"):null;return{searchParams:n,setSearchParams:l,queryClient:a,showHistoryModal:d,setShowHistoryModal:h,isLoadingReport:u,activeTab:v,setActiveTab:b,selectedDataset:j,targetCol:w,setTargetCol:S,taskType:E,setTaskType:T,excludedColsDraft:O,filtersDraft:ge,filtersApplied:pe,scatter:Pe,setScatter:xe,excludedDirty:K,filtersDirty:Q,datasetOptions:R,reportQuery:B,report:F,loading:X,error:re,history:A,analyzeMutation:ae,analyzing:z,selectionUnavailable:se,profileForUi:ne,runAnalysis:U,loadSpecificReport:W,handleAddFilter:$,handleAddFilters:ye,handleRemoveFilter:ce,handleResetFilters:Oe,handleApplyFilters:St,handleToggleExclude:Tt,handleApplyExcluded:tt,existingReport:Et}}function pl(n){return i.jsx(i.Fragment,{children:i.jsxs("header",{className:"flex-none bg-white dark:bg-slate-900 border-b border-gray-200 dark:border-gray-800 px-4 py-2 flex flex-wrap items-center justify-between gap-3 z-20 shadow-sm lg:h-16 lg:flex-nowrap lg:py-0 lg:gap-4",children:[i.jsx(xl,{...n}),i.jsx(_l,{...n}),i.jsx(bl,{...n})]})})}function xl(n){const{report:l,selectionUnavailable:a,selectedDataset:d,searchParams:h,setSearchParams:u,datasetOptions:m}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex items-center gap-4 lg:gap-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-lg font-bold text-gray-900 dark:text-white leading-tight",children:"Exploratory Analysis"}),l&&l.created_at&&i.jsxs("p",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:["Last analyzed: ",new Date(l.created_at).toLocaleString()]})]}),i.jsx("div",{className:"h-8 w-px bg-gray-200 dark:bg-gray-700 mx-2"}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("label",{htmlFor:"eda-toolbar-dataset",className:"text-[10px] font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:"Dataset"}),i.jsxs("select",{id:"eda-toolbar-dataset",value:a?"":d||"",onChange:p=>{const g=new URLSearchParams(h);g.set("dataset_id",p.target.value),u(g)},className:"block w-48 text-sm font-medium bg-transparent border-none p-0 focus:ring-0 text-gray-900 dark:text-white cursor-pointer hover:text-blue-600",children:[i.jsx("option",{value:"",disabled:!0,children:"Select a dataset"}),m.map(p=>i.jsx("option",{value:p.value,children:p.label},p.value))]})]})]})})}function _l(n){const{taskType:l,setTaskType:a,report:d}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-wrap items-center gap-3 bg-gray-50 dark:bg-gray-800/50 p-1.5 rounded-lg border border-gray-200 dark:border-gray-700 lg:flex-nowrap lg:gap-4",children:[i.jsx(yl,{...n}),i.jsx("div",{className:"w-px h-8 bg-gray-200 dark:bg-gray-700"}),i.jsxs("div",{className:"flex flex-col px-2",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("label",{htmlFor:"eda-toolbar-task-type",className:"text-[10px] font-medium text-gray-400 uppercase tracking-wider",children:"Task Type"}),i.jsxs("div",{className:"group relative",children:[i.jsx(cr,{className:"w-3 h-3 text-gray-400 cursor-help"}),i.jsx("div",{className:"absolute bottom-full mb-2 w-56 p-2 bg-slate-800 text-white text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-50 pointer-events-none left-1/2 -translate-x-1/2",children:"Force Classification or Regression."})]})]}),i.jsxs("select",{id:"eda-toolbar-task-type",value:l,onChange:h=>a(h.target.value),disabled:!d||!d.profile_data,className:"block w-28 text-sm bg-transparent border-none p-0 focus:ring-0 text-gray-700 dark:text-gray-200 cursor-pointer disabled:opacity-50",children:[i.jsx("option",{value:"",children:"Auto"}),i.jsx("option",{value:"Classification",children:"Classification"}),i.jsx("option",{value:"Regression",children:"Regression"})]})]}),i.jsx(vl,{...n})]})})}function yl(n){const{targetCol:l,setTargetCol:a,report:d,excludedColsDraft:h}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-col px-2",children:[i.jsx("label",{htmlFor:"eda-toolbar-target-column",className:"text-[10px] font-medium text-gray-400 uppercase tracking-wider",children:"Target Column"}),i.jsxs("select",{id:"eda-toolbar-target-column",value:l,onChange:u=>a(u.target.value),disabled:!d||!d.profile_data,className:"block w-36 text-sm bg-transparent border-none p-0 focus:ring-0 text-gray-700 dark:text-gray-200 cursor-pointer disabled:opacity-50",children:[i.jsx("option",{value:"",children:"None"}),d&&d.profile_data&&Object.keys(d.profile_data.columns).filter(u=>!h.includes(u)).map(u=>i.jsx("option",{value:u,children:u},u))]})]})})}function vl(n){const{selectedDataset:l,runAnalysis:a,analyzing:d,existingReport:h}=n;return i.jsx(i.Fragment,{children:i.jsxs("button",{onClick:()=>l&&a(),disabled:!l||d,className:`ml-2 px-3 py-1.5 rounded text-sm font-medium transition-colors flex items-center shadow-sm ${h?"bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-200 border border-gray-300 dark:border-gray-600 hover:bg-gray-50":"action-primary border border-transparent"}`,children:[d?i.jsx(je,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ci,{className:"w-4 h-4 mr-2"}),h?"Re-Run":"Analyze"]})})}function bl(n){const{existingReport:l,report:a,loadSpecificReport:d,isLoadingReport:h,setShowHistoryModal:u}=n;return i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex items-center gap-3",children:[l&&a&&a.id!==l.id&&i.jsxs("button",{onClick:()=>d(l.id),disabled:h,className:"flex items-center px-3 py-1.5 text-xs bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-400 border border-green-200 dark:border-green-800 rounded-md hover:bg-green-100 dark:hover:bg-green-900/40 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:`Load existing from ${new Date(l.created_at).toLocaleString()}`,children:[h?i.jsx(je,{className:"w-3 h-3 mr-1 animate-spin"}):i.jsx(ti,{className:"w-3 h-3 mr-1"}),"Load Saved"]}),i.jsxs("button",{onClick:()=>u(!0),className:"flex items-center px-3 py-1.5 text-sm font-medium text-gray-600 bg-gray-50 dark:bg-gray-800 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:[i.jsx(po,{className:"w-4 h-4 mr-2"}),"History"]})]})})}function wl(n){const{history:l,report:a,loadSpecificReport:d,isLoadingReport:h}=n;return i.jsx(i.Fragment,{children:l.length>0&&i.jsxs("div",{className:"flex-none bg-white dark:bg-slate-950 border-b border-gray-100 dark:border-gray-800 px-4 py-1.5 flex items-center gap-3 overflow-x-auto z-10 shadow-[0_2px_3px_-1px_rgba(0,0,0,0.02)]",children:[i.jsx("span",{className:"text-[10px] uppercase font-bold text-gray-400 tracking-wider whitespace-nowrap",children:"Recent Targets:"}),i.jsx("div",{className:"flex gap-2",children:Array.from(new Set(l.filter(u=>u.target_col&&u.status==="COMPLETED").map(u=>u.target_col))).slice(0,8).map(u=>{var m;return i.jsxs("button",{onClick:()=>{const p=l.find(g=>g.target_col===u&&g.status==="COMPLETED");p&&d(p.id)},disabled:h,className:`px-2 py-0.5 text-xs rounded-full border transition-colors flex items-center disabled:opacity-50 disabled:cursor-not-allowed ${((m=a==null?void 0:a.profile_data)==null?void 0:m.target_col)===u?"bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800 font-medium":"bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400 border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-200"}`,children:[i.jsx(dr,{className:"w-3 h-3 mr-1"}),u]},u)})})]})})}const jl={Numeric:{badgeClass:"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",iconColorClass:"text-blue-500",Icon:vo},Categorical:{badgeClass:"bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300",iconColorClass:"text-purple-500",Icon:yo},Boolean:{badgeClass:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300",iconColorClass:"text-amber-500",Icon:_o},DateTime:{badgeClass:"bg-teal-100 text-teal-800 dark:bg-teal-900/30 dark:text-teal-300",iconColorClass:"text-teal-500",Icon:ws},Text:{badgeClass:"bg-slate-100 text-slate-800 dark:bg-slate-800 dark:text-slate-300",iconColorClass:"text-slate-500",Icon:xo}},kl={badgeClass:"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300",iconColorClass:"text-gray-500",Icon:bo};function Ls(n){return jl[n]??kl}function Nl(n){return Ls(n).badgeClass}function Cl(n){return Ls(n).iconColorClass}function Ll(n){return Ls(n).Icon}const Pl=({isOpen:n,onClose:l,history:a,datasetId:d,onSelect:h,onFetchReport:u,onRefresh:m})=>{const[p,g]=k.useState(null),[N,_]=k.useState(!1),v=k.useRef(0),b=ol(d),j=b.isPending?b.variables??null:null,C=Oo(),w=()=>{g(null),l()},S=async(T,O)=>{if(T.stopPropagation(),!!await C({title:"Cancel analysis?",message:"Are you sure you want to cancel this analysis?",confirmLabel:"Cancel job",variant:"danger"}))try{await b.mutateAsync(O),m&&m()}catch(ge){console.error("Failed to cancel job",ge),Qt.error("Failed to cancel job")}},E=async T=>{const O=++v.current;_(!0);try{const le=await u(T.id);if(O!==v.current)return;g(le)}catch(le){console.error("Failed to load report details",le),O===v.current&&Qt.error("Failed to load job details","Please try again.")}finally{O===v.current&&_(!1)}};return i.jsx(Do,{isOpen:n,onClose:w,size:p?"5xl":"2xl",title:i.jsxs("div",{className:"flex items-center gap-3",children:[p?i.jsx("button",{onClick:()=>g(null),className:"p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-colors","aria-label":"Back to history",children:i.jsx(wo,{className:"w-5 h-5 text-gray-500 dark:text-gray-400"})}):i.jsx(us,{className:"w-5 h-5 text-blue-500"}),i.jsx("span",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:p?`Analysis #${p.id} Details`:"Analysis History"})]}),footer:p?i.jsx("div",{className:"flex justify-end",children:i.jsxs("button",{onClick:()=>{h(p),w()},className:"flex items-center px-4 py-2 action-primary rounded-md transition-colors shadow-sm",children:[i.jsx(Ci,{className:"w-4 h-4 mr-2"}),"Load this Report"]})}):i.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 text-center w-full",children:"Select a previous analysis to view details."}),children:i.jsx("div",{className:"p-6",children:p?N?i.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500",children:[i.jsx(je,{className:"w-12 h-12 mb-4 animate-spin text-blue-500"}),i.jsx("p",{children:"Loading analysis details..."})]}):i.jsx(El,{selectedJob:p}):a.length===0?i.jsxs("div",{className:"text-center py-12 text-gray-500 dark:text-gray-400",children:[i.jsx(us,{className:"w-12 h-12 mx-auto mb-3 opacity-20"}),i.jsx("p",{children:"No history available for this dataset."})]}):i.jsx("div",{className:"space-y-3",children:a.map(T=>i.jsx(Sl,{job:T,handleJobClick:E,cancelling:j,handleCancel:S},T.id))})})})};function Sl({job:n,handleJobClick:l,cancelling:a,handleCancel:d}){return i.jsxs("div",{...Pi(()=>l(n)),className:"flex items-center justify-between p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-blue-500 dark:hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 cursor-pointer transition-all group",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Tl,{status:n.status}),i.jsxs("div",{children:[i.jsxs("div",{className:"font-medium text-gray-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 flex items-center gap-2",children:["Analysis #",n.id,i.jsx(Nr,{status:n.status??"unknown"})]}),i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:n.created_at?new Date(n.created_at).toLocaleString():"—"}),n.target_col&&i.jsxs("div",{className:"text-xs text-gray-400 mt-1 flex items-center gap-1",children:[i.jsx(Ci,{className:"w-3 h-3"})," Target: ",n.target_col,n.task_type&&i.jsx("span",{className:"ml-1 px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-[10px]",children:n.task_type})]})]})]}),i.jsx("div",{className:"text-right flex items-center gap-4",children:(n.status==="PENDING"||n.status==="STARTED"||n.status==="RUNNING")&&i.jsx("button",{onClick:h=>d(h,n.id),disabled:a===n.id,className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-full transition-colors",title:"Cancel Analysis",children:a===n.id?i.jsx(je,{className:"w-4 h-4 animate-spin"}):i.jsx(hr,{className:"w-4 h-4"})})})]})}function Tl({status:n}){return i.jsx("div",{className:`p-2 rounded-full ${n==="COMPLETED"?"bg-green-100 text-green-600 dark:bg-green-900/30 dark:text-green-400":n==="FAILED"?"bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400":n==="CANCELLED"?"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400":"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/30 dark:text-yellow-400"}`,children:n==="COMPLETED"?i.jsx(ur,{className:"w-5 h-5"}):n==="FAILED"?i.jsx(Gt,{className:"w-5 h-5"}):n==="CANCELLED"?i.jsx(hr,{className:"w-5 h-5"}):i.jsx(je,{className:"w-5 h-5 animate-spin"})})}function El({selectedJob:n}){var l,a;return i.jsxs("div",{className:"space-y-8",children:[i.jsx(Ml,{selectedJob:n}),((l=n.profile_data)==null?void 0:l.excluded_columns)&&n.profile_data.excluded_columns.length>0&&i.jsxs("div",{children:[i.jsxs("h3",{className:"text-sm font-medium text-gray-900 dark:text-white mb-3 flex items-center gap-2",children:[i.jsx(ii,{className:"w-4 h-4 text-gray-500"}),"Excluded Columns (",n.profile_data.excluded_columns.length,")"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:n.profile_data.excluded_columns.map(d=>i.jsx("span",{className:"px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded text-sm line-through",children:d},d))})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-gray-900 dark:text-white mb-3",children:"Variables Overview"}),i.jsx("div",{className:"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden",children:i.jsxs("table",{className:"w-full text-sm text-left",children:[i.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900/50 text-gray-500 dark:text-gray-400",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-4 py-3 font-medium",children:"Name"}),i.jsx("th",{className:"px-4 py-3 font-medium",children:"Type"}),i.jsx("th",{className:"px-4 py-3 font-medium",children:"Missing"}),i.jsx("th",{className:"px-4 py-3 font-medium",children:"Distinct"})]})}),i.jsx("tbody",{className:"divide-y divide-gray-200 dark:divide-gray-700",children:((a=n.profile_data)==null?void 0:a.columns)&&Object.values(n.profile_data.columns).map(d=>{var u;const h=Ll(d.dtype);return i.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[i.jsx("td",{className:"px-4 py-3 font-medium text-gray-900 dark:text-white",children:d.name}),i.jsx("td",{className:"px-4 py-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(h,{className:`w-4 h-4 ${Cl(d.dtype)}`}),i.jsx("span",{children:d.dtype})]})}),i.jsx("td",{className:"px-4 py-3",children:d.missing_percentage>0?i.jsxs("span",{className:"text-amber-600",children:[d.missing_percentage.toFixed(1),"%"]}):i.jsx("span",{className:"text-green-600",children:"0%"})}),i.jsx("td",{className:"px-4 py-3 text-gray-500 dark:text-gray-400",children:((u=d.categorical_stats)==null?void 0:u.unique_count)||"-"})]},d.name)})})]})})]})]})}function Ml({selectedJob:n}){var l,a,d,h,u,m;return i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1",children:[i.jsx(mr,{className:"w-4 h-4"}),i.jsx("span",{className:"text-xs uppercase font-medium",children:"Rows"})]}),i.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:((a=(l=n.profile_data)==null?void 0:l.row_count)==null?void 0:a.toLocaleString())||"-"})]}),i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1",children:[i.jsx(jo,{className:"w-4 h-4"}),i.jsx("span",{className:"text-xs uppercase font-medium",children:"Columns"})]}),i.jsx("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:((h=(d=n.profile_data)==null?void 0:d.column_count)==null?void 0:h.toLocaleString())||"-"})]}),i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400 mb-1",children:[i.jsx(fr,{className:"w-4 h-4"}),i.jsx("span",{className:"text-xs uppercase font-medium",children:"Missing Cells"})]}),i.jsxs("div",{className:"text-2xl font-bold text-gray-900 dark:text-white",children:[(m=(u=n.profile_data)==null?void 0:u.missing_cells_percentage)==null?void 0:m.toFixed(1),"%"]})]})]})}function Al(n){const{selectionUnavailable:l,selectedDataset:a,analyzeMutation:d,analyzing:h,runAnalysis:u}=n;return i.jsxs(i.Fragment,{children:[l&&i.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-b border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-200",children:[i.jsx(Gt,{className:"h-4 w-4 shrink-0"}),i.jsxs("span",{className:"flex-1 min-w-[12rem]",children:["Dataset #",a," isn't available for analysis — it may still be processing or have no usable columns. Pick another dataset above to continue."]})]}),d.isError&&i.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-b border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900 dark:bg-red-950/40 dark:text-red-200",children:[i.jsx(Gt,{className:"h-4 w-4 shrink-0"}),i.jsxs("span",{className:"flex-1 min-w-[12rem]",children:["Could not start the analysis: ",d.error instanceof Error?d.error.message:"the request was rejected."," ","Your dataset, target, and filter choices were kept."]}),i.jsxs("button",{onClick:()=>{const m=d.variables;u(m==null?void 0:m.excluded,m==null?void 0:m.filters)},disabled:h,className:"flex items-center rounded-md border border-red-300 px-3 py-1.5 font-medium hover:bg-red-100 disabled:opacity-50 dark:border-red-800 dark:hover:bg-red-900/40",children:[i.jsx(ti,{className:"mr-2 h-4 w-4"}),"Try again"]}),i.jsx("button",{onClick:()=>d.reset(),className:"rounded-md px-2 py-1.5 font-medium underline hover:no-underline",children:"Dismiss"})]})]})}function zl(n){const{showHistoryModal:l,setShowHistoryModal:a,history:d,selectedDataset:h,queryClient:u}=n;return i.jsx(i.Fragment,{children:i.jsx(Pl,{isOpen:l,onClose:()=>a(!1),history:d,datasetId:h??null,onRefresh:()=>u.invalidateQueries({queryKey:Ie.history(h??null)}),onFetchReport:async m=>{const p=await Ke.getReport(m);return{...p,id:p.id??m}},onSelect:m=>{var g;h&&u.setQueryData(Ie.report(h),m);const p=Array.isArray((g=m.profile_data)==null?void 0:g.excluded_columns)?m.profile_data.excluded_columns:[];ie.getState().setExcludedApplied(p),ie.getState().setExcludedDraft(p)}})})}function Il(n,l,a,d){return l?a&&!d?`${n===">"?"Greater than":n==="<"?"Less than":n===">="?"Greater than or equal to":"Less than or equal to"} needs a numeric value`:"":"Enter a filter value"}function Ol(n,l,a){const d=[">","<",">=","<="].includes(l),h=n.trim().length>0,u=l.trim().length>0,m=a.trim().length>0,p=Number.isFinite(Number(a)),g=Il(l,m,d,p);return{hasFilterColumn:h,hasFilterOperator:u,hasFilterValue:m,isComparisonOperator:d,currentFilterValueError:g}}function Dl(n){const[l,a]=k.useState(!1),[d,h]=k.useState(""),[u,m]=k.useState("=="),[p,g]=k.useState(""),[N,_]=k.useState(!1),{hasFilterColumn:v,hasFilterOperator:b,hasFilterValue:j,isComparisonOperator:C,currentFilterValueError:w}=Ol(d,u,p);return{isAddingFilter:l,setIsAddingFilter:a,newFilterCol:d,setNewFilterCol:h,newFilterOp:u,setNewFilterOp:m,newFilterVal:p,setNewFilterVal:g,filterValidationAttempted:N,setFilterValidationAttempted:_,columnError:N&&!v?"Choose a filter column":"",operatorError:N&&!b?"Choose a filter operator":"",valueError:N&&w?w:"",handleAddFilterSubmit:()=>{_(!0),!(!v||!b||!j||w)&&(n(d,C?Number(p):Number.isNaN(Number(p))?p:Number(p),u),a(!1),_(!1),h(""),m("=="),g(""))}}}const Vn=n=>`${n.column}${n.operator}${JSON.stringify(n.value)}`,Rl=(n,l)=>n.length!==l.length?!1:n.every((a,d)=>Vn(a)===Vn(l[d]));function Bl({filtersDraft:n,filtersApplied:l,filtersDirty:a,columns:d,analyzing:h,onRemoveFilter:u,onResetFilters:m,onApplyFilters:p,showFilters:g,setShowFilters:N,form:_}){const v=a||!Rl(n,l);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between w-full mb-2",children:[i.jsxs("button",{onClick:()=>N(!g),className:"flex items-center text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider hover:text-gray-700 dark:hover:text-gray-300",children:[i.jsxs("span",{children:["Draft Filters (",n.length,")"]}),g?i.jsx(js,{className:"w-3 h-3 ml-1"}):i.jsx(Li,{className:"w-3 h-3 ml-1"})]}),a&&i.jsx("span",{className:"text-[10px] font-medium rounded-full bg-amber-100 text-amber-800 px-2 py-0.5",children:"Pending"})]}),g&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-[10px] text-gray-500 dark:text-gray-400",children:["Report uses ",l.length," applied filter",l.length===1?"":"s"," until you apply draft changes."]}),i.jsx(Fl,{filtersDraft:n,filtersDirty:a,analyzing:h,onRemoveFilter:u}),i.jsx(Zl,{form:_,columns:d}),i.jsx($l,{disabled:!v||h,onResetFilters:m,onApplyFilters:p})]})]})}function Fl({filtersDraft:n,filtersDirty:l,analyzing:a,onRemoveFilter:d}){return i.jsx(i.Fragment,{children:n.length>0?n.map((h,u)=>i.jsxs("div",{className:`flex items-center justify-between rounded px-2 py-1 text-xs border ${l?"bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-800":"bg-gray-50 dark:bg-gray-900/50 border-gray-200 dark:border-gray-700"}`,children:[i.jsxs("div",{className:"truncate max-w-[140px]",children:[i.jsx("span",{className:"font-medium text-blue-700 dark:text-blue-300",children:h.column}),i.jsx("span",{className:"mx-1 text-gray-500 dark:text-gray-400",children:h.operator}),i.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:String(h.value)})]}),i.jsx("button",{onClick:()=>d(u),className:"text-gray-500 dark:text-gray-400 hover:text-red-500","aria-label":`Remove filter ${u+1}`,disabled:a,children:i.jsx(gr,{className:"w-3 h-3"})})]},u)):i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"No draft filters yet."})})}function Zl({form:n,columns:l}){const{isAddingFilter:a,setIsAddingFilter:d,newFilterCol:h,setNewFilterCol:u,newFilterOp:m,setNewFilterOp:p,newFilterVal:g,setNewFilterVal:N,filterValidationAttempted:_,setFilterValidationAttempted:v,columnError:b,operatorError:j,valueError:C,handleAddFilterSubmit:w}=n;return i.jsx(i.Fragment,{children:a?i.jsxs("div",{className:"bg-white dark:bg-gray-900 p-2 rounded border border-gray-200 dark:border-gray-700 space-y-2 shadow-sm",children:[i.jsx(cs,{label:"Filter column",hideLabel:!0,required:!0,..._?{error:b}:{},children:S=>i.jsxs("select",{...S,value:h,onChange:E=>u(E.target.value),className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",children:[i.jsx("option",{value:"",disabled:!0,children:"Column"}),l.map(E=>i.jsx("option",{value:E,children:E},E))]})}),i.jsxs("div",{className:"flex gap-1",children:[i.jsx(cs,{label:"Filter operator",hideLabel:!0,required:!0,className:"w-1/3",..._?{error:j}:{},children:S=>i.jsxs("select",{...S,value:m,onChange:E=>p(E.target.value),className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",children:[i.jsx("option",{value:"==",children:"=="}),i.jsx("option",{value:"!=",children:"!="}),i.jsx("option",{value:">",children:">"}),i.jsx("option",{value:"<",children:"<"}),i.jsx("option",{value:">=",children:">="}),i.jsx("option",{value:"<=",children:"<="})]})}),i.jsx(cs,{label:"Filter value",hideLabel:!0,required:!0,className:"w-2/3",..._?{error:C}:{},children:S=>i.jsx("input",{...S,type:"text",value:g,onChange:E=>N(E.target.value),placeholder:"Value",className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",onKeyDown:E=>E.key==="Enter"&&w()})})]}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx("button",{onClick:()=>{d(!1),v(!1),u(""),p("=="),N("")},className:"text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300",children:"Cancel"}),i.jsx("button",{onClick:w,className:"text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700",children:"Save draft"})]})]}):i.jsxs("button",{onClick:()=>d(!0),className:"w-full flex items-center justify-center px-2 py-1 text-xs border border-dashed border-gray-300 dark:border-gray-600 rounded text-gray-500 dark:text-gray-400 hover:text-blue-600 hover:border-blue-300 transition-colors",children:[i.jsx(ks,{className:"w-3 h-3 mr-1"})," Add Filter"]})})}function $l({disabled:n,onResetFilters:l,onApplyFilters:a}){return i.jsxs("div",{className:"flex gap-2 pt-1",children:[i.jsx("button",{onClick:l,disabled:n,className:`flex-1 text-xs px-2 py-1 rounded border transition-colors ${n?"bg-gray-100 dark:bg-gray-800 text-gray-400 border-gray-200 dark:border-gray-700 cursor-not-allowed":"bg-white dark:bg-gray-900 text-gray-600 border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-800"}`,children:"Reset filters"}),i.jsx("button",{onClick:a,disabled:n,className:`flex-1 text-xs px-2 py-1 rounded border transition-colors ${n?"bg-gray-100 dark:bg-gray-800 text-gray-400 border-gray-200 dark:border-gray-700 cursor-not-allowed":"bg-blue-600 text-white border-blue-700 hover:bg-blue-700"}`,children:"Apply filters"})]})}function Hl({columns:n,excludedCols:l,excludedDirty:a,analyzing:d,onToggleExclude:h,onApplyExcluded:u,showExclusions:m,setShowExclusions:p,isAddingExclusion:g,setIsAddingExclusion:N}){return i.jsxs("div",{children:[i.jsxs("button",{onClick:()=>p(!m),className:"flex items-center justify-between w-full text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2 hover:text-gray-700 dark:hover:text-gray-300",children:[i.jsxs("span",{children:["Excluded (",l.length,")"]}),m?i.jsx(js,{className:"w-3 h-3"}):i.jsx(Li,{className:"w-3 h-3"})]}),m&&i.jsxs("div",{className:"space-y-2",children:[l.map((_,v)=>i.jsxs("div",{className:"flex items-center justify-between bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded px-2 py-1 text-xs",children:[i.jsx("span",{className:"font-medium text-gray-500 dark:text-gray-400 line-through truncate max-w-[140px]",children:_}),i.jsx("button",{onClick:()=>h(_,!1),className:"text-gray-500 dark:text-gray-400 hover:text-green-500",title:"Include back",children:i.jsx(ks,{className:"w-3 h-3"})})]},v)),i.jsx(Wl,{onApplyExcluded:u,excludedDirty:a,analyzing:d}),g?i.jsxs("div",{className:"bg-white dark:bg-gray-900 p-2 rounded border border-gray-200 dark:border-gray-700 space-y-2 shadow-sm",children:[i.jsxs("select",{"aria-label":"Column to exclude from analysis",className:"w-full text-xs rounded border-gray-300 dark:border-gray-600 dark:bg-gray-800 p-1",onChange:_=>{_.target.value&&(h(_.target.value,!0),N(!1))},defaultValue:"",children:[i.jsx("option",{value:"",disabled:!0,children:"Select Column"}),n.filter(_=>!l.includes(_)).map(_=>i.jsx("option",{value:_,children:_},_))]}),i.jsx("button",{onClick:()=>N(!1),className:"w-full text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 text-center",children:"Cancel"})]}):i.jsxs("button",{onClick:()=>N(!0),className:"w-full flex items-center justify-center px-2 py-1 text-xs border border-dashed border-gray-300 dark:border-gray-600 rounded text-gray-500 dark:text-gray-400 hover:text-red-600 hover:border-red-300 transition-colors",children:[i.jsx(ii,{className:"w-3 h-3 mr-1"})," Exclude Column"]})]})]})}function Wl({onApplyExcluded:n,excludedDirty:l,analyzing:a}){return i.jsx("button",{onClick:n,disabled:!l||a,className:`w-full flex items-center justify-center px-2 py-1 text-xs rounded border transition-colors ${l&&!a?"bg-blue-600 text-white border-blue-700 hover:bg-blue-700":"bg-gray-100 dark:bg-gray-800 text-gray-400 border-gray-200 dark:border-gray-700 cursor-not-allowed"}`,title:l?"Apply excluded columns to re-run analysis":"No pending exclusion changes",children:"Apply changes"})}function Vl(n){return[{title:"Overview",items:[{id:"dashboard",label:"Dashboard",icon:Co,show:!0},{id:"pii",label:"PII Review",icon:pr,show:!0},{id:"sample",label:"Sample Data",icon:xr,show:!!n.sample_data},{id:"insights",label:"Smart Insights",icon:_r,show:!0}]},{title:"Univariate Analysis",items:[{id:"variables",label:"Variables",icon:kt,show:!0},{id:"outliers",label:"Outliers",icon:ji,show:!!n.outliers},{id:"target",label:"Target Analysis",icon:dr,show:!!(n.target_col&&n.target_correlations)}]},{title:"Multivariate Analysis",items:[{id:"correlations",label:"Correlations",icon:Lo,show:!!(n.correlations||n.correlations_with_target||n.causal_target_exclusion_reason)},{id:"bivariate",label:"Bivariate",icon:Kt,show:!0},{id:"pca",label:"PCA & Clusters",icon:Lt,show:!!n.pca_data||!!n.clustering}]},{title:"Structure & Causal",items:[{id:"causal",label:"Causal Graph",icon:Lt,show:!!(n.causal_graph||n.causal_target_exclusion_reason)},{id:"rules",label:"Decision Tree",icon:ms,show:!!n.rule_tree},{id:"decomposition",label:"Decomposition",icon:Po,show:!0}]},{title:"Specialized",items:[{id:"timeseries",label:"Time Series",icon:ws,show:!!n.timeseries},{id:"geospatial",label:"Geospatial",icon:fs,show:!!n.geospatial}]}]}function ql({activeTab:n,setActiveTab:l,profile:a,isCollapsed:d,setIsCollapsed:h}){const u=Vl(a);return i.jsxs("div",{className:`flex-1 overflow-y-auto ${d?"p-2":"p-3"}`,children:[i.jsxs("div",{className:`flex items-center ${d?"justify-center":"justify-between"} mb-3`,children:[!d&&i.jsx("h2",{className:"text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider",children:"Analysis Modules"}),i.jsx("button",{onClick:()=>h(!d),className:"p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded text-gray-500 dark:text-gray-400",title:d?"Expand Sidebar":"Collapse Sidebar",children:d?i.jsx(ko,{className:"w-4 h-4"}):i.jsx(No,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"space-y-6",children:u.map((m,p)=>{const g=m.items.filter(N=>N.show);return g.length===0?null:i.jsxs("div",{children:[!d&&i.jsx("h3",{className:"px-2 text-xs font-medium text-gray-500 dark:text-gray-400 mb-2",children:m.title}),i.jsx("div",{className:"space-y-1",children:g.map(N=>i.jsx(Ul,{item:N,activeTab:n,setActiveTab:l,isCollapsed:d},N.id))})]},p)})})]})}function Ul({item:n,activeTab:l,setActiveTab:a,isCollapsed:d}){const h=l===n.id?{button:"bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-400",icon:"text-blue-500",current:"page"}:{button:"text-gray-600 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700",icon:"text-gray-400",current:void 0};return i.jsxs("button",{onClick:()=>a(n.id),"aria-label":n.label,"aria-current":h.current,title:d?n.label:void 0,className:`w-full flex items-center ${d?"justify-center py-2":"px-2 py-2"} text-sm font-medium rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-gray-800 ${h.button}`,children:[i.jsx(n.icon,{className:`${d?"h-5 w-5":"mr-3 h-4 w-4"} ${h.icon}`}),!d&&i.jsxs(i.Fragment,{children:[n.label,l===n.id&&i.jsx(yr,{className:"ml-auto h-4 w-4 text-blue-400"})]})]})}const Gl=n=>{const[l,a]=k.useState(!0),[d,h]=k.useState(!1),[u,m]=k.useState(!1),p=Dl(n.onAddFilter),[g,N]=k.useState(!1);return i.jsxs("div",{className:`${u?"w-14":"w-60"} bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex-shrink-0 h-full overflow-y-auto flex flex-col transition-all duration-300`,children:[!u&&n.activeTab!=="pii"&&i.jsxs("div",{className:"p-3 border-b border-gray-200 dark:border-gray-700 space-y-3 bg-gray-50/50 dark:bg-gray-900/20",children:[i.jsx(Bl,{...n,showFilters:l,setShowFilters:a,form:p}),i.jsx(Hl,{...n,showExclusions:d,setShowExclusions:h,isAddingExclusion:g,setIsAddingExclusion:N})]}),i.jsx(ql,{activeTab:n.activeTab,setActiveTab:n.setActiveTab,profile:n.profile,isCollapsed:u,setIsCollapsed:m})]})},Kl=({profile:n})=>{if(!n)return null;const l=n.missing_cells_percentage??0,a=n.duplicate_rows??0;return i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Rows"}),i.jsx("div",{className:"text-2xl font-bold",children:(n.row_count??0).toLocaleString()})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Columns"}),i.jsx("div",{className:"text-2xl font-bold",children:n.column_count})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Missing Cells"}),i.jsxs("div",{className:"text-2xl font-bold",children:[l.toFixed(1),"%"]})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Duplicates"}),i.jsx("div",{className:"text-2xl font-bold",children:a})]}),n.vif&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"High VIF Features"}),i.jsx("div",{className:"text-2xl font-bold text-amber-600",children:Object.values(n.vif).filter(d=>d>5).length})]})]})},Yl=({alerts:n})=>{const[l,a]=k.useState(!0);return!n||n.length===0?null:i.jsxs("div",{className:"bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex justify-between items-center cursor-pointer",...Pi(()=>a(!l)),children:[i.jsxs("h3",{className:"font-medium text-amber-800 dark:text-amber-200 flex items-center",children:[i.jsx(Gt,{className:"w-4 h-4 mr-2"}),"Data Quality Alerts (",n.length,")"]}),l?i.jsx(js,{className:"w-4 h-4 text-amber-800 dark:text-amber-200"}):i.jsx(Li,{className:"w-4 h-4 text-amber-800 dark:text-amber-200"})]}),l&&i.jsx("div",{className:"max-h-40 overflow-y-auto pr-2 mt-2 animate-in slide-in-from-top-2 duration-200",children:i.jsx("ul",{className:"space-y-1",children:n.map((d,h)=>i.jsxs("li",{className:"text-sm text-amber-700 dark:text-amber-300 flex items-start",children:[i.jsx("span",{className:"mr-2",children:"•"}),i.jsxs("span",{children:[d.column&&i.jsxs("span",{className:"font-semibold",children:[d.column,": "]}),d.message]})]},h))})})]})},Jl=({profile:n,onToggleExclude:l,excludedCols:a=[]})=>{const d=ht(),h=k.useMemo(()=>{if(!(n!=null&&n.columns))return[];const m={};return Object.values(n.columns).forEach(p=>{m[String(p.dtype)]=(m[String(p.dtype)]||0)+1}),Object.entries(m).map(([p,g])=>({name:p,value:g}))},[n]),u=k.useMemo(()=>n!=null&&n.columns?Object.values(n.columns).filter(m=>m.missing_percentage>0).sort((m,p)=>p.missing_percentage-m.missing_percentage).slice(0,20).map(m=>({name:m.name,value:m.missing_percentage})):[],[n]);return i.jsxs("div",{className:"space-y-6",children:[i.jsx(Kl,{profile:n}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(mr,{className:"w-5 h-5 mr-2 text-blue-500"}),"Column Types"]}),i.jsx("div",{className:"h-64",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(Wo,{children:[i.jsx(Vo,{data:h,cx:"50%",cy:"50%",innerRadius:60,outerRadius:80,fill:"#8884d8",paddingAngle:5,dataKey:"value",children:h.map((m,p)=>i.jsx(Cs,{fill:Ue[p%Ue.length]},`cell-${p}`))}),i.jsx(qe,{contentStyle:d.tooltipContentStyle,itemStyle:d.tooltipItemStyle,labelStyle:d.tooltipLabelStyle}),i.jsx(Pr,{verticalAlign:"bottom",height:36})]})})})]}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(ji,{className:"w-5 h-5 mr-2 text-amber-500"}),"Top Missing Values"]}),u.length>0?i.jsx("div",{className:"h-64 overflow-y-auto pr-2 space-y-3",children:u.map((m,p)=>{const g=a.includes(m.name);return i.jsxs("div",{className:"flex items-center gap-3 text-sm group",children:[i.jsx("div",{className:"w-32 truncate text-gray-600 dark:text-gray-300 font-medium",title:m.name,children:m.name}),i.jsx("div",{className:"flex-1 h-2 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${m.value}%`,backgroundColor:`hsl(10, 80%, ${60-p*2}%)`}})}),i.jsxs("div",{className:"w-12 text-right text-gray-500 text-xs",children:[m.value.toFixed(1),"%"]}),l&&i.jsx("button",{onClick:()=>l(m.name,!g),className:`p-1.5 rounded-md transition-colors opacity-100 md:opacity-0 md:group-hover:opacity-100 focus:opacity-100 ${g?"bg-red-100 text-red-600 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 opacity-100":"text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700 dark:hover:text-gray-300"}`,title:g?"Include Column":"Exclude Column","aria-label":g?"Include Column":"Exclude Column",children:g?i.jsx(ii,{className:"w-4 h-4"}):i.jsx(vr,{className:"w-4 h-4"})})]},p)})}):i.jsxs("div",{className:"h-64 flex flex-col items-center justify-center text-gray-400",children:[i.jsx(fr,{className:"w-12 h-12 mb-2 opacity-20"}),i.jsx("p",{children:"No missing values found!"})]})]})]}),i.jsx(Yl,{alerts:n.alerts??[]})]})},Ql=({profile:n})=>{const l=Array.isArray(n.recommendations)?n.recommendations:[];return i.jsx("div",{className:"mt-4 space-y-6",children:i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(_r,{className:"w-5 h-5 mr-2 text-yellow-500"}),"Smart Recommendations"]}),l.length>0?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:l.map((a,d)=>i.jsxs("div",{className:"p-4 bg-blue-50 dark:bg-blue-900/10 rounded-lg border border-blue-100 dark:border-blue-800",children:[i.jsxs("div",{className:"flex justify-between items-start mb-2",children:[i.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400 bg-white dark:bg-gray-800 px-2 py-1 rounded border border-blue-100 dark:border-blue-800",children:a.action}),a.column&&i.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 font-mono",children:a.column})]}),i.jsx("h4",{className:"font-medium text-gray-900 dark:text-white text-sm mb-1",children:a.reason}),i.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:a.suggestion})]},d))}):i.jsx("p",{className:"text-gray-500 dark:text-gray-400 italic",children:"No recommendations were recorded for this report."})]})})};function Xl({alerts:n=[]}){const l=n.filter(d=>d.type==="PII"),a=new Set(l.map(d=>d.column).filter(Boolean)).size;return i.jsxs("section",{id:"eda-pii-review","aria-labelledby":"eda-pii-heading",className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("h2",{id:"eda-pii-heading",className:"flex items-center gap-2 text-xl font-semibold text-gray-900 dark:text-white",children:[i.jsx(pr,{"aria-hidden":"true",className:"h-5 w-5 text-blue-600 dark:text-blue-400"}),"PII review"]}),i.jsx("p",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"Review columns that may contain personally identifiable information (PII). Values and samples are not shown here."})]}),i.jsxs("div",{className:"flex gap-3 rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-800 dark:bg-blue-900/20",children:[i.jsx(Pt,{"aria-hidden":"true",className:"mt-0.5 h-5 w-5 shrink-0 text-blue-700 dark:text-blue-300"}),i.jsxs("div",{className:"space-y-1 text-sm text-blue-900 dark:text-blue-100",children:[i.jsx("p",{className:"font-semibold",children:"Advisory heuristics only"}),i.jsx("p",{children:"Matches can be false positives, and detection can miss personal information. Findings do not classify data as legally sensitive or determine compliance. This review does not mask, delete, or block data."})]})]}),l.length===0?i.jsxs("div",{className:"rounded-lg border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800",children:[i.jsx("h3",{className:"font-semibold text-gray-900 dark:text-white",children:"No PII findings recorded"}),i.jsx("p",{className:"mt-2 text-sm text-gray-600 dark:text-gray-300",children:"This profile contains no PII alerts. That does not guarantee the dataset is free of personal information."})]}):i.jsxs("div",{className:"overflow-hidden rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800",children:[i.jsxs("div",{className:"border-b border-gray-200 p-4 dark:border-gray-700",children:[i.jsxs("h3",{className:"font-semibold text-gray-900 dark:text-white",children:[l.length," finding",l.length===1?"":"s"," across ",a," flagged column",a===1?"":"s"]}),i.jsx("p",{className:"mt-1 text-sm text-gray-600 dark:text-gray-300",children:"The detector checks email and phone patterns together; it does not report which pattern matched. Findings describe the saved profile, including columns with pending exclusions."})]}),i.jsx("div",{role:"region","aria-label":"PII findings table",tabIndex:0,className:"overflow-x-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-500",children:i.jsxs("table",{className:"w-full min-w-[600px] text-left text-sm",children:[i.jsx("caption",{className:"sr-only",children:"Possible PII findings from this profile"}),i.jsx("thead",{className:"bg-gray-50 text-gray-600 dark:bg-gray-900/50 dark:text-gray-300",children:i.jsxs("tr",{children:[i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Column"}),i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Detector category"}),i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Severity"}),i.jsx("th",{scope:"col",className:"px-4 py-3 font-medium",children:"Explanation"})]})}),i.jsx("tbody",{className:"divide-y divide-gray-200 dark:divide-gray-700",children:l.map((d,h)=>{const u=d.severity==="error"?"Error":d.severity==="warning"?"Warning":d.severity==="info"?"Info":"Unspecified",m=u==="Error"?"bg-red-50 text-red-800 dark:bg-red-900/30 dark:text-red-200":u==="Warning"?"bg-amber-50 text-amber-800 dark:bg-amber-900/30 dark:text-amber-200":"bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-200";return i.jsxs("tr",{className:"align-top",children:[i.jsx("th",{scope:"row",className:"max-w-64 break-words px-4 py-4 font-medium text-gray-900 dark:text-white",children:d.column||"Column not specified"}),i.jsx("td",{className:"whitespace-nowrap px-4 py-4 text-gray-700 dark:text-gray-200",children:"Email / phone"}),i.jsx("td",{className:"px-4 py-4",children:i.jsx("span",{className:`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${m}`,children:u})}),i.jsx("td",{className:"px-4 py-4 text-gray-600 dark:text-gray-300",children:"Values may match an email address or phone number pattern. Review whether this column is appropriate for your intended use."})]},h)})})]})})]})]})}var ed=il();const Er=br(ed);var td=sl();const id=br(td),sd=id(Er),qn=["circle","square","diamond","cross","x"],nd={circle:"circle",square:"rect",diamond:"rectRot",cross:"cross",x:"crossRot"},rd={circle:"circle",square:"square",diamond:"diamond",cross:"cross",x:"x"},Un=n=>qn[n%qn.length],ad=n=>nd[n],od=n=>rd[n],ld=(n,l)=>{const a=n.localeCompare(l,"en");return a!==0||n===l?a:n{let l="Unlabeled",a=1;for(;n.has(l);)l=a===1?"Unlabeled (missing)":`Unlabeled (missing) ${a}`,a+=1;return l},si=(n,l)=>{if(!l)return[{value:null,label:"Data Points",points:n,color:Ue[0],shape:Un(0)}];const a=new Map;n.forEach(m=>{const p=m[l],g=p==null?null:String(p),N=a.get(g)??[];N.push(m),a.set(g,N)});const d=[...a.keys()].filter(m=>m!==null).sort(ld),h=d.map((m,p)=>({value:m,label:m,points:a.get(m),color:Ue[p%Ue.length],shape:Un(p)})),u=a.get(null);return u&&h.push({value:null,label:dd(new Set(d)),points:u,color:"#6b7280",shape:"cross"}),h},Mr=n=>n.map(({label:l,color:a,shape:d})=>({label:l,color:a,shape:d})),Ar=({data:n,xKey:l,yKey:a,zKey:d,labelKey:h,xLabel:u,yLabel:m,zLabel:p,height:g=600})=>{const N=k.useMemo(()=>si(n,h).map(({label:b,points:j,color:C,shape:w})=>{const S=od(w);return{x:j.map(E=>E[l]??null),y:j.map(E=>E[a]??null),z:j.map(E=>E[d]??null),mode:"markers",type:"scatter3d",name:b,marker:{size:3,opacity:.8,color:C,symbol:S},hovertemplate:`${b}
${u||l}: %{x}
${m||a}: %{y}
${p||d}: %{z}`}}),[n,l,a,d,h,u,m,p]),_=ht();return n.length===0?i.jsx("div",{className:"text-gray-500 text-sm italic p-4 text-center",children:"No data points to display"}):i.jsx("div",{style:{height:g,width:"100%"},children:i.jsx(sd,{data:N,layout:{autosize:!0,height:g,margin:{l:0,r:0,b:0,t:0},paper_bgcolor:_.bgColor,plot_bgcolor:_.bgColor,font:{color:_.textColor},scene:{xaxis:{title:{text:u||l},color:_.axisColor,gridcolor:_.gridColor},yaxis:{title:{text:m||a},color:_.axisColor,gridcolor:_.gridColor},zaxis:{title:{text:p||d},color:_.axisColor,gridcolor:_.gridColor}},showlegend:!1},useResizeHandler:!0,style:{width:"100%",height:"100%"},config:{displayModeBar:!0}})})};Uo.register(Go,Ko,Yo,Jo,Qo);const zr=({data:n,xKey:l,yKey:a,labelKey:d,xLabel:h,yLabel:u,height:m=500})=>{const p=k.useMemo(()=>si(n,d).map(({label:v,points:b,color:j,shape:C})=>({label:v,data:b.map(w=>({x:Number(w[l]),y:Number(w[a]),raw:w})),backgroundColor:j,borderColor:j,pointStyle:ad(C),pointRadius:3,pointHoverRadius:5})),[n,l,a,d]),g=ht(),N={responsive:!0,maintainAspectRatio:!1,scales:{x:{title:{display:!!h,text:h,color:g.axisColor,font:{weight:"bold"}},grid:{color:g.gridColor,lineWidth:1},ticks:{color:g.axisColor}},y:{title:{display:!!u,text:u,color:g.axisColor,font:{weight:"bold"}},grid:{color:g.gridColor,lineWidth:1},ticks:{color:g.axisColor}}},plugins:{tooltip:{callbacks:{label:_=>{const v=_.parsed;let b=_.dataset.label||"";return b&&(b+=": "),b+=`(${v.x}, ${v.y})`,b}}},legend:{display:!1}}};return i.jsx("div",{style:{height:m,width:"100%"},children:i.jsx(qo,{options:N,data:{datasets:p}})})},cd=({shape:n,color:l})=>{const a={width:12,height:12,"aria-hidden":!0};switch(n){case"square":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("rect",{x:"1",y:"1",width:"10",height:"10",fill:l})});case"diamond":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("polygon",{points:"6,0 12,6 6,12 0,6",fill:l})});case"cross":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("path",{d:"M6 1 L6 11 M1 6 L11 6",stroke:l,strokeWidth:2})});case"x":return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("path",{d:"M2 2 L10 10 M10 2 L2 10",stroke:l,strokeWidth:2})});case"circle":default:return i.jsx("svg",{...a,viewBox:"0 0 12 12",children:i.jsx("circle",{cx:"6",cy:"6",r:"5",fill:l})})}},Ps=({entries:n,filterThreshold:l=12})=>{const[a,d]=k.useState(""),h=k.useMemo(()=>{if(!a.trim())return n;const m=a.trim().toLowerCase();return n.filter(p=>p.label.toLowerCase().includes(m))},[n,a]);if(n.length===0)return null;const u=n.length>l;return i.jsxs("div",{className:"mt-3 border border-gray-200 dark:border-gray-700 rounded-md p-2",children:[u&&i.jsx("input",{type:"search",value:a,onChange:m=>d(m.target.value),placeholder:`Filter ${n.length} legend groups…`,"aria-label":"Filter legend groups",className:"mb-2 w-full text-xs rounded border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white px-2 py-1"}),i.jsxs("ul",{className:`flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-gray-700 dark:text-gray-300 ${u?"max-h-32 overflow-y-auto":""}`,children:[h.map(m=>i.jsxs("li",{className:"flex items-center gap-1.5",children:[i.jsx(cd,{shape:m.shape,color:m.color}),i.jsx("span",{className:"truncate max-w-[10rem]",title:m.label,children:m.label})]},m.label)),h.length===0&&i.jsxs("li",{className:"italic text-gray-500 dark:text-gray-400",children:["No groups match “",a,"”."]})]})]})},hd=({profile:n,downloadChart:l})=>{var d;const a=n.clustering;return a?i.jsxs("div",{className:"mt-4 space-y-6",id:"clustering-chart",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Lt,{className:"w-5 h-5 mr-2 text-rose-500"}),"Post-Hoc Clustering (Segmentation)",i.jsx(be,{text:"Automatically groups data points into distinct clusters (segments) based on similarity. Useful for finding natural groups like 'High Spenders' or 'At Risk' users."})]}),i.jsx("button",{onClick:()=>l("clustering-chart","clustering-summary","Clustering Summary",`${a.n_clusters} Clusters Found`),className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300",title:"Download Summary","aria-label":"Download Summary",children:i.jsx(Ne,{className:"w-4 h-4"})})]}),i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:i.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:i.jsxs("div",{className:"p-4 bg-purple-50 dark:bg-purple-900/10 rounded-lg border border-purple-100 dark:border-purple-800",children:[i.jsx("h4",{className:"text-sm font-semibold text-purple-900 dark:text-purple-100 mb-2",children:"Algorithm Summary"}),i.jsxs("div",{className:"space-y-1 text-sm text-purple-700 dark:text-purple-300",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{children:"Method:"}),i.jsx("span",{className:"font-medium",children:a.method})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{children:"Metric (Inertia):"}),i.jsx("span",{className:"font-medium",children:((d=a.inertia)==null?void 0:d.toFixed(1))??"N/A"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{children:"Clusters:"}),i.jsx("span",{className:"font-medium",children:a.n_clusters})]})]})]})}),i.jsx("h4",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mt-4",children:"Cluster Profiles (Centroids)"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:a.clusters.map(h=>i.jsxs("div",{className:"p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("span",{className:"font-bold text-gray-900 dark:text-white flex items-center",children:[i.jsx("span",{className:"w-3 h-3 rounded-full mr-2",style:{backgroundColor:ud(h.cluster_id)}}),"Cluster ",h.cluster_id]}),i.jsxs("span",{className:"text-xs px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded-full text-gray-600 dark:text-gray-300",children:[h.percentage.toFixed(1),"% (",h.size,")"]})]}),i.jsxs("div",{className:"space-y-1",children:[Object.entries(h.center).sort(([,u],[,m])=>Math.abs(m??0)-Math.abs(u??0)).slice(0,5).map(([u,m])=>i.jsxs("div",{className:"flex justify-between text-xs",children:[i.jsx("span",{className:"text-gray-500 dark:text-gray-400 truncate w-24",title:u,children:u}),i.jsx("span",{className:"font-mono text-gray-700 dark:text-gray-200",children:(m==null?void 0:m.toFixed(2))??"N/A"})]},u)),Object.keys(h.center).length>5&&i.jsxs("div",{className:"text-xs text-center text-gray-400 italic pt-1",children:["+ ",Object.keys(h.center).length-5," more features"]})]})]},h.cluster_id))})]})})]}),i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded-lg text-sm border border-blue-100 dark:border-blue-800",children:[i.jsx(Pt,{className:"w-5 h-5 flex-shrink-0 mt-0.5"}),i.jsx("div",{children:"This summary shows the clustering method, inertia and cluster profiles. Each profile lists up to five centroid feature values, ordered by absolute magnitude."})]})]}):i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm flex flex-col items-center justify-center text-gray-500 min-h-[300px]",children:[i.jsx(Lt,{className:"w-12 h-12 mb-4 opacity-20"}),i.jsx("p",{children:"Clustering analysis not available."}),i.jsx("p",{className:"text-sm mt-2",children:"No clustering results were recorded for this report."})]})},ud=n=>Ue[n%Ue.length];function md({components:n,isPCA3D:l}){return i.jsx(i.Fragment,{children:n&&n.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("h4",{className:"text-sm font-medium text-gray-900 dark:text-gray-100 mb-3",children:"Principal Component Composition"}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:n.slice(0,l?3:2).map(a=>i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900/50 p-3 rounded-md border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex justify-between items-center border-b border-gray-200 dark:border-gray-700 pb-2 mb-2",children:[i.jsx("span",{className:"font-semibold text-gray-800 dark:text-gray-200",children:a.component}),i.jsxs("span",{className:"text-xs bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 px-2 py-0.5 rounded-full",children:[(a.explained_variance_ratio*100).toFixed(1),"% Var"]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-[10px] text-gray-500 uppercase tracking-wider mb-1",children:"Top Loadings"}),Object.entries(a.top_features||{}).map(([d,h],u)=>i.jsxs("div",{className:"flex justify-between text-xs items-center group",children:[i.jsx("span",{className:"text-gray-600 dark:text-gray-400 truncate mr-2 flex-1",title:d,children:d}),i.jsxs("span",{className:`font-mono text-[10px] ${Number(h)>0?"text-green-600 dark:text-green-400":"text-red-500 dark:text-red-400"}`,children:[Number(h)>0?"+":"",Number(h).toFixed(3)]})]},u))]})]},a.component))})]})})}const fd=({profile:n,isPCA3D:l,setIsPCA3D:a,downloadChart:d})=>{const h=Array.isArray(n.pca_data)&&n.pca_data.length>0,u=h?"Download Chart":"PCA results unavailable",m=k.useMemo(()=>n.pca_data??[],[n.pca_data]),p=k.useMemo(()=>Mr(si(m,"label")),[m]),g=k.useMemo(()=>{const N=[{key:"x",label:"PC1"},{key:"y",label:"PC2"}];return l&&N.push({key:"z",label:"PC3"}),N.push({key:"label",label:"Group"}),N},[l]);return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Kt,{className:"w-5 h-5 mr-2 text-purple-500"}),"Multivariate Structure (PCA)",i.jsx(be,{text:"Reduces data to 2D or 3D. Points closer together are similar. Colors show clusters or target values."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{disabled:!h,onClick:()=>d("pca-chart","pca-analysis","Multivariate Structure (PCA)",l?"3D Projection":"2D Projection"),className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 disabled:opacity-50",title:u,"aria-label":u,children:i.jsx(Ne,{className:"w-4 h-4"})}),i.jsxs("button",{onClick:()=>a(!l),className:`p-2 rounded-md border transition-colors flex items-center gap-2 text-sm ${l?"bg-blue-50 border-blue-200 text-blue-700 dark:bg-blue-900/20 dark:border-blue-800 dark:text-blue-300":"bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300"}`,children:[i.jsx(wr,{className:"w-4 h-4"}),l?"Switch to 2D":"Switch to 3D"]})]})]}),i.jsx("div",{id:"pca-chart",children:n.pca_data?l?i.jsx(Ar,{data:n.pca_data,xKey:"x",yKey:"y",zKey:"z",labelKey:"label",xLabel:"PC1",yLabel:"PC2",zLabel:"PC3"}):i.jsx(zr,{data:n.pca_data,xKey:"x",yKey:"y",labelKey:"label",xLabel:"Principal Component 1 (PC1)",yLabel:"Principal Component 2 (PC2)"}):i.jsx("div",{className:"h-64 flex items-center justify-center bg-gray-50 dark:bg-gray-900 rounded text-gray-400 text-sm text-center p-4",children:"No PCA projection was recorded for this report."})}),p.length>0&&i.jsx(Ps,{entries:p}),i.jsx(Si,{caption:"PCA projection data",filename:"pca-analysis",columns:g,rows:m}),i.jsxs("div",{className:"mt-6 flex items-start gap-2 bg-blue-50 dark:bg-blue-900/20 p-3 rounded-md border border-blue-100 dark:border-blue-800",children:[i.jsx(Pt,{className:"w-4 h-4 text-blue-500 mt-0.5 shrink-0"}),i.jsxs("div",{className:"text-sm text-blue-700 dark:text-blue-300",children:[i.jsx("p",{className:"font-medium mb-1",children:"About this visualization"}),i.jsxs("p",{children:["This chart shows a ",l?"3D":"2D"," projection of your data using Principal Component Analysis (PCA). Points that are close together share similar characteristics across all numeric features."]}),i.jsxs("p",{className:"mt-1 text-xs opacity-80",children:["* For performance, this visualization uses a random sample of up to ",i.jsx("strong",{children:"5,000 points"}),"."]})]})]}),i.jsx(md,{components:n.pca_components,isPCA3D:l})]}),i.jsx(hd,{profile:n,downloadChart:d})]})};function Ir(n,l){const a=k.useRef(l);k.useEffect(function(){l!==a.current&&n.attributionControl!=null&&(a.current!=null&&n.attributionControl.removeAttribution(a.current),l!=null&&n.attributionControl.addAttribution(l)),a.current=l},[n,l])}function gd(n,l,a){l.center!==a.center&&n.setLatLng(l.center),l.radius!=null&&l.radius!==a.radius&&n.setRadius(l.radius)}const pd=1;function xd(n){return Object.freeze({__version:pd,map:n})}function _d(n,l){return Object.freeze({...n,...l})}const Or=k.createContext(null),Dr=Or.Provider;function Ss(){const n=k.useContext(Or);if(n==null)throw new Error("No context provided: useLeafletContext() can only be used in a descendant of ");return n}function yd(n){function l(a,d){const{instance:h,context:u}=n(a).current;return k.useImperativeHandle(d,()=>h),a.children==null?null:Yt.createElement(Dr,{value:u},a.children)}return k.forwardRef(l)}function vd(n){function l(a,d){const[h,u]=k.useState(!1),{instance:m}=n(a,u).current;k.useImperativeHandle(d,()=>m),k.useEffect(function(){h&&m.update()},[m,h,a.children]);const p=m._contentNode;return p?Xo.createPortal(a.children,p):null}return k.forwardRef(l)}function bd(n){function l(a,d){const{instance:h}=n(a).current;return k.useImperativeHandle(d,()=>h),null}return k.forwardRef(l)}function Ts(n,l){const a=k.useRef();k.useEffect(function(){return l!=null&&n.instance.on(l),a.current=l,function(){a.current!=null&&n.instance.off(a.current),a.current=null}},[n,l])}function Ti(n,l){const a=n.pane??l.pane;return a?{...n,pane:a}:n}function wd(n,l){return function(d,h){const u=Ss(),m=n(Ti(d,u),u);return Ir(u.map,d.attribution),Ts(m.current,d.eventHandlers),l(m.current,u,d,h),m}}var Ut={exports:{}};/* @preserve * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade */var jd=Ut.exports,Gn;function kd(){return Gn||(Gn=1,(function(n,l){(function(a,d){d(l)})(jd,(function(a){var d="1.9.4";function h(e){var t,s,r,o;for(s=1,r=arguments.length;s"u"||!L||!L.Mixin)){e=O(e)?e:[e];for(var t=0;t0?Math.floor(e):Math.ceil(e)};A.prototype={clone:function(){return new A(this.x,this.y)},add:function(e){return this.clone()._add(z(e))},_add:function(e){return this.x+=e.x,this.y+=e.y,this},subtract:function(e){return this.clone()._subtract(z(e))},_subtract:function(e){return this.x-=e.x,this.y-=e.y,this},divideBy:function(e){return this.clone()._divideBy(e)},_divideBy:function(e){return this.x/=e,this.y/=e,this},multiplyBy:function(e){return this.clone()._multiplyBy(e)},_multiplyBy:function(e){return this.x*=e,this.y*=e,this},scaleBy:function(e){return new A(this.x*e.x,this.y*e.y)},unscaleBy:function(e){return new A(this.x/e.x,this.y/e.y)},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.clone()._ceil()},_ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},trunc:function(){return this.clone()._trunc()},_trunc:function(){return this.x=ae(this.x),this.y=ae(this.y),this},distanceTo:function(e){e=z(e);var t=e.x-this.x,s=e.y-this.y;return Math.sqrt(t*t+s*s)},equals:function(e){return e=z(e),e.x===this.x&&e.y===this.y},contains:function(e){return e=z(e),Math.abs(e.x)<=Math.abs(this.x)&&Math.abs(e.y)<=Math.abs(this.y)},toString:function(){return"Point("+b(this.x)+", "+b(this.y)+")"}};function z(e,t,s){return e instanceof A?e:O(e)?new A(e[0],e[1]):e==null?e:typeof e=="object"&&"x"in e&&"y"in e?new A(e.x,e.y):new A(e,t,s)}function H(e,t){if(e)for(var s=t?[e,t]:e,r=0,o=s.length;r=this.min.x&&s.x<=this.max.x&&t.y>=this.min.y&&s.y<=this.max.y},intersects:function(e){e=se(e);var t=this.min,s=this.max,r=e.min,o=e.max,c=o.x>=t.x&&r.x<=s.x,f=o.y>=t.y&&r.y<=s.y;return c&&f},overlaps:function(e){e=se(e);var t=this.min,s=this.max,r=e.min,o=e.max,c=o.x>t.x&&r.xt.y&&r.y=t.lat&&o.lat<=s.lat&&r.lng>=t.lng&&o.lng<=s.lng},intersects:function(e){e=U(e);var t=this._southWest,s=this._northEast,r=e.getSouthWest(),o=e.getNorthEast(),c=o.lat>=t.lat&&r.lat<=s.lat,f=o.lng>=t.lng&&r.lng<=s.lng;return c&&f},overlaps:function(e){e=U(e);var t=this._southWest,s=this._northEast,r=e.getSouthWest(),o=e.getNorthEast(),c=o.lat>t.lat&&r.latt.lng&&r.lng1,na=(function(){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("testPassiveEventSupport",v,t),window.removeEventListener("testPassiveEventSupport",v,t)}catch{}return e})(),ra=(function(){return!!document.createElement("canvas").getContext})(),Ii=!!(document.createElementNS&&he("svg").createSVGRect),aa=!!Ii&&(function(){var e=document.createElement("div");return e.innerHTML="",(e.firstChild&&e.firstChild.namespaceURI)==="http://www.w3.org/2000/svg"})(),oa=!Ii&&(function(){try{var e=document.createElement("div");e.innerHTML='';var t=e.firstChild;return t.style.behavior="url(#default#VML)",t&&typeof t.adj=="object"}catch{return!1}})(),la=navigator.platform.indexOf("Mac")===0,da=navigator.platform.indexOf("Linux")===0;function De(e){return navigator.userAgent.toLowerCase().indexOf(e)>=0}var D={ie:ut,ielt9:qr,edge:As,webkit:Mi,android:zs,android23:Is,androidStock:Gr,opera:Ai,chrome:Os,gecko:Ds,safari:Kr,phantom:Rs,opera12:Bs,win:Yr,ie3d:Fs,webkit3d:zi,gecko3d:Zs,any3d:Jr,mobile:Mt,mobileWebkit:Qr,mobileWebkit3d:Xr,msPointer:$s,pointer:Hs,touch:ea,touchNative:Ws,mobileOpera:ta,mobileGecko:ia,retina:sa,passiveEvents:na,canvas:ra,svg:Ii,vml:oa,inlineSvg:aa,mac:la,linux:da},Vs=D.msPointer?"MSPointerDown":"pointerdown",qs=D.msPointer?"MSPointerMove":"pointermove",Us=D.msPointer?"MSPointerUp":"pointerup",Gs=D.msPointer?"MSPointerCancel":"pointercancel",Oi={touchstart:Vs,touchmove:qs,touchend:Us,touchcancel:Gs},Ks={touchstart:ga,touchmove:ni,touchend:ni,touchcancel:ni},mt={},Ys=!1;function ca(e,t,s){return t==="touchstart"&&fa(),Ks[t]?(s=Ks[t].bind(this,s),e.addEventListener(Oi[t],s,!1),s):(console.warn("wrong event specified:",t),v)}function ha(e,t,s){if(!Oi[t]){console.warn("wrong event specified:",t);return}e.removeEventListener(Oi[t],s,!1)}function ua(e){mt[e.pointerId]=e}function ma(e){mt[e.pointerId]&&(mt[e.pointerId]=e)}function Js(e){delete mt[e.pointerId]}function fa(){Ys||(document.addEventListener(Vs,ua,!0),document.addEventListener(qs,ma,!0),document.addEventListener(Us,Js,!0),document.addEventListener(Gs,Js,!0),Ys=!0)}function ni(e,t){if(t.pointerType!==(t.MSPOINTER_TYPE_MOUSE||"mouse")){t.touches=[];for(var s in mt)t.touches.push(mt[s]);t.changedTouches=[t],e(t)}}function ga(e,t){t.MSPOINTER_TYPE_TOUCH&&t.pointerType===t.MSPOINTER_TYPE_TOUCH&&ve(t),ni(e,t)}function pa(e){var t={},s,r;for(r in e)s=e[r],t[r]=s&&s.bind?s.bind(e):s;return e=t,t.type="dblclick",t.detail=2,t.isTrusted=!1,t._simulated=!0,t}var xa=200;function _a(e,t){e.addEventListener("dblclick",t);var s=0,r;function o(c){if(c.detail!==1){r=c.detail;return}if(!(c.pointerType==="mouse"||c.sourceCapabilities&&!c.sourceCapabilities.firesTouchEvents)){var f=sn(c);if(!(f.some(function(y){return y instanceof HTMLLabelElement&&y.attributes.for})&&!f.some(function(y){return y instanceof HTMLInputElement||y instanceof HTMLSelectElement}))){var x=Date.now();x-s<=xa?(r++,r===2&&t(pa(c))):r=1,s=x}}}return e.addEventListener("click",o),{dblclick:t,simDblclick:o}}function ya(e,t){e.removeEventListener("dblclick",t.dblclick),e.removeEventListener("click",t.simDblclick)}var Di=oi(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),At=oi(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),Qs=At==="webkitTransition"||At==="OTransition"?At+"End":"transitionend";function Xs(e){return typeof e=="string"?document.getElementById(e):e}function zt(e,t){var s=e.style[t]||e.currentStyle&&e.currentStyle[t];if((!s||s==="auto")&&document.defaultView){var r=document.defaultView.getComputedStyle(e,null);s=r?r[t]:null}return s==="auto"?null:s}function te(e,t,s){var r=document.createElement(e);return r.className=t||"",s&&s.appendChild(r),r}function de(e){var t=e.parentNode;t&&t.removeChild(e)}function ri(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function ft(e){var t=e.parentNode;t&&t.lastChild!==e&&t.appendChild(e)}function gt(e){var t=e.parentNode;t&&t.firstChild!==e&&t.insertBefore(e,t.firstChild)}function Ri(e,t){if(e.classList!==void 0)return e.classList.contains(t);var s=ai(e);return s.length>0&&new RegExp("(^|\\s)"+t+"(\\s|$)").test(s)}function G(e,t){if(e.classList!==void 0)for(var s=C(t),r=0,o=s.length;r0?2*window.devicePixelRatio:1;function rn(e){return D.edge?e.wheelDeltaY/2:e.deltaY&&e.deltaMode===0?-e.deltaY/wa:e.deltaY&&e.deltaMode===1?-e.deltaY*20:e.deltaY&&e.deltaMode===2?-e.deltaY*60:e.deltaX||e.deltaZ?0:e.wheelDelta?(e.wheelDeltaY||e.wheelDelta)/2:e.detail&&Math.abs(e.detail)<32765?-e.detail*20:e.detail?e.detail/-32765*60:0}function Yi(e,t){var s=t.relatedTarget;if(!s)return!0;try{for(;s&&s!==e;)s=s.parentNode}catch{return!1}return s!==e}var ja={__proto__:null,on:V,off:oe,stopPropagation:nt,disableScrollPropagation:Ki,disableClickPropagation:Rt,preventDefault:ve,stop:rt,getPropagationPath:sn,getMousePosition:nn,getWheelDelta:rn,isExternalTarget:Yi,addListener:V,removeListener:oe},an=re.extend({run:function(e,t,s,r){this.stop(),this._el=e,this._inProgress=!0,this._duration=s||.25,this._easeOutPower=1/Math.max(r||.5,.2),this._startPos=st(e),this._offset=t.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(!0),this._complete())},_animate:function(){this._animId=q(this._animate,this),this._step()},_step:function(e){var t=+new Date-this._startTime,s=this._duration*1e3;tthis.options.maxZoom)?this.setZoom(e):this},panInsideBounds:function(e,t){this._enforcingBounds=!0;var s=this.getCenter(),r=this._limitCenter(s,this._zoom,U(e));return s.equals(r)||this.panTo(r,t),this._enforcingBounds=!1,this},panInside:function(e,t){t=t||{};var s=z(t.paddingTopLeft||t.padding||[0,0]),r=z(t.paddingBottomRight||t.padding||[0,0]),o=this.project(this.getCenter()),c=this.project(e),f=this.getPixelBounds(),x=se([f.min.add(s),f.max.subtract(r)]),y=x.getSize();if(!x.contains(c)){this._enforcingBounds=!0;var P=c.subtract(x.getCenter()),M=x.extend(c).getSize().subtract(y);o.x+=P.x<0?-M.x:M.x,o.y+=P.y<0?-M.y:M.y,this.panTo(this.unproject(o),t),this._enforcingBounds=!1}return this},invalidateSize:function(e){if(!this._loaded)return this;e=h({animate:!1,pan:!0},e===!0?{animate:!0}:e);var t=this.getSize();this._sizeChanged=!0,this._lastCenter=null;var s=this.getSize(),r=t.divideBy(2).round(),o=s.divideBy(2).round(),c=r.subtract(o);return!c.x&&!c.y?this:(e.animate&&e.pan?this.panBy(c):(e.pan&&this._rawPanBy(c),this.fire("move"),e.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(m(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:t,newSize:s}))},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(e){if(e=this._locateOptions=h({timeout:1e4,watch:!1},e),!("geolocation"in navigator))return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var t=m(this._handleGeolocationResponse,this),s=m(this._handleGeolocationError,this);return e.watch?this._locationWatchId=navigator.geolocation.watchPosition(t,s,e):navigator.geolocation.getCurrentPosition(t,s,e),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(e){if(this._container._leaflet_id){var t=e.code,s=e.message||(t===1?"permission denied":t===2?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:t,message:"Geolocation error: "+s+"."})}},_handleGeolocationResponse:function(e){if(this._container._leaflet_id){var t=e.coords.latitude,s=e.coords.longitude,r=new W(t,s),o=r.toBounds(e.coords.accuracy*2),c=this._locateOptions;if(c.setView){var f=this.getBoundsZoom(o);this.setView(r,c.maxZoom?Math.min(f,c.maxZoom):f)}var x={latlng:r,bounds:o,timestamp:e.timestamp};for(var y in e.coords)typeof e.coords[y]=="number"&&(x[y]=e.coords[y]);this.fire("locationfound",x)}},addHandler:function(e,t){if(!t)return this;var s=this[e]=new t(this);return this._handlers.push(s),this.options[e]&&s.enable(),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch{this._container._leaflet_id=void 0,this._containerId=void 0}this._locationWatchId!==void 0&&this.stopLocate(),this._stop(),de(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(ee(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload");var e;for(e in this._layers)this._layers[e].remove();for(e in this._panes)de(this._panes[e]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(e,t){var s="leaflet-pane"+(e?" leaflet-"+e.replace("Pane","")+"-pane":""),r=te("div",s,t||this._mapPane);return e&&(this._panes[e]=r),r},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var e=this.getPixelBounds(),t=this.unproject(e.getBottomLeft()),s=this.unproject(e.getTopRight());return new ne(t,s)},getMinZoom:function(){return this.options.minZoom===void 0?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===void 0?this._layersMaxZoom===void 0?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(e,t,s){e=U(e),s=z(s||[0,0]);var r=this.getZoom()||0,o=this.getMinZoom(),c=this.getMaxZoom(),f=e.getNorthWest(),x=e.getSouthEast(),y=this.getSize().subtract(s),P=se(this.project(x,r),this.project(f,r)).getSize(),M=D.any3d?this.options.zoomSnap:1,Z=y.x/P.x,Y=y.y/P.y,we=t?Math.max(Z,Y):Math.min(Z,Y);return r=this.getScaleZoom(we,r),M&&(r=Math.round(r/(M/100))*(M/100),r=t?Math.ceil(r/M)*M:Math.floor(r/M)*M),Math.max(o,Math.min(c,r))},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new A(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(e,t){var s=this._getTopLeftPoint(e,t);return new H(s,s.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(e){return this.options.crs.getProjectedBounds(e===void 0?this.getZoom():e)},getPane:function(e){return typeof e=="string"?this._panes[e]:e},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(e,t){var s=this.options.crs;return t=t===void 0?this._zoom:t,s.scale(e)/s.scale(t)},getScaleZoom:function(e,t){var s=this.options.crs;t=t===void 0?this._zoom:t;var r=s.zoom(e*s.scale(t));return isNaN(r)?1/0:r},project:function(e,t){return t=t===void 0?this._zoom:t,this.options.crs.latLngToPoint($(e),t)},unproject:function(e,t){return t=t===void 0?this._zoom:t,this.options.crs.pointToLatLng(z(e),t)},layerPointToLatLng:function(e){var t=z(e).add(this.getPixelOrigin());return this.unproject(t)},latLngToLayerPoint:function(e){var t=this.project($(e))._round();return t._subtract(this.getPixelOrigin())},wrapLatLng:function(e){return this.options.crs.wrapLatLng($(e))},wrapLatLngBounds:function(e){return this.options.crs.wrapLatLngBounds(U(e))},distance:function(e,t){return this.options.crs.distance($(e),$(t))},containerPointToLayerPoint:function(e){return z(e).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(e){return z(e).add(this._getMapPanePos())},containerPointToLatLng:function(e){var t=this.containerPointToLayerPoint(z(e));return this.layerPointToLatLng(t)},latLngToContainerPoint:function(e){return this.layerPointToContainerPoint(this.latLngToLayerPoint($(e)))},mouseEventToContainerPoint:function(e){return nn(e,this._container)},mouseEventToLayerPoint:function(e){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e))},mouseEventToLatLng:function(e){return this.layerPointToLatLng(this.mouseEventToLayerPoint(e))},_initContainer:function(e){var t=this._container=Xs(e);if(t){if(t._leaflet_id)throw new Error("Map container is already initialized.")}else throw new Error("Map container not found.");V(t,"scroll",this._onScroll,this),this._containerId=g(t)},_initLayout:function(){var e=this._container;this._fadeAnimated=this.options.fadeAnimation&&D.any3d,G(e,"leaflet-container"+(D.touch?" leaflet-touch":"")+(D.retina?" leaflet-retina":"")+(D.ielt9?" leaflet-oldie":"")+(D.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":""));var t=zt(e,"position");t!=="absolute"&&t!=="relative"&&t!=="fixed"&&t!=="sticky"&&(e.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var e=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),me(this._mapPane,new A(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(G(e.markerPane,"leaflet-zoom-hide"),G(e.shadowPane,"leaflet-zoom-hide"))},_resetView:function(e,t,s){me(this._mapPane,new A(0,0));var r=!this._loaded;this._loaded=!0,t=this._limitZoom(t),this.fire("viewprereset");var o=this._zoom!==t;this._moveStart(o,s)._move(e,t)._moveEnd(o),this.fire("viewreset"),r&&this.fire("load")},_moveStart:function(e,t){return e&&this.fire("zoomstart"),t||this.fire("movestart"),this},_move:function(e,t,s,r){t===void 0&&(t=this._zoom);var o=this._zoom!==t;return this._zoom=t,this._lastCenter=e,this._pixelOrigin=this._getNewPixelOrigin(e),r?s&&s.pinch&&this.fire("zoom",s):((o||s&&s.pinch)&&this.fire("zoom",s),this.fire("move",s)),this},_moveEnd:function(e){return e&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return ee(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(e){me(this._mapPane,this._getMapPanePos().subtract(e))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(e){this._targets={},this._targets[g(this._container)]=this;var t=e?oe:V;t(this._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&t(window,"resize",this._onResize,this),D.any3d&&this.options.transform3DLimit&&(e?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){ee(this._resizeRequest),this._resizeRequest=q(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var e=this._getMapPanePos();Math.max(Math.abs(e.x),Math.abs(e.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(e,t){for(var s=[],r,o=t==="mouseout"||t==="mouseover",c=e.target||e.srcElement,f=!1;c;){if(r=this._targets[g(c)],r&&(t==="click"||t==="preclick")&&this._draggableMoved(r)){f=!0;break}if(r&&r.listens(t,!0)&&(o&&!Yi(c,e)||(s.push(r),o))||c===this._container)break;c=c.parentNode}return!s.length&&!f&&!o&&this.listens(t,!0)&&(s=[this]),s},_isClickDisabled:function(e){for(;e&&e!==this._container;){if(e._leaflet_disable_click)return!0;e=e.parentNode}},_handleDOMEvent:function(e){var t=e.target||e.srcElement;if(!(!this._loaded||t._leaflet_disable_events||e.type==="click"&&this._isClickDisabled(t))){var s=e.type;s==="mousedown"&&Wi(t),this._fireDOMEvent(e,s)}},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(e,t,s){if(e.type==="click"){var r=h({},e);r.type="preclick",this._fireDOMEvent(r,r.type,s)}var o=this._findEventTargets(e,t);if(s){for(var c=[],f=0;f0?Math.round(e-t)/2:Math.max(0,Math.ceil(e))-Math.max(0,Math.floor(t))},_limitZoom:function(e){var t=this.getMinZoom(),s=this.getMaxZoom(),r=D.any3d?this.options.zoomSnap:1;return r&&(e=Math.round(e/r)*r),Math.max(t,Math.min(s,e))},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){ue(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(e,t){var s=this._getCenterOffset(e)._trunc();return(t&&t.animate)!==!0&&!this.getSize().contains(s)?!1:(this.panBy(s,t),!0)},_createAnimProxy:function(){var e=this._proxy=te("div","leaflet-proxy leaflet-zoom-animated");this._panes.mapPane.appendChild(e),this.on("zoomanim",function(t){var s=Di,r=this._proxy.style[s];it(this._proxy,this.project(t.center,t.zoom),this.getZoomScale(t.zoom,1)),r===this._proxy.style[s]&&this._animatingZoom&&this._onZoomTransitionEnd()},this),this.on("load moveend",this._animMoveEnd,this),this._on("unload",this._destroyAnimProxy,this)},_destroyAnimProxy:function(){de(this._proxy),this.off("load moveend",this._animMoveEnd,this),delete this._proxy},_animMoveEnd:function(){var e=this.getCenter(),t=this.getZoom();it(this._proxy,this.project(e,t),this.getZoomScale(t,1))},_catchTransitionEnd:function(e){this._animatingZoom&&e.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(e,t,s){if(this._animatingZoom)return!0;if(s=s||{},!this._zoomAnimated||s.animate===!1||this._nothingToAnimate()||Math.abs(t-this._zoom)>this.options.zoomAnimationThreshold)return!1;var r=this.getZoomScale(t),o=this._getCenterOffset(e)._divideBy(1-1/r);return s.animate!==!0&&!this.getSize().contains(o)?!1:(q(function(){this._moveStart(!0,s.noMoveStart||!1)._animateZoom(e,t,!0)},this),!0)},_animateZoom:function(e,t,s,r){this._mapPane&&(s&&(this._animatingZoom=!0,this._animateToCenter=e,this._animateToZoom=t,G(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:e,zoom:t,noUpdate:r}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(m(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&ue(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function ka(e,t){return new J(e,t)}var Ae=B.extend({options:{position:"topright"},initialize:function(e){w(this,e)},getPosition:function(){return this.options.position},setPosition:function(e){var t=this._map;return t&&t.removeControl(this),this.options.position=e,t&&t.addControl(this),this},getContainer:function(){return this._container},addTo:function(e){this.remove(),this._map=e;var t=this._container=this.onAdd(e),s=this.getPosition(),r=e._controlCorners[s];return G(t,"leaflet-control"),s.indexOf("bottom")!==-1?r.insertBefore(t,r.firstChild):r.appendChild(t),this._map.on("unload",this.remove,this),this},remove:function(){return this._map?(de(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null,this):this},_refocusOnMap:function(e){this._map&&e&&e.screenX>0&&e.screenY>0&&this._map.getContainer().focus()}}),Bt=function(e){return new Ae(e)};J.include({addControl:function(e){return e.addTo(this),this},removeControl:function(e){return e.remove(),this},_initControlPos:function(){var e=this._controlCorners={},t="leaflet-",s=this._controlContainer=te("div",t+"control-container",this._container);function r(o,c){var f=t+o+" "+t+c;e[o+c]=te("div",f,s)}r("top","left"),r("top","right"),r("bottom","left"),r("bottom","right")},_clearControlPos:function(){for(var e in this._controlCorners)de(this._controlCorners[e]);de(this._controlContainer),delete this._controlCorners,delete this._controlContainer}});var on=Ae.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0,hideSingleBase:!1,sortLayers:!1,sortFunction:function(e,t,s,r){return s1,this._baseLayersList.style.display=e?"":"none"),this._separator.style.display=t&&e?"":"none",this},_onLayerChange:function(e){this._handlingClick||this._update();var t=this._getLayer(g(e.target)),s=t.overlay?e.type==="add"?"overlayadd":"overlayremove":e.type==="add"?"baselayerchange":null;s&&this._map.fire(s,t)},_createRadioElement:function(e,t){var s='",r=document.createElement("div");return r.innerHTML=s,r.firstChild},_addItem:function(e){var t=document.createElement("label"),s=this._map.hasLayer(e.layer),r;e.overlay?(r=document.createElement("input"),r.type="checkbox",r.className="leaflet-control-layers-selector",r.defaultChecked=s):r=this._createRadioElement("leaflet-base-layers_"+g(this),s),this._layerControlInputs.push(r),r.layerId=g(e.layer),V(r,"click",this._onInputClick,this);var o=document.createElement("span");o.innerHTML=" "+e.name;var c=document.createElement("span");t.appendChild(c),c.appendChild(r),c.appendChild(o);var f=e.overlay?this._overlaysList:this._baseLayersList;return f.appendChild(t),this._checkDisabledLayers(),t},_onInputClick:function(){if(!this._preventClick){var e=this._layerControlInputs,t,s,r=[],o=[];this._handlingClick=!0;for(var c=e.length-1;c>=0;c--)t=e[c],s=this._getLayer(t.layerId).layer,t.checked?r.push(s):t.checked||o.push(s);for(c=0;c=0;o--)t=e[o],s=this._getLayer(t.layerId).layer,t.disabled=s.options.minZoom!==void 0&&rs.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expandSafely:function(){var e=this._section;this._preventClick=!0,V(e,"click",ve),this.expand();var t=this;setTimeout(function(){oe(e,"click",ve),t._preventClick=!1})}}),Na=function(e,t,s){return new on(e,t,s)},Ji=Ae.extend({options:{position:"topleft",zoomInText:'',zoomInTitle:"Zoom in",zoomOutText:'',zoomOutTitle:"Zoom out"},onAdd:function(e){var t="leaflet-control-zoom",s=te("div",t+" leaflet-bar"),r=this.options;return this._zoomInButton=this._createButton(r.zoomInText,r.zoomInTitle,t+"-in",s,this._zoomIn),this._zoomOutButton=this._createButton(r.zoomOutText,r.zoomOutTitle,t+"-out",s,this._zoomOut),this._updateDisabled(),e.on("zoomend zoomlevelschange",this._updateDisabled,this),s},onRemove:function(e){e.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(e){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(e.shiftKey?3:1))},_createButton:function(e,t,s,r,o){var c=te("a",s,r);return c.innerHTML=e,c.href="#",c.title=t,c.setAttribute("role","button"),c.setAttribute("aria-label",t),Rt(c),V(c,"click",rt),V(c,"click",o,this),V(c,"click",this._refocusOnMap,this),c},_updateDisabled:function(){var e=this._map,t="leaflet-disabled";ue(this._zoomInButton,t),ue(this._zoomOutButton,t),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),(this._disabled||e._zoom===e.getMinZoom())&&(G(this._zoomOutButton,t),this._zoomOutButton.setAttribute("aria-disabled","true")),(this._disabled||e._zoom===e.getMaxZoom())&&(G(this._zoomInButton,t),this._zoomInButton.setAttribute("aria-disabled","true"))}});J.mergeOptions({zoomControl:!0}),J.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new Ji,this.addControl(this.zoomControl))});var Ca=function(e){return new Ji(e)},ln=Ae.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(e){var t="leaflet-control-scale",s=te("div",t),r=this.options;return this._addScales(r,t+"-line",s),e.on(r.updateWhenIdle?"moveend":"move",this._update,this),e.whenReady(this._update,this),s},onRemove:function(e){e.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(e,t,s){e.metric&&(this._mScale=te("div",t,s)),e.imperial&&(this._iScale=te("div",t,s))},_update:function(){var e=this._map,t=e.getSize().y/2,s=e.distance(e.containerPointToLatLng([0,t]),e.containerPointToLatLng([this.options.maxWidth,t]));this._updateScales(s)},_updateScales:function(e){this.options.metric&&e&&this._updateMetric(e),this.options.imperial&&e&&this._updateImperial(e)},_updateMetric:function(e){var t=this._getRoundNum(e),s=t<1e3?t+" m":t/1e3+" km";this._updateScale(this._mScale,s,t/e)},_updateImperial:function(e){var t=e*3.2808399,s,r,o;t>5280?(s=t/5280,r=this._getRoundNum(s),this._updateScale(this._iScale,r+" mi",r/s)):(o=this._getRoundNum(t),this._updateScale(this._iScale,o+" ft",o/t))},_updateScale:function(e,t,s){e.style.width=Math.round(this.options.maxWidth*s)+"px",e.innerHTML=t},_getRoundNum:function(e){var t=Math.pow(10,(Math.floor(e)+"").length-1),s=e/t;return s=s>=10?10:s>=5?5:s>=3?3:s>=2?2:1,t*s}}),La=function(e){return new ln(e)},Pa='',Qi=Ae.extend({options:{position:"bottomright",prefix:''+(D.inlineSvg?Pa+" ":"")+"Leaflet"},initialize:function(e){w(this,e),this._attributions={}},onAdd:function(e){e.attributionControl=this,this._container=te("div","leaflet-control-attribution"),Rt(this._container);for(var t in e._layers)e._layers[t].getAttribution&&this.addAttribution(e._layers[t].getAttribution());return this._update(),e.on("layeradd",this._addAttribution,this),this._container},onRemove:function(e){e.off("layeradd",this._addAttribution,this)},_addAttribution:function(e){e.layer.getAttribution&&(this.addAttribution(e.layer.getAttribution()),e.layer.once("remove",function(){this.removeAttribution(e.layer.getAttribution())},this))},setPrefix:function(e){return this.options.prefix=e,this._update(),this},addAttribution:function(e){return e?(this._attributions[e]||(this._attributions[e]=0),this._attributions[e]++,this._update(),this):this},removeAttribution:function(e){return e?(this._attributions[e]&&(this._attributions[e]--,this._update()),this):this},_update:function(){if(this._map){var e=[];for(var t in this._attributions)this._attributions[t]&&e.push(t);var s=[];this.options.prefix&&s.push(this.options.prefix),e.length&&s.push(e.join(", ")),this._container.innerHTML=s.join(' ')}}});J.mergeOptions({attributionControl:!0}),J.addInitHook(function(){this.options.attributionControl&&new Qi().addTo(this)});var Sa=function(e){return new Qi(e)};Ae.Layers=on,Ae.Zoom=Ji,Ae.Scale=ln,Ae.Attribution=Qi,Bt.layers=Na,Bt.zoom=Ca,Bt.scale=La,Bt.attribution=Sa;var Be=B.extend({initialize:function(e){this._map=e},enable:function(){return this._enabled?this:(this._enabled=!0,this.addHooks(),this)},disable:function(){return this._enabled?(this._enabled=!1,this.removeHooks(),this):this},enabled:function(){return!!this._enabled}});Be.addTo=function(e,t){return e.addHandler(t,this),this};var Ta={Events:X},dn=D.touch?"touchstart mousedown":"mousedown",Ye=re.extend({options:{clickTolerance:3},initialize:function(e,t,s,r){w(this,r),this._element=e,this._dragStartTarget=t||e,this._preventOutline=s},enable:function(){this._enabled||(V(this._dragStartTarget,dn,this._onDown,this),this._enabled=!0)},disable:function(){this._enabled&&(Ye._dragging===this&&this.finishDrag(!0),oe(this._dragStartTarget,dn,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(e){if(this._enabled&&(this._moved=!1,!Ri(this._element,"leaflet-zoom-anim"))){if(e.touches&&e.touches.length!==1){Ye._dragging===this&&this.finishDrag();return}if(!(Ye._dragging||e.shiftKey||e.which!==1&&e.button!==1&&!e.touches)&&(Ye._dragging=this,this._preventOutline&&Wi(this._element),Zi(),It(),!this._moving)){this.fire("down");var t=e.touches?e.touches[0]:e,s=en(this._element);this._startPoint=new A(t.clientX,t.clientY),this._startPos=st(this._element),this._parentScale=Vi(s);var r=e.type==="mousedown";V(document,r?"mousemove":"touchmove",this._onMove,this),V(document,r?"mouseup":"touchend touchcancel",this._onUp,this)}}},_onMove:function(e){if(this._enabled){if(e.touches&&e.touches.length>1){this._moved=!0;return}var t=e.touches&&e.touches.length===1?e.touches[0]:e,s=new A(t.clientX,t.clientY)._subtract(this._startPoint);!s.x&&!s.y||Math.abs(s.x)+Math.abs(s.y)c&&(f=x,c=y);c>s&&(t[f]=1,es(e,t,s,r,f),es(e,t,s,f,o))}function za(e,t){for(var s=[e[0]],r=1,o=0,c=e.length;rt&&(s.push(e[r]),o=r);return ot.max.x&&(s|=2),e.yt.max.y&&(s|=8),s}function Ia(e,t){var s=t.x-e.x,r=t.y-e.y;return s*s+r*r}function Ft(e,t,s,r){var o=t.x,c=t.y,f=s.x-o,x=s.y-c,y=f*f+x*x,P;return y>0&&(P=((e.x-o)*f+(e.y-c)*x)/y,P>1?(o=s.x,c=s.y):P>0&&(o+=f*P,c+=x*P)),f=e.x-o,x=e.y-c,r?f*f+x*x:new A(o,c)}function Ee(e){return!O(e[0])||typeof e[0][0]!="object"&&typeof e[0][0]<"u"}function pn(e){return console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead."),Ee(e)}function xn(e,t){var s,r,o,c,f,x,y,P;if(!e||e.length===0)throw new Error("latlngs not passed");Ee(e)||(console.warn("latlngs are not flat! Only the first ring will be used"),e=e[0]);var M=$([0,0]),Z=U(e),Y=Z.getNorthWest().distanceTo(Z.getSouthWest())*Z.getNorthEast().distanceTo(Z.getNorthWest());Y<1700&&(M=Xi(e));var we=e.length,_e=[];for(s=0;sr){y=(c-r)/o,P=[x.x-y*(x.x-f.x),x.y-y*(x.y-f.y)];break}var ke=t.unproject(z(P));return $([ke.lat+M.lat,ke.lng+M.lng])}var Oa={__proto__:null,simplify:un,pointToSegmentDistance:mn,closestPointOnSegment:Ma,clipSegment:gn,_getEdgeIntersection:ci,_getBitCode:at,_sqClosestPointOnSegment:Ft,isFlat:Ee,_flat:pn,polylineCenter:xn},ts={project:function(e){return new A(e.lng,e.lat)},unproject:function(e){return new W(e.y,e.x)},bounds:new H([-180,-90],[180,90])},is={R:6378137,R_MINOR:6356752314245179e-9,bounds:new H([-2003750834279e-5,-1549657073972e-5],[2003750834279e-5,1876465623138e-5]),project:function(e){var t=Math.PI/180,s=this.R,r=e.lat*t,o=this.R_MINOR/s,c=Math.sqrt(1-o*o),f=c*Math.sin(r),x=Math.tan(Math.PI/4-r/2)/Math.pow((1-f)/(1+f),c/2);return r=-s*Math.log(Math.max(x,1e-10)),new A(e.lng*t*s,r)},unproject:function(e){for(var t=180/Math.PI,s=this.R,r=this.R_MINOR/s,o=Math.sqrt(1-r*r),c=Math.exp(-e.y/s),f=Math.PI/2-2*Math.atan(c),x=0,y=.1,P;x<15&&Math.abs(y)>1e-7;x++)P=o*Math.sin(f),P=Math.pow((1-P)/(1+P),o/2),y=Math.PI/2-2*Math.atan(c*P)-f,f+=y;return new W(f*t,e.x*t/s)}},Da={__proto__:null,LonLat:ts,Mercator:is,SphericalMercator:St},Ra=h({},ye,{code:"EPSG:3395",projection:is,transformation:(function(){var e=.5/(Math.PI*is.R);return tt(e,.5,-e,.5)})()}),_n=h({},ye,{code:"EPSG:4326",projection:ts,transformation:tt(1/180,1,-1/180,.5)}),Ba=h({},ce,{projection:ts,transformation:tt(1,0,-1,0),scale:function(e){return Math.pow(2,e)},zoom:function(e){return Math.log(e)/Math.LN2},distance:function(e,t){var s=t.lng-e.lng,r=t.lat-e.lat;return Math.sqrt(s*s+r*r)},infinite:!0});ce.Earth=ye,ce.EPSG3395=Ra,ce.EPSG3857=Et,ce.EPSG900913=I,ce.EPSG4326=_n,ce.Simple=Ba;var ze=re.extend({options:{pane:"overlayPane",attribution:null,bubblingMouseEvents:!0},addTo:function(e){return e.addLayer(this),this},remove:function(){return this.removeFrom(this._map||this._mapToAdd)},removeFrom:function(e){return e&&e.removeLayer(this),this},getPane:function(e){return this._map.getPane(e?this.options[e]||e:this.options.pane)},addInteractiveTarget:function(e){return this._map._targets[g(e)]=this,this},removeInteractiveTarget:function(e){return delete this._map._targets[g(e)],this},getAttribution:function(){return this.options.attribution},_layerAdd:function(e){var t=e.target;if(t.hasLayer(this)){if(this._map=t,this._zoomAnimated=t._zoomAnimated,this.getEvents){var s=this.getEvents();t.on(s,this),this.once("remove",function(){t.off(s,this)},this)}this.onAdd(t),this.fire("add"),t.fire("layeradd",{layer:this})}}});J.include({addLayer:function(e){if(!e._layerAdd)throw new Error("The provided object is not a Layer.");var t=g(e);return this._layers[t]?this:(this._layers[t]=e,e._mapToAdd=this,e.beforeAdd&&e.beforeAdd(this),this.whenReady(e._layerAdd,e),this)},removeLayer:function(e){var t=g(e);return this._layers[t]?(this._loaded&&e.onRemove(this),delete this._layers[t],this._loaded&&(this.fire("layerremove",{layer:e}),e.fire("remove")),e._map=e._mapToAdd=null,this):this},hasLayer:function(e){return g(e)in this._layers},eachLayer:function(e,t){for(var s in this._layers)e.call(t,this._layers[s]);return this},_addLayers:function(e){e=e?O(e)?e:[e]:[];for(var t=0,s=e.length;tthis._layersMaxZoom&&this.setZoom(this._layersMaxZoom),this.options.minZoom===void 0&&this._layersMinZoom&&this.getZoom()=2&&t[0]instanceof W&&t[0].equals(t[s-1])&&t.pop(),t},_setLatLngs:function(e){He.prototype._setLatLngs.call(this,e),Ee(this._latlngs)&&(this._latlngs=[this._latlngs])},_defaultShape:function(){return Ee(this._latlngs[0])?this._latlngs[0]:this._latlngs[0][0]},_clipPoints:function(){var e=this._renderer._bounds,t=this.options.weight,s=new A(t,t);if(e=new H(e.min.subtract(s),e.max.add(s)),this._parts=[],!(!this._pxBounds||!this._pxBounds.intersects(e))){if(this.options.noClip){this._parts=this._rings;return}for(var r=0,o=this._rings.length,c;re.y!=o.y>e.y&&e.x<(o.x-r.x)*(e.y-r.y)/(o.y-r.y)+r.x&&(t=!t);return t||He.prototype._containsPoint.call(this,e,!0)}});function Ua(e,t){return new _t(e,t)}var We=$e.extend({initialize:function(e,t){w(this,t),this._layers={},e&&this.addData(e)},addData:function(e){var t=O(e)?e:e.features,s,r,o;if(t){for(s=0,r=t.length;s0&&o.push(o[0].slice()),o}function yt(e,t){return e.feature?h({},e.feature,{geometry:t}):pi(t)}function pi(e){return e.type==="Feature"||e.type==="FeatureCollection"?e:{type:"Feature",properties:{},geometry:e}}var as={toGeoJSON:function(e){return yt(this,{type:"Point",coordinates:rs(this.getLatLng(),e)})}};hi.include(as),ss.include(as),ui.include(as),He.include({toGeoJSON:function(e){var t=!Ee(this._latlngs),s=gi(this._latlngs,t?1:0,!1,e);return yt(this,{type:(t?"Multi":"")+"LineString",coordinates:s})}}),_t.include({toGeoJSON:function(e){var t=!Ee(this._latlngs),s=t&&!Ee(this._latlngs[0]),r=gi(this._latlngs,s?2:t?1:0,!0,e);return t||(r=[r]),yt(this,{type:(s?"Multi":"")+"Polygon",coordinates:r})}}),pt.include({toMultiPoint:function(e){var t=[];return this.eachLayer(function(s){t.push(s.toGeoJSON(e).geometry.coordinates)}),yt(this,{type:"MultiPoint",coordinates:t})},toGeoJSON:function(e){var t=this.feature&&this.feature.geometry&&this.feature.geometry.type;if(t==="MultiPoint")return this.toMultiPoint(e);var s=t==="GeometryCollection",r=[];return this.eachLayer(function(o){if(o.toGeoJSON){var c=o.toGeoJSON(e);if(s)r.push(c.geometry);else{var f=pi(c);f.type==="FeatureCollection"?r.push.apply(r,f.features):r.push(f)}}}),s?yt(this,{geometries:r,type:"GeometryCollection"}):{type:"FeatureCollection",features:r}}});function bn(e,t){return new We(e,t)}var Ga=bn,xi=ze.extend({options:{opacity:1,alt:"",interactive:!1,crossOrigin:!1,errorOverlayUrl:"",zIndex:1,className:""},initialize:function(e,t,s){this._url=e,this._bounds=U(t),w(this,s)},onAdd:function(){this._image||(this._initImage(),this.options.opacity<1&&this._updateOpacity()),this.options.interactive&&(G(this._image,"leaflet-interactive"),this.addInteractiveTarget(this._image)),this.getPane().appendChild(this._image),this._reset()},onRemove:function(){de(this._image),this.options.interactive&&this.removeInteractiveTarget(this._image)},setOpacity:function(e){return this.options.opacity=e,this._image&&this._updateOpacity(),this},setStyle:function(e){return e.opacity&&this.setOpacity(e.opacity),this},bringToFront:function(){return this._map&&ft(this._image),this},bringToBack:function(){return this._map&>(this._image),this},setUrl:function(e){return this._url=e,this._image&&(this._image.src=e),this},setBounds:function(e){return this._bounds=U(e),this._map&&this._reset(),this},getEvents:function(){var e={zoom:this._reset,viewreset:this._reset};return this._zoomAnimated&&(e.zoomanim=this._animateZoom),e},setZIndex:function(e){return this.options.zIndex=e,this._updateZIndex(),this},getBounds:function(){return this._bounds},getElement:function(){return this._image},_initImage:function(){var e=this._url.tagName==="IMG",t=this._image=e?this._url:te("img");if(G(t,"leaflet-image-layer"),this._zoomAnimated&&G(t,"leaflet-zoom-animated"),this.options.className&&G(t,this.options.className),t.onselectstart=v,t.onmousemove=v,t.onload=m(this.fire,this,"load"),t.onerror=m(this._overlayOnError,this,"error"),(this.options.crossOrigin||this.options.crossOrigin==="")&&(t.crossOrigin=this.options.crossOrigin===!0?"":this.options.crossOrigin),this.options.zIndex&&this._updateZIndex(),e){this._url=t.src;return}t.src=this._url,t.alt=this.options.alt},_animateZoom:function(e){var t=this._map.getZoomScale(e.zoom),s=this._map._latLngBoundsToNewLayerBounds(this._bounds,e.zoom,e.center).min;it(this._image,s,t)},_reset:function(){var e=this._image,t=new H(this._map.latLngToLayerPoint(this._bounds.getNorthWest()),this._map.latLngToLayerPoint(this._bounds.getSouthEast())),s=t.getSize();me(e,t.min),e.style.width=s.x+"px",e.style.height=s.y+"px"},_updateOpacity:function(){Te(this._image,this.options.opacity)},_updateZIndex:function(){this._image&&this.options.zIndex!==void 0&&this.options.zIndex!==null&&(this._image.style.zIndex=this.options.zIndex)},_overlayOnError:function(){this.fire("error");var e=this.options.errorOverlayUrl;e&&this._url!==e&&(this._url=e,this._image.src=e)},getCenter:function(){return this._bounds.getCenter()}}),Ka=function(e,t,s){return new xi(e,t,s)},wn=xi.extend({options:{autoplay:!0,loop:!0,keepAspectRatio:!0,muted:!1,playsInline:!0},_initImage:function(){var e=this._url.tagName==="VIDEO",t=this._image=e?this._url:te("video");if(G(t,"leaflet-image-layer"),this._zoomAnimated&&G(t,"leaflet-zoom-animated"),this.options.className&&G(t,this.options.className),t.onselectstart=v,t.onmousemove=v,t.onloadeddata=m(this.fire,this,"load"),e){for(var s=t.getElementsByTagName("source"),r=[],o=0;o0?r:[t.src];return}O(this._url)||(this._url=[this._url]),!this.options.keepAspectRatio&&Object.prototype.hasOwnProperty.call(t.style,"objectFit")&&(t.style.objectFit="fill"),t.autoplay=!!this.options.autoplay,t.loop=!!this.options.loop,t.muted=!!this.options.muted,t.playsInline=!!this.options.playsInline;for(var c=0;co?(t.height=o+"px",G(e,c)):ue(e,c),this._containerWidth=this._container.offsetWidth},_animateZoom:function(e){var t=this._map._latLngToNewLayerPoint(this._latlng,e.zoom,e.center),s=this._getAnchor();me(this._container,t.add(s))},_adjustPan:function(){if(this.options.autoPan){if(this._map._panAnim&&this._map._panAnim.stop(),this._autopanning){this._autopanning=!1;return}var e=this._map,t=parseInt(zt(this._container,"marginBottom"),10)||0,s=this._container.offsetHeight+t,r=this._containerWidth,o=new A(this._containerLeft,-s-this._containerBottom);o._add(st(this._container));var c=e.layerPointToContainerPoint(o),f=z(this.options.autoPanPadding),x=z(this.options.autoPanPaddingTopLeft||f),y=z(this.options.autoPanPaddingBottomRight||f),P=e.getSize(),M=0,Z=0;c.x+r+y.x>P.x&&(M=c.x+r-P.x+y.x),c.x-M-x.x<0&&(M=c.x-x.x),c.y+s+y.y>P.y&&(Z=c.y+s-P.y+y.y),c.y-Z-x.y<0&&(Z=c.y-x.y),(M||Z)&&(this.options.keepInView&&(this._autopanning=!0),e.fire("autopanstart").panBy([M,Z]))}},_getAnchor:function(){return z(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}}),Qa=function(e,t){return new _i(e,t)};J.mergeOptions({closePopupOnClick:!0}),J.include({openPopup:function(e,t,s){return this._initOverlay(_i,e,t,s).openOn(this),this},closePopup:function(e){return e=arguments.length?e:this._popup,e&&e.close(),this}}),ze.include({bindPopup:function(e,t){return this._popup=this._initOverlay(_i,this._popup,e,t),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(e){return this._popup&&(this instanceof $e||(this._popup._source=this),this._popup._prepareOpen(e||this._latlng)&&this._popup.openOn(this._map)),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return this._popup?this._popup.isOpen():!1},setPopupContent:function(e){return this._popup&&this._popup.setContent(e),this},getPopup:function(){return this._popup},_openPopup:function(e){if(!(!this._popup||!this._map)){rt(e);var t=e.layer||e.target;if(this._popup._source===t&&!(t instanceof Je)){this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(e.latlng);return}this._popup._source=t,this.openPopup(e.latlng)}},_movePopup:function(e){this._popup.setLatLng(e.latlng)},_onKeyPress:function(e){e.originalEvent.keyCode===13&&this._openPopup(e)}});var yi=Fe.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(e){Fe.prototype.onAdd.call(this,e),this.setOpacity(this.options.opacity),e.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(e){Fe.prototype.onRemove.call(this,e),e.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var e=Fe.prototype.getEvents.call(this);return this.options.permanent||(e.preclick=this.close),e},_initLayout:function(){var e="leaflet-tooltip",t=e+" "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=te("div",t),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+g(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(e){var t,s,r=this._map,o=this._container,c=r.latLngToContainerPoint(r.getCenter()),f=r.layerPointToContainerPoint(e),x=this.options.direction,y=o.offsetWidth,P=o.offsetHeight,M=z(this.options.offset),Z=this._getAnchor();x==="top"?(t=y/2,s=P):x==="bottom"?(t=y/2,s=0):x==="center"?(t=y/2,s=P/2):x==="right"?(t=0,s=P/2):x==="left"?(t=y,s=P/2):f.xthis.options.maxZoom||sr?this._retainParent(o,c,f,r):!1)},_retainChildren:function(e,t,s,r){for(var o=2*e;o<2*e+2;o++)for(var c=2*t;c<2*t+2;c++){var f=new A(o,c);f.z=s+1;var x=this._tileCoordsToKey(f),y=this._tiles[x];if(y&&y.active){y.retain=!0;continue}else y&&y.loaded&&(y.retain=!0);s+1this.options.maxZoom||this.options.minZoom!==void 0&&o1){this._setView(e,s);return}for(var Z=o.min.y;Z<=o.max.y;Z++)for(var Y=o.min.x;Y<=o.max.x;Y++){var we=new A(Y,Z);if(we.z=this._tileZoom,!!this._isValidTile(we)){var _e=this._tiles[this._tileCoordsToKey(we)];_e?_e.current=!0:f.push(we)}}if(f.sort(function(ke,bt){return ke.distanceTo(c)-bt.distanceTo(c)}),f.length!==0){this._loading||(this._loading=!0,this.fire("loading"));var Me=document.createDocumentFragment();for(Y=0;Ys.max.x)||!t.wrapLat&&(e.ys.max.y))return!1}if(!this.options.bounds)return!0;var r=this._tileCoordsToBounds(e);return U(this.options.bounds).overlaps(r)},_keyToBounds:function(e){return this._tileCoordsToBounds(this._keyToTileCoords(e))},_tileCoordsToNwSe:function(e){var t=this._map,s=this.getTileSize(),r=e.scaleBy(s),o=r.add(s),c=t.unproject(r,e.z),f=t.unproject(o,e.z);return[c,f]},_tileCoordsToBounds:function(e){var t=this._tileCoordsToNwSe(e),s=new ne(t[0],t[1]);return this.options.noWrap||(s=this._map.wrapLatLngBounds(s)),s},_tileCoordsToKey:function(e){return e.x+":"+e.y+":"+e.z},_keyToTileCoords:function(e){var t=e.split(":"),s=new A(+t[0],+t[1]);return s.z=+t[2],s},_removeTile:function(e){var t=this._tiles[e];t&&(de(t.el),delete this._tiles[e],this.fire("tileunload",{tile:t.el,coords:this._keyToTileCoords(e)}))},_initTile:function(e){G(e,"leaflet-tile");var t=this.getTileSize();e.style.width=t.x+"px",e.style.height=t.y+"px",e.onselectstart=v,e.onmousemove=v,D.ielt9&&this.options.opacity<1&&Te(e,this.options.opacity)},_addTile:function(e,t){var s=this._getTilePos(e),r=this._tileCoordsToKey(e),o=this.createTile(this._wrapCoords(e),m(this._tileReady,this,e));this._initTile(o),this.createTile.length<2&&q(m(this._tileReady,this,e,null,o)),me(o,s),this._tiles[r]={el:o,coords:e,current:!0},t.appendChild(o),this.fire("tileloadstart",{tile:o,coords:e})},_tileReady:function(e,t,s){t&&this.fire("tileerror",{error:t,tile:s,coords:e});var r=this._tileCoordsToKey(e);s=this._tiles[r],s&&(s.loaded=+new Date,this._map._fadeAnimated?(Te(s.el,0),ee(this._fadeFrame),this._fadeFrame=q(this._updateOpacity,this)):(s.active=!0,this._pruneTiles()),t||(G(s.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:s.el,coords:e})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),D.ielt9||!this._map._fadeAnimated?q(this._pruneTiles,this):setTimeout(m(this._pruneTiles,this),250)))},_getTilePos:function(e){return e.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(e){var t=new A(this._wrapX?_(e.x,this._wrapX):e.x,this._wrapY?_(e.y,this._wrapY):e.y);return t.z=e.z,t},_pxBoundsToTileRange:function(e){var t=this.getTileSize();return new H(e.min.unscaleBy(t).floor(),e.max.unscaleBy(t).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var e in this._tiles)if(!this._tiles[e].loaded)return!1;return!0}});function to(e){return new $t(e)}var vt=$t.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(e,t){this._url=e,t=w(this,t),t.detectRetina&&D.retina&&t.maxZoom>0?(t.tileSize=Math.floor(t.tileSize/2),t.zoomReverse?(t.zoomOffset--,t.minZoom=Math.min(t.maxZoom,t.minZoom+1)):(t.zoomOffset++,t.maxZoom=Math.max(t.minZoom,t.maxZoom-1)),t.minZoom=Math.max(0,t.minZoom)):t.zoomReverse?t.minZoom=Math.min(t.maxZoom,t.minZoom):t.maxZoom=Math.max(t.minZoom,t.maxZoom),typeof t.subdomains=="string"&&(t.subdomains=t.subdomains.split("")),this.on("tileunload",this._onTileRemove)},setUrl:function(e,t){return this._url===e&&t===void 0&&(t=!0),this._url=e,t||this.redraw(),this},createTile:function(e,t){var s=document.createElement("img");return V(s,"load",m(this._tileOnLoad,this,t,s)),V(s,"error",m(this._tileOnError,this,t,s)),(this.options.crossOrigin||this.options.crossOrigin==="")&&(s.crossOrigin=this.options.crossOrigin===!0?"":this.options.crossOrigin),typeof this.options.referrerPolicy=="string"&&(s.referrerPolicy=this.options.referrerPolicy),s.alt="",s.src=this.getTileUrl(e),s},getTileUrl:function(e){var t={r:D.retina?"@2x":"",s:this._getSubdomain(e),x:e.x,y:e.y,z:this._getZoomForUrl()};if(this._map&&!this._map.options.crs.infinite){var s=this._globalTileRange.max.y-e.y;this.options.tms&&(t.y=s),t["-y"]=s}return T(this._url,h(t,this.options))},_tileOnLoad:function(e,t){D.ielt9?setTimeout(m(e,this,null,t),0):e(null,t)},_tileOnError:function(e,t,s){var r=this.options.errorTileUrl;r&&t.getAttribute("src")!==r&&(t.src=r),e(s,t)},_onTileRemove:function(e){e.tile.onload=null},_getZoomForUrl:function(){var e=this._tileZoom,t=this.options.maxZoom,s=this.options.zoomReverse,r=this.options.zoomOffset;return s&&(e=t-e),e+r},_getSubdomain:function(e){var t=Math.abs(e.x+e.y)%this.options.subdomains.length;return this.options.subdomains[t]},_abortLoading:function(){var e,t;for(e in this._tiles)if(this._tiles[e].coords.z!==this._tileZoom&&(t=this._tiles[e].el,t.onload=v,t.onerror=v,!t.complete)){t.src=ge;var s=this._tiles[e].coords;de(t),delete this._tiles[e],this.fire("tileabort",{tile:t,coords:s})}},_removeTile:function(e){var t=this._tiles[e];if(t)return t.el.setAttribute("src",ge),$t.prototype._removeTile.call(this,e)},_tileReady:function(e,t,s){if(!(!this._map||s&&s.getAttribute("src")===ge))return $t.prototype._tileReady.call(this,e,t,s)}});function Nn(e,t){return new vt(e,t)}var Cn=vt.extend({defaultWmsParams:{service:"WMS",request:"GetMap",layers:"",styles:"",format:"image/jpeg",transparent:!1,version:"1.1.1"},options:{crs:null,uppercase:!1},initialize:function(e,t){this._url=e;var s=h({},this.defaultWmsParams);for(var r in t)r in this.options||(s[r]=t[r]);t=w(this,t);var o=t.detectRetina&&D.retina?2:1,c=this.getTileSize();s.width=c.x*o,s.height=c.y*o,this.wmsParams=s},onAdd:function(e){this._crs=this.options.crs||e.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var t=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[t]=this._crs.code,vt.prototype.onAdd.call(this,e)},getTileUrl:function(e){var t=this._tileCoordsToNwSe(e),s=this._crs,r=se(s.project(t[0]),s.project(t[1])),o=r.min,c=r.max,f=(this._wmsVersion>=1.3&&this._crs===_n?[o.y,o.x,c.y,c.x]:[o.x,o.y,c.x,c.y]).join(","),x=vt.prototype.getTileUrl.call(this,e);return x+S(this.wmsParams,x,this.options.uppercase)+(this.options.uppercase?"&BBOX=":"&bbox=")+f},setParams:function(e,t){return h(this.wmsParams,e),t||this.redraw(),this}});function io(e,t){return new Cn(e,t)}vt.WMS=Cn,Nn.wms=io;var Ve=ze.extend({options:{padding:.1},initialize:function(e){w(this,e),g(this),this._layers=this._layers||{}},onAdd:function(){this._container||(this._initContainer(),G(this._container,"leaflet-zoom-animated")),this.getPane().appendChild(this._container),this._update(),this.on("update",this._updatePaths,this)},onRemove:function(){this.off("update",this._updatePaths,this),this._destroyContainer()},getEvents:function(){var e={viewreset:this._reset,zoom:this._onZoom,moveend:this._update,zoomend:this._onZoomEnd};return this._zoomAnimated&&(e.zoomanim=this._onAnimZoom),e},_onAnimZoom:function(e){this._updateTransform(e.center,e.zoom)},_onZoom:function(){this._updateTransform(this._map.getCenter(),this._map.getZoom())},_updateTransform:function(e,t){var s=this._map.getZoomScale(t,this._zoom),r=this._map.getSize().multiplyBy(.5+this.options.padding),o=this._map.project(this._center,t),c=r.multiplyBy(-s).add(o).subtract(this._map._getNewPixelOrigin(e,t));D.any3d?it(this._container,c,s):me(this._container,c)},_reset:function(){this._update(),this._updateTransform(this._center,this._zoom);for(var e in this._layers)this._layers[e]._reset()},_onZoomEnd:function(){for(var e in this._layers)this._layers[e]._project()},_updatePaths:function(){for(var e in this._layers)this._layers[e]._update()},_update:function(){var e=this.options.padding,t=this._map.getSize(),s=this._map.containerPointToLayerPoint(t.multiplyBy(-e)).round();this._bounds=new H(s,s.add(t.multiplyBy(1+e*2)).round()),this._center=this._map.getCenter(),this._zoom=this._map.getZoom()}}),Ln=Ve.extend({options:{tolerance:0},getEvents:function(){var e=Ve.prototype.getEvents.call(this);return e.viewprereset=this._onViewPreReset,e},_onViewPreReset:function(){this._postponeUpdatePaths=!0},onAdd:function(){Ve.prototype.onAdd.call(this),this._draw()},_initContainer:function(){var e=this._container=document.createElement("canvas");V(e,"mousemove",this._onMouseMove,this),V(e,"click dblclick mousedown mouseup contextmenu",this._onClick,this),V(e,"mouseout",this._handleMouseOut,this),e._leaflet_disable_events=!0,this._ctx=e.getContext("2d")},_destroyContainer:function(){ee(this._redrawRequest),delete this._ctx,de(this._container),oe(this._container),delete this._container},_updatePaths:function(){if(!this._postponeUpdatePaths){var e;this._redrawBounds=null;for(var t in this._layers)e=this._layers[t],e._update();this._redraw()}},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){Ve.prototype._update.call(this);var e=this._bounds,t=this._container,s=e.getSize(),r=D.retina?2:1;me(t,e.min),t.width=r*s.x,t.height=r*s.y,t.style.width=s.x+"px",t.style.height=s.y+"px",D.retina&&this._ctx.scale(2,2),this._ctx.translate(-e.min.x,-e.min.y),this.fire("update")}},_reset:function(){Ve.prototype._reset.call(this),this._postponeUpdatePaths&&(this._postponeUpdatePaths=!1,this._updatePaths())},_initPath:function(e){this._updateDashArray(e),this._layers[g(e)]=e;var t=e._order={layer:e,prev:this._drawLast,next:null};this._drawLast&&(this._drawLast.next=t),this._drawLast=t,this._drawFirst=this._drawFirst||this._drawLast},_addPath:function(e){this._requestRedraw(e)},_removePath:function(e){var t=e._order,s=t.next,r=t.prev;s?s.prev=r:this._drawLast=r,r?r.next=s:this._drawFirst=s,delete e._order,delete this._layers[g(e)],this._requestRedraw(e)},_updatePath:function(e){this._extendRedrawBounds(e),e._project(),e._update(),this._requestRedraw(e)},_updateStyle:function(e){this._updateDashArray(e),this._requestRedraw(e)},_updateDashArray:function(e){if(typeof e.options.dashArray=="string"){var t=e.options.dashArray.split(/[, ]+/),s=[],r,o;for(o=0;o')}}catch{}return function(e){return document.createElement("<"+e+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}})(),so={_initContainer:function(){this._container=te("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(Ve.prototype._update.call(this),this.fire("update"))},_initPath:function(e){var t=e._container=Ht("shape");G(t,"leaflet-vml-shape "+(this.options.className||"")),t.coordsize="1 1",e._path=Ht("path"),t.appendChild(e._path),this._updateStyle(e),this._layers[g(e)]=e},_addPath:function(e){var t=e._container;this._container.appendChild(t),e.options.interactive&&e.addInteractiveTarget(t)},_removePath:function(e){var t=e._container;de(t),e.removeInteractiveTarget(t),delete this._layers[g(e)]},_updateStyle:function(e){var t=e._stroke,s=e._fill,r=e.options,o=e._container;o.stroked=!!r.stroke,o.filled=!!r.fill,r.stroke?(t||(t=e._stroke=Ht("stroke")),o.appendChild(t),t.weight=r.weight+"px",t.color=r.color,t.opacity=r.opacity,r.dashArray?t.dashStyle=O(r.dashArray)?r.dashArray.join(" "):r.dashArray.replace(/( *, *)/g," "):t.dashStyle="",t.endcap=r.lineCap.replace("butt","flat"),t.joinstyle=r.lineJoin):t&&(o.removeChild(t),e._stroke=null),r.fill?(s||(s=e._fill=Ht("fill")),o.appendChild(s),s.color=r.fillColor||r.color,s.opacity=r.fillOpacity):s&&(o.removeChild(s),e._fill=null)},_updateCircle:function(e){var t=e._point.round(),s=Math.round(e._radius),r=Math.round(e._radiusY||s);this._setPath(e,e._empty()?"M0 0":"AL "+t.x+","+t.y+" "+s+","+r+" 0,"+65535*360)},_setPath:function(e,t){e._path.v=t},_bringToFront:function(e){ft(e._container)},_bringToBack:function(e){gt(e._container)}},vi=D.vml?Ht:he,Wt=Ve.extend({_initContainer:function(){this._container=vi("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=vi("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){de(this._container),oe(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){Ve.prototype._update.call(this);var e=this._bounds,t=e.getSize(),s=this._container;(!this._svgSize||!this._svgSize.equals(t))&&(this._svgSize=t,s.setAttribute("width",t.x),s.setAttribute("height",t.y)),me(s,e.min),s.setAttribute("viewBox",[e.min.x,e.min.y,t.x,t.y].join(" ")),this.fire("update")}},_initPath:function(e){var t=e._path=vi("path");e.options.className&&G(t,e.options.className),e.options.interactive&&G(t,"leaflet-interactive"),this._updateStyle(e),this._layers[g(e)]=e},_addPath:function(e){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(e._path),e.addInteractiveTarget(e._path)},_removePath:function(e){de(e._path),e.removeInteractiveTarget(e._path),delete this._layers[g(e)]},_updatePath:function(e){e._project(),e._update()},_updateStyle:function(e){var t=e._path,s=e.options;t&&(s.stroke?(t.setAttribute("stroke",s.color),t.setAttribute("stroke-opacity",s.opacity),t.setAttribute("stroke-width",s.weight),t.setAttribute("stroke-linecap",s.lineCap),t.setAttribute("stroke-linejoin",s.lineJoin),s.dashArray?t.setAttribute("stroke-dasharray",s.dashArray):t.removeAttribute("stroke-dasharray"),s.dashOffset?t.setAttribute("stroke-dashoffset",s.dashOffset):t.removeAttribute("stroke-dashoffset")):t.setAttribute("stroke","none"),s.fill?(t.setAttribute("fill",s.fillColor||s.color),t.setAttribute("fill-opacity",s.fillOpacity),t.setAttribute("fill-rule",s.fillRule||"evenodd")):t.setAttribute("fill","none"))},_updatePoly:function(e,t){this._setPath(e,Se(e._parts,t))},_updateCircle:function(e){var t=e._point,s=Math.max(Math.round(e._radius),1),r=Math.max(Math.round(e._radiusY),1)||s,o="a"+s+","+r+" 0 1,0 ",c=e._empty()?"M0 0":"M"+(t.x-s)+","+t.y+o+s*2+",0 "+o+-s*2+",0 ";this._setPath(e,c)},_setPath:function(e,t){e._path.setAttribute("d",t)},_bringToFront:function(e){ft(e._path)},_bringToBack:function(e){gt(e._path)}});D.vml&&Wt.include(so);function Sn(e){return D.svg||D.vml?new Wt(e):null}J.include({getRenderer:function(e){var t=e.options.renderer||this._getPaneRenderer(e.options.pane)||this.options.renderer||this._renderer;return t||(t=this._renderer=this._createRenderer()),this.hasLayer(t)||this.addLayer(t),t},_getPaneRenderer:function(e){if(e==="overlayPane"||e===void 0)return!1;var t=this._paneRenderers[e];return t===void 0&&(t=this._createRenderer({pane:e}),this._paneRenderers[e]=t),t},_createRenderer:function(e){return this.options.preferCanvas&&Pn(e)||Sn(e)}});var Tn=_t.extend({initialize:function(e,t){_t.prototype.initialize.call(this,this._boundsToLatLngs(e),t)},setBounds:function(e){return this.setLatLngs(this._boundsToLatLngs(e))},_boundsToLatLngs:function(e){return e=U(e),[e.getSouthWest(),e.getNorthWest(),e.getNorthEast(),e.getSouthEast()]}});function no(e,t){return new Tn(e,t)}Wt.create=vi,Wt.pointsToPath=Se,We.geometryToLayer=mi,We.coordsToLatLng=ns,We.coordsToLatLngs=fi,We.latLngToCoords=rs,We.latLngsToCoords=gi,We.getFeature=yt,We.asFeature=pi,J.mergeOptions({boxZoom:!0});var En=Be.extend({initialize:function(e){this._map=e,this._container=e._container,this._pane=e._panes.overlayPane,this._resetStateTimeout=0,e.on("unload",this._destroy,this)},addHooks:function(){V(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){oe(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){de(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){this._resetStateTimeout!==0&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(e){if(!e.shiftKey||e.which!==1&&e.button!==1)return!1;this._clearDeferredResetState(),this._resetState(),It(),Zi(),this._startPoint=this._map.mouseEventToContainerPoint(e),V(document,{contextmenu:rt,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(e){this._moved||(this._moved=!0,this._box=te("div","leaflet-zoom-box",this._container),G(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(e);var t=new H(this._point,this._startPoint),s=t.getSize();me(this._box,t.min),this._box.style.width=s.x+"px",this._box.style.height=s.y+"px"},_finish:function(){this._moved&&(de(this._box),ue(this._container,"leaflet-crosshair")),Ot(),$i(),oe(document,{contextmenu:rt,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(e){if(!(e.which!==1&&e.button!==1)&&(this._finish(),!!this._moved)){this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(m(this._resetState,this),0);var t=new ne(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point));this._map.fitBounds(t).fire("boxzoomend",{boxZoomBounds:t})}},_onKeyDown:function(e){e.keyCode===27&&(this._finish(),this._clearDeferredResetState(),this._resetState())}});J.addInitHook("addHandler","boxZoom",En),J.mergeOptions({doubleClickZoom:!0});var Mn=Be.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(e){var t=this._map,s=t.getZoom(),r=t.options.zoomDelta,o=e.originalEvent.shiftKey?s-r:s+r;t.options.doubleClickZoom==="center"?t.setZoom(o):t.setZoomAround(e.containerPoint,o)}});J.addInitHook("addHandler","doubleClickZoom",Mn),J.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0});var An=Be.extend({addHooks:function(){if(!this._draggable){var e=this._map;this._draggable=new Ye(e._mapPane,e._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),e.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),e.on("zoomend",this._onZoomEnd,this),e.whenReady(this._onZoomEnd,this))}G(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){ue(this._map._container,"leaflet-grab"),ue(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var e=this._map;if(e._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity){var t=U(this._map.options.maxBounds);this._offsetLimit=se(this._map.latLngToContainerPoint(t.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(t.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))}else this._offsetLimit=null;e.fire("movestart").fire("dragstart"),e.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(e){if(this._map.options.inertia){var t=this._lastTime=+new Date,s=this._lastPos=this._draggable._absPos||this._draggable._newPos;this._positions.push(s),this._times.push(t),this._prunePositions(t)}this._map.fire("move",e).fire("drag",e)},_prunePositions:function(e){for(;this._positions.length>1&&e-this._times[0]>50;)this._positions.shift(),this._times.shift()},_onZoomEnd:function(){var e=this._map.getSize().divideBy(2),t=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=t.subtract(e).x,this._worldWidth=this._map.getPixelWorldBounds().getSize().x},_viscousLimit:function(e,t){return e-(e-t)*this._viscosity},_onPreDragLimit:function(){if(!(!this._viscosity||!this._offsetLimit)){var e=this._draggable._newPos.subtract(this._draggable._startPos),t=this._offsetLimit;e.xt.max.x&&(e.x=this._viscousLimit(e.x,t.max.x)),e.y>t.max.y&&(e.y=this._viscousLimit(e.y,t.max.y)),this._draggable._newPos=this._draggable._startPos.add(e)}},_onPreDragWrap:function(){var e=this._worldWidth,t=Math.round(e/2),s=this._initialWorldOffset,r=this._draggable._newPos.x,o=(r-t+s)%e+t-s,c=(r+t+s)%e-t-s,f=Math.abs(o+s)0?c:-c))-t;this._delta=0,this._startTime=null,f&&(e.options.scrollWheelZoom==="center"?e.setZoom(t+f):e.setZoomAround(this._lastMousePos,t+f))}});J.addInitHook("addHandler","scrollWheelZoom",In);var ro=600;J.mergeOptions({tapHold:D.touchNative&&D.safari&&D.mobile,tapTolerance:15});var On=Be.extend({addHooks:function(){V(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){oe(this._map._container,"touchstart",this._onDown,this)},_onDown:function(e){if(clearTimeout(this._holdTimeout),e.touches.length===1){var t=e.touches[0];this._startPos=this._newPos=new A(t.clientX,t.clientY),this._holdTimeout=setTimeout(m(function(){this._cancel(),this._isTapValid()&&(V(document,"touchend",ve),V(document,"touchend touchcancel",this._cancelClickPrevent),this._simulateEvent("contextmenu",t))},this),ro),V(document,"touchend touchcancel contextmenu",this._cancel,this),V(document,"touchmove",this._onMove,this)}},_cancelClickPrevent:function e(){oe(document,"touchend",ve),oe(document,"touchend touchcancel",e)},_cancel:function(){clearTimeout(this._holdTimeout),oe(document,"touchend touchcancel contextmenu",this._cancel,this),oe(document,"touchmove",this._onMove,this)},_onMove:function(e){var t=e.touches[0];this._newPos=new A(t.clientX,t.clientY)},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_simulateEvent:function(e,t){var s=new MouseEvent(e,{bubbles:!0,cancelable:!0,view:window,screenX:t.screenX,screenY:t.screenY,clientX:t.clientX,clientY:t.clientY});s._simulated=!0,t.target.dispatchEvent(s)}});J.addInitHook("addHandler","tapHold",On),J.mergeOptions({touchZoom:D.touch,bounceAtZoomLimits:!0});var Dn=Be.extend({addHooks:function(){G(this._map._container,"leaflet-touch-zoom"),V(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){ue(this._map._container,"leaflet-touch-zoom"),oe(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(e){var t=this._map;if(!(!e.touches||e.touches.length!==2||t._animatingZoom||this._zooming)){var s=t.mouseEventToContainerPoint(e.touches[0]),r=t.mouseEventToContainerPoint(e.touches[1]);this._centerPoint=t.getSize()._divideBy(2),this._startLatLng=t.containerPointToLatLng(this._centerPoint),t.options.touchZoom!=="center"&&(this._pinchStartLatLng=t.containerPointToLatLng(s.add(r)._divideBy(2))),this._startDist=s.distanceTo(r),this._startZoom=t.getZoom(),this._moved=!1,this._zooming=!0,t._stop(),V(document,"touchmove",this._onTouchMove,this),V(document,"touchend touchcancel",this._onTouchEnd,this),ve(e)}},_onTouchMove:function(e){if(!(!e.touches||e.touches.length!==2||!this._zooming)){var t=this._map,s=t.mouseEventToContainerPoint(e.touches[0]),r=t.mouseEventToContainerPoint(e.touches[1]),o=s.distanceTo(r)/this._startDist;if(this._zoom=t.getScaleZoom(o,this._startZoom),!t.options.bounceAtZoomLimits&&(this._zoomt.getMaxZoom()&&o>1)&&(this._zoom=t._limitZoom(this._zoom)),t.options.touchZoom==="center"){if(this._center=this._startLatLng,o===1)return}else{var c=s._add(r)._divideBy(2)._subtract(this._centerPoint);if(o===1&&c.x===0&&c.y===0)return;this._center=t.unproject(t.project(this._pinchStartLatLng,this._zoom).subtract(c),this._zoom)}this._moved||(t._moveStart(!0,!1),this._moved=!0),ee(this._animRequest);var f=m(t._move,t,this._center,this._zoom,{pinch:!0,round:!1},void 0);this._animRequest=q(f,this,!0),ve(e)}},_onTouchEnd:function(){if(!this._moved||!this._zooming){this._zooming=!1;return}this._zooming=!1,ee(this._animRequest),oe(document,"touchmove",this._onTouchMove,this),oe(document,"touchend touchcancel",this._onTouchEnd,this),this._map.options.zoomAnimation?this._map._animateZoom(this._center,this._map._limitZoom(this._zoom),!0,this._map.options.zoomSnap):this._map._resetView(this._center,this._map._limitZoom(this._zoom))}});J.addInitHook("addHandler","touchZoom",Dn),J.BoxZoom=En,J.DoubleClickZoom=Mn,J.Drag=An,J.Keyboard=zn,J.ScrollWheelZoom=In,J.TapHold=On,J.TouchZoom=Dn,a.Bounds=H,a.Browser=D,a.CRS=ce,a.Canvas=Ln,a.Circle=ss,a.CircleMarker=ui,a.Class=B,a.Control=Ae,a.DivIcon=kn,a.DivOverlay=Fe,a.DomEvent=ja,a.DomUtil=ba,a.Draggable=Ye,a.Evented=re,a.FeatureGroup=$e,a.GeoJSON=We,a.GridLayer=$t,a.Handler=Be,a.Icon=xt,a.ImageOverlay=xi,a.LatLng=W,a.LatLngBounds=ne,a.Layer=ze,a.LayerGroup=pt,a.LineUtil=Oa,a.Map=J,a.Marker=hi,a.Mixin=Ta,a.Path=Je,a.Point=A,a.PolyUtil=Ea,a.Polygon=_t,a.Polyline=He,a.Popup=_i,a.PosAnimation=an,a.Projection=Da,a.Rectangle=Tn,a.Renderer=Ve,a.SVG=Wt,a.SVGOverlay=jn,a.TileLayer=vt,a.Tooltip=yi,a.Transformation=Tt,a.Util=R,a.VideoOverlay=wn,a.bind=m,a.bounds=se,a.canvas=Pn,a.circle=Va,a.circleMarker=Wa,a.control=Bt,a.divIcon=eo,a.extend=h,a.featureGroup=Za,a.geoJSON=bn,a.geoJson=Ga,a.gridLayer=to,a.icon=$a,a.imageOverlay=Ka,a.latLng=$,a.latLngBounds=U,a.layerGroup=Fa,a.map=ka,a.marker=Ha,a.point=z,a.polygon=Ua,a.polyline=qa,a.popup=Qa,a.rectangle=no,a.setOptions=w,a.stamp=g,a.svg=Sn,a.svgOverlay=Ja,a.tileLayer=Nn,a.tooltip=Xa,a.transformation=tt,a.version=d,a.videoOverlay=Ya;var ao=window.L;a.noConflict=function(){return window.L=ao,this},window.L=a}))})(Ut,Ut.exports)),Ut.exports}var Ei=kd();function Es(n,l,a){return Object.freeze({instance:n,context:l,container:a})}function Ms(n,l){return l==null?function(d,h){const u=k.useRef();return u.current||(u.current=n(d,h)),u}:function(d,h){const u=k.useRef();u.current||(u.current=n(d,h));const m=k.useRef(d),{instance:p}=u.current;return k.useEffect(function(){m.current!==d&&(l(p,d,m.current),m.current=d)},[p,d,h]),u}}function Rr(n,l){k.useEffect(function(){return(l.layerContainer??l.map).addLayer(n.instance),function(){var u;(u=l.layerContainer)==null||u.removeLayer(n.instance),l.map.removeLayer(n.instance)}},[l,n])}function Nd(n){return function(a){const d=Ss(),h=n(Ti(a,d),d);return Ir(d.map,a.attribution),Ts(h.current,a.eventHandlers),Rr(h.current,d),h}}function Cd(n,l){const a=k.useRef();k.useEffect(function(){if(l.pathOptions!==a.current){const h=l.pathOptions??{};n.instance.setStyle(h),a.current=h}},[n,l])}function Ld(n){return function(a){const d=Ss(),h=n(Ti(a,d),d);return Ts(h.current,a.eventHandlers),Rr(h.current,d),Cd(h.current,a),h}}function Pd(n,l){const a=Ms(n),d=wd(a,l);return vd(d)}function Sd(n,l){const a=Ms(n,l),d=Ld(a);return yd(d)}function Td(n,l){const a=Ms(n,l),d=Nd(a);return bd(d)}function Ed(n,l,a){const{opacity:d,zIndex:h}=l;d!=null&&d!==a.opacity&&n.setOpacity(d),h!=null&&h!==a.zIndex&&n.setZIndex(h)}const Md=Sd(function({center:l,children:a,...d},h){const u=new Ei.CircleMarker(l,d);return Es(u,_d(h,{overlayContainer:u}))},gd);function ys(){return ys=Object.assign||function(n){for(var l=1;l(j==null?void 0:j.map)??null,[j]);const w=k.useCallback(E=>{if(E!==null&&j===null){const T=new Ei.Map(E,_);a!=null&&N!=null?T.setView(a,N):n!=null&&T.fitBounds(n,l),g!=null&&T.whenReady(g),C(xd(T))}},[]);k.useEffect(()=>()=>{j==null||j.map.remove()},[j]);const S=j?Yt.createElement(Dr,{value:j},d):m??null;return Yt.createElement("div",ys({},b,{ref:w}),S)}const zd=k.forwardRef(Ad),Id=Pd(function(l,a){const d=new Ei.Popup(l,a.overlayContainer);return Es(d,a)},function(l,a,{position:d},h){k.useEffect(function(){const{instance:m}=l;function p(N){N.popup===m&&(m.update(),h(!0))}function g(N){N.popup===m&&h(!1)}return a.map.on({popupopen:p,popupclose:g}),a.overlayContainer==null?(d!=null&&m.setLatLng(d),m.openOn(a.map)):a.overlayContainer.bindPopup(m),function(){var _;a.map.off({popupopen:p,popupclose:g}),(_=a.overlayContainer)==null||_.unbindPopup(),a.map.removeLayer(m)}},[l,a,h,d])}),Od=Td(function({url:l,...a},d){const h=new Ei.TileLayer(l,Ti(a,d));return Es(h,d)},function(l,a,d){Ed(l,a,d);const{url:h}=a;h!=null&&h!==d.url&&l.setUrl(h)}),Dd=({profile:n})=>{var m,p,g,N;if(!((p=(m=n==null?void 0:n.geospatial)==null?void 0:m.sample_points)!=null&&p.length))return i.jsx(ct,{icon:i.jsx(fs,{className:"w-12 h-12 text-slate-300 dark:text-slate-600"}),title:"No Geospatial Data",description:"No geospatial sample points were recorded for this report."});const l=n.geospatial,a=!!n.target_col,d=si(l.sample_points??[],a?"label":void 0),h=d.map(({label:_,color:v})=>({label:_,color:v,shape:"circle"})),u=[[l.min_lat,l.min_lon],[l.max_lat,l.max_lon]];return i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(fs,{className:"w-5 h-5 mr-2 text-blue-500"}),"Geospatial Analysis",i.jsx(be,{text:"Visualizes data points on a map based on detected Latitude/Longitude columns. Colors indicate target values."})]}),i.jsxs("div",{className:"text-sm text-gray-500",children:["Detected columns: ",i.jsx("span",{className:"font-mono bg-gray-100 dark:bg-gray-900 px-1 rounded",children:n.geospatial.lat_col}),", ",i.jsx("span",{className:"font-mono bg-gray-100 dark:bg-gray-900 px-1 rounded",children:n.geospatial.lon_col})]})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[i.jsxs("div",{className:"lg:col-span-2 min-w-0",children:[i.jsx("div",{className:"h-96 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 relative z-0",children:i.jsxs(zd,{bounds:u,style:{height:"100%",width:"100%"},scrollWheelZoom:!0,children:[i.jsx(Od,{url:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",attribution:'© OpenStreetMap contributors'}),d.flatMap(_=>_.points.map((v,b)=>i.jsx(Md,{center:[v.lat,v.lon],radius:5,pathOptions:{color:a?_.color:"#3b82f6",fillColor:a?_.color:"#3b82f6",fillOpacity:.7,weight:1},children:i.jsx(Id,{children:i.jsxs("div",{className:"text-xs",children:[i.jsx("strong",{children:"Lat:"})," ",v.lat.toFixed(4),i.jsx("br",{}),i.jsx("strong",{children:"Lon:"})," ",v.lon.toFixed(4),i.jsx("br",{}),a&&i.jsxs(i.Fragment,{children:[i.jsxs("strong",{children:[n.target_col,":"]})," ",_.label]})]})})},JSON.stringify([_.value,b]))))]},`${l.lat_col??""}-${l.lon_col??""}-${u.flat().join(",")}`)}),a&&i.jsx(Ps,{entries:h})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 p-4 rounded-md",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-3",children:"Spatial Bounds"}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("span",{className:"block text-xs text-gray-400",children:"Latitude Range"}),i.jsxs("span",{className:"font-mono",children:[n.geospatial.min_lat.toFixed(4)," to ",n.geospatial.max_lat.toFixed(4)]})]}),i.jsxs("div",{children:[i.jsx("span",{className:"block text-xs text-gray-400",children:"Longitude Range"}),i.jsxs("span",{className:"font-mono",children:[n.geospatial.min_lon.toFixed(4)," to ",n.geospatial.max_lon.toFixed(4)]})]})]})]}),i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 p-4 rounded-md",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-3",children:"Centroid"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500"}),i.jsxs("span",{className:"font-mono text-sm",children:[((g=n.geospatial.centroid_lat)==null?void 0:g.toFixed(4))??"—",", ",((N=n.geospatial.centroid_lon)==null?void 0:N.toFixed(4))??"—"]})]})]}),i.jsxs("div",{className:"flex items-start gap-2 bg-blue-50 dark:bg-blue-900/20 p-3 rounded-md border border-blue-100 dark:border-blue-800",children:[i.jsx(Pt,{className:"w-4 h-4 text-blue-500 mt-0.5 shrink-0"}),i.jsx("div",{className:"text-sm text-blue-700 dark:text-blue-300",children:i.jsxs("p",{children:["This scatter plot shows the spatial distribution of your data.",!!n.target_col&&" Points are colored by the target variable."]})})]})]})]})]})};function Vt(n){return(n==null?void 0:n.toFixed(2))??"N/A"}const Rd=({profile:n,downloadChart:l,history:a,loading:d,loadSpecificReport:h,report:u})=>{var C;const[m,p]=k.useState("idle"),g=ht(),N=k.useCallback(()=>{p("done"),setTimeout(()=>p("idle"),1200)},[]),{target_col:_,target_correlations:v}=n;if(!v)return null;const b=Object.values(v)[0],j=async()=>{if(n!=null&&n.target_interactions){p("downloading");try{const w=Cr(),S=n.target_interactions,E=400,T=800,O=40,le=2,ge=Math.ceil(S.length/le),pe=le*T+(le+1)*O,Pe=ge*(E+O)+100,xe=document.createElement("canvas");xe.width=pe,xe.height=Pe;const K=xe.getContext("2d");if(!K)return;K.fillStyle=w.bgColor,K.fillRect(0,0,xe.width,xe.height),K.fillStyle=w.textColor,K.font="bold 24px sans-serif",K.textAlign="center",K.fillText("Detailed Interactions (Box Plots)",pe/2,50);for(let q=0;q{se.onload=()=>{K.drawImage(se,A,ae+30,T,E-50),URL.revokeObjectURL(U),W()},se.onerror=()=>{URL.revokeObjectURL(U),W()},se.src=U})}const Q=document.createElement("a");Q.download="all-interactions.png",Q.href=xe.toDataURL("image/png"),Q.click()}finally{N()}}};return i.jsxs("div",{className:"mt-4 grid grid-cols-1 lg:grid-cols-4 gap-6",children:[i.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(kt,{className:"w-5 h-5 mr-2 text-blue-500"}),"Target Analysis: ",i.jsx("span",{className:"ml-2 text-blue-600",children:n.target_col}),i.jsx(be,{text:"Analyzes relationships between the target variable and other features. Shows top correlations and key drivers."})]}),i.jsx("button",{onClick:()=>l("target-analysis-chart","target-analysis",`Target Analysis: ${n.target_col}`,"Top Associated Features"),className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300",title:"Download Chart","aria-label":"Download Chart",children:i.jsx(Ne,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-4",children:"Top Associated Features"}),i.jsx("div",{className:"h-64 w-full",id:"target-analysis-chart",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(lt,{data:Object.entries(v).slice(0,10).map(([w,S])=>({name:w,value:S})),layout:"vertical",margin:{top:5,right:30,left:40,bottom:5},children:[i.jsx(Qe,{strokeDasharray:"3 3",horizontal:!1,stroke:g.gridColor}),i.jsx(Xe,{type:"number",domain:[0,1],tick:{fontSize:12,fill:g.axisColor}}),i.jsx(et,{type:"category",dataKey:"name",width:120,tick:{fontSize:12,fill:g.axisColor}}),i.jsx(qe,{contentStyle:g.tooltipContentStyle,itemStyle:g.tooltipItemStyle,labelStyle:g.tooltipLabelStyle,formatter:w=>[w.toFixed(3),"Association"]}),i.jsx(Sr,{x:0,stroke:"#9ca3af"}),i.jsx(Ge,{dataKey:"value",fill:"#3b82f6",radius:[0,4,4,0],barSize:20})]})})})]}),i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 p-4 rounded-md",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-2",children:"Key Insights"}),i.jsxs("ul",{className:"space-y-2 text-sm",children:[i.jsxs("li",{className:"flex items-start",children:[i.jsx("span",{className:"mr-2 text-blue-500",children:"•"}),i.jsxs("span",{children:["Target is ",i.jsx("strong",{children:(C=n.columns[String(_)])==null?void 0:C.dtype})]})]}),i.jsxs("li",{className:"flex items-start",children:[i.jsx("span",{className:"mr-2 text-blue-500",children:"•"}),i.jsxs("span",{children:["Strongest predictor: ",i.jsx("strong",{children:Object.keys(v)[0]||"None"}),b!=null&&i.jsxs(i.Fragment,{children:[" (",b.toFixed(2),")"]})]})]})]})]})]})]}),n.target_interactions&&n.target_interactions.length>0&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-2",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Kt,{className:"w-5 h-5 mr-2 text-purple-500"}),"Detailed Interactions (Box Plots)",i.jsx(be,{text:"Shows distribution of values across categories. The box represents the middle 50% of data (Q1 to Q3). The line inside is the median."})]}),i.jsx("button",{onClick:j,disabled:m!=="idle",className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 disabled:opacity-50",title:"Download All Charts","aria-label":"Download All Charts",children:m==="downloading"?i.jsx(je,{className:"w-4 h-4 animate-spin"}):m==="done"?i.jsx(Jt,{className:"w-4 h-4 text-green-500"}):i.jsx(Ne,{className:"w-4 h-4"})})]}),i.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mb-6",children:[i.jsx("span",{className:"font-semibold",children:"ANOVA Analysis:"})," A p-value < 0.05 (highlighted in green) indicates that the feature varies significantly across the target categories, making it a strong predictor."]}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:n.target_interactions.map((w,S)=>i.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 p-4 rounded-lg border border-gray-100 dark:border-gray-800 relative group",children:[i.jsx("div",{className:"absolute top-2 right-2 opacity-100",children:i.jsx("button",{onClick:()=>l(`interaction-chart-${S}`,`interaction-${w.feature}`,`${w.feature} vs ${n.target_col}`,w.p_value!=null?`ANOVA p: ${Number(w.p_value).toExponential(2)}`:void 0),className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm",title:"Download Chart","aria-label":"Download Chart",children:i.jsx(Ne,{className:"w-3 h-3"})})}),i.jsxs("div",{className:"text-center mb-2",children:[i.jsxs("h4",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:[w.feature," vs ",n.target_col]}),w.p_value!==void 0&&w.p_value!==null&&i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full inline-block mt-1 ${w.p_value<.05?"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400":"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400"}`,children:["ANOVA p: ",Number(w.p_value).toExponential(2)]})]}),i.jsx("div",{className:"h-64 w-full",id:`interaction-chart-${S}`,children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(el,{data:w.data.map(E=>({...E,boxBottom:E.stats.q1,boxHeight:E.stats.q3!=null&&E.stats.q1!=null?E.stats.q3-E.stats.q1:null})),margin:{top:20,right:30,left:20,bottom:5},children:[i.jsx(Qe,{strokeDasharray:"3 3",vertical:!1,stroke:g.gridColor}),i.jsx(Xe,{dataKey:"name",tick:{fontSize:11,fill:g.axisColor}}),i.jsx(et,{domain:["auto","auto"],tick:{fontSize:11,fill:g.axisColor}}),i.jsx(qe,{cursor:{fill:"transparent"},content:({active:E,activeIndex:T})=>{const O=T===void 0?void 0:w.data[Number(T)];return E&&O?i.jsxs("div",{style:g.tooltipContentStyle,className:"text-xs p-2 rounded shadow-lg z-50",children:[i.jsx("p",{className:"font-semibold mb-1",children:O.name}),i.jsxs("p",{children:["Max: ",Vt(O.stats.max)]}),i.jsxs("p",{children:["Q3: ",Vt(O.stats.q3)]}),i.jsxs("p",{children:["Median: ",Vt(O.stats.median)]}),i.jsxs("p",{children:["Q1: ",Vt(O.stats.q1)]}),i.jsxs("p",{children:["Min: ",Vt(O.stats.min)]})]}):null}}),i.jsx(Ge,{dataKey:"boxBottom",stackId:"a",fill:"transparent",legendType:"none"}),i.jsx(Ge,{dataKey:"boxHeight",stackId:"a",fill:"#8884d8",fillOpacity:.6,name:"IQR (Q1-Q3)"}),i.jsx(ds,{name:"Median",dataKey:"stats.median",fill:"#ff7300",shape:"square"}),i.jsx(ds,{name:"Max",dataKey:"stats.max",fill:"#82ca9d",shape:"cross"}),i.jsx(ds,{name:"Min",dataKey:"stats.min",fill:"#82ca9d",shape:"cross"})]})})}),i.jsx("p",{className:"text-xs text-center text-gray-400 mt-2",children:"* Box: Q1-Q3. Orange square: Median. Green crosses: Min/Max."})]},S))})]})]}),i.jsx("div",{className:"lg:col-span-1",children:i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm h-fit sticky top-4",children:[i.jsxs("h3",{className:"text-sm font-semibold text-gray-900 dark:text-white mb-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center",children:[i.jsx(us,{className:"w-4 h-4 mr-2"}),"Analysis History"]}),d&&i.jsx(je,{className:"w-3 h-3 animate-spin text-blue-500"})]}),i.jsx("div",{className:"space-y-2 max-h-[500px] overflow-y-auto",children:a.length===0?i.jsx("p",{className:"text-xs text-gray-500 italic",children:"No previous analyses found."}):a.slice(0,10).map(w=>i.jsxs("button",{onClick:()=>!d&&h(w.id),disabled:d,className:`w-full text-left p-3 rounded-md text-sm border transition-colors ${u&&u.id===w.id?"bg-blue-50 border-blue-200 text-blue-700 dark:bg-blue-900/20 dark:border-blue-800 dark:text-blue-300":"bg-gray-50 border-gray-100 text-gray-600 hover:bg-gray-100 dark:bg-gray-900 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800"} ${d?"opacity-50 cursor-not-allowed":""}`,children:[i.jsx("div",{className:"font-medium truncate",children:w.target_col?`Target: ${w.target_col}`:"General Analysis"}),i.jsx("div",{className:"text-xs opacity-70 mt-1",children:new Date(w.created_at).toLocaleString()}),i.jsx("div",{className:"mt-1",children:i.jsx(Nr,{status:w.status})})]},w.id))})]})})]})};function Bd(n){return n.aggregation==="count"?"Row count":n.aggregation==="mean"&&n.metric?`Mean of ${n.metric}`:"Recorded value (measure unavailable)"}const Fd=({profile:n,downloadChart:l})=>{var m,p;const a=ht(),{timeseries:d}=n;if(!d)return null;const h=d.seasonality,u=Bd(h);return i.jsxs("div",{className:"mt-4 space-y-6",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center",children:[i.jsx(ws,{className:"w-5 h-5 mr-2 text-blue-500"}),"Trend Analysis (",d.date_col,")",i.jsx(be,{text:"Shows how values change over time. Look for long-term trends (up/down) or sudden shifts."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[d.stationarity_test&&i.jsxs("div",{className:`text-xs px-3 py-1 rounded-full border flex items-center gap-1 ${d.stationarity_test.is_stationary?"bg-green-50 border-green-200 text-green-700 dark:bg-green-900/20 dark:border-green-800 dark:text-green-300":"bg-yellow-50 border-yellow-200 text-yellow-700 dark:bg-yellow-900/20 dark:border-yellow-800 dark:text-yellow-300"}`,children:[i.jsx(be,{text:"Augmented Dickey-Fuller Test. Stationary (p<0.05) means the data has constant mean/variance over time. Non-Stationary (p>=0.05) means it has a trend or seasonality."}),i.jsx("span",{className:"font-semibold",children:"ADF Test:"})," ",d.stationarity_test.is_stationary?"Stationary":"Non-Stationary",i.jsxs("span",{className:"opacity-75 ml-1",children:["(p=",d.stationarity_test.p_value.toFixed(3),")"]})]}),i.jsx("button",{onClick:()=>l("trend-chart","trend-analysis","Trend Analysis",`Date Column: ${d.date_col}`,d.stationarity_test?`ADF Test: ${d.stationarity_test.is_stationary?"Stationary":"Non-Stationary"} (p=${d.stationarity_test.p_value.toFixed(3)})`:void 0),className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm",title:"Download Chart","aria-label":"Download Chart",children:i.jsx(Ne,{className:"w-4 h-4"})})]})]}),i.jsx("div",{className:"h-80 w-full",id:"trend-chart",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(tl,{data:d.trend,children:[i.jsx(Qe,{strokeDasharray:"3 3",vertical:!1,stroke:a.gridColor}),i.jsx(Xe,{dataKey:"date",tick:{fontSize:12,fill:a.axisColor},minTickGap:30}),i.jsx(et,{tick:{fill:a.axisColor}}),i.jsx(qe,{contentStyle:a.tooltipContentStyle,itemStyle:a.tooltipItemStyle,labelStyle:a.tooltipLabelStyle}),i.jsx(Pr,{}),Object.keys(((m=d.trend[0])==null?void 0:m.values)||{}).map((g,N)=>i.jsx($n,{type:"monotone",dataKey:`values.${g}`,name:g,stroke:Ue[N%Ue.length],dot:!1,strokeWidth:2},g)),(!((p=d.trend[0])!=null&&p.values)||Object.keys(d.trend[0].values).length===0)&&i.jsx($n,{type:"monotone",dataKey:"count",stroke:"#3b82f6",dot:!1})]})})})]}),i.jsx("div",{className:"grid grid-cols-1 gap-6",children:i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm relative group",children:[i.jsx("div",{className:"absolute top-4 right-4 opacity-100 z-10",children:i.jsx("button",{onClick:()=>l("day-seasonality-chart","day-seasonality","Day of Week Seasonality",u),className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm",title:"Download Chart","aria-label":"Download Chart",children:i.jsx(Ne,{className:"w-3 h-3"})})}),i.jsxs("div",{className:"flex items-center mb-4",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500",children:"Day of Week Seasonality"}),i.jsx(be,{text:`${u} by day of week. Helps identify weekly patterns.`})]}),i.jsx("p",{className:"text-sm text-gray-500 mb-2",children:u}),i.jsx("div",{className:"h-64 w-full",id:"day-seasonality-chart",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(lt,{data:d.seasonality.day_of_week,children:[i.jsx(Qe,{strokeDasharray:"3 3",vertical:!1,stroke:a.gridColor}),i.jsx(Xe,{dataKey:"day",tick:{fontSize:12,fill:a.axisColor}}),i.jsx(et,{tick:{fill:a.axisColor}}),i.jsx(qe,{contentStyle:a.tooltipContentStyle,itemStyle:a.tooltipItemStyle,labelStyle:a.tooltipLabelStyle,cursor:{fill:"transparent"}}),i.jsx(Ge,{dataKey:"count",name:u,fill:"#8884d8",radius:[4,4,0,0]})]})})})]})}),i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm relative group",children:[i.jsx("div",{className:"absolute top-4 right-4 opacity-100 z-10",children:i.jsx("button",{onClick:()=>l("month-seasonality-chart","month-seasonality","Monthly Seasonality",u),className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm",title:"Download Chart","aria-label":"Download Chart",children:i.jsx(Ne,{className:"w-3 h-3"})})}),i.jsxs("div",{className:"flex items-center mb-4",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500",children:"Monthly Seasonality"}),i.jsx(be,{text:`${u} by month. Helps identify yearly patterns.`})]}),i.jsx("p",{className:"text-sm text-gray-500 mb-2",children:u}),i.jsx("div",{className:"h-64 w-full",id:"month-seasonality-chart",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(lt,{data:d.seasonality.month_of_year,children:[i.jsx(Qe,{strokeDasharray:"3 3",vertical:!1,stroke:a.gridColor}),i.jsx(Xe,{dataKey:"month",tick:{fontSize:12,fill:a.axisColor}}),i.jsx(et,{tick:{fill:a.axisColor}}),i.jsx(qe,{contentStyle:a.tooltipContentStyle,itemStyle:a.tooltipItemStyle,labelStyle:a.tooltipLabelStyle,cursor:{fill:"transparent"}}),i.jsx(Ge,{dataKey:"count",name:u,fill:"#82ca9d",radius:[4,4,0,0]})]})})})]}),d.autocorrelation&&d.autocorrelation.length>0&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm relative group",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center",children:[i.jsx("h3",{className:"text-sm font-medium text-gray-500",children:"Autocorrelation (Lag Analysis)"}),i.jsxs("div",{className:"group relative ml-2",children:[i.jsx(Pt,{className:"w-4 h-4 text-gray-400 cursor-help"}),i.jsxs("div",{className:"absolute left-1/2 -translate-x-1/2 bottom-full mb-2 w-64 p-2 bg-gray-800 text-white text-xs rounded shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-50 pointer-events-none text-center",children:["Shows how much the current value depends on past values (lags). High bars indicate repeating patterns or seasonality.",i.jsx("div",{className:"absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-800"})]})]})]}),i.jsx("button",{onClick:()=>l("autocorrelation-chart","autocorrelation","Autocorrelation (Lag Analysis)"),className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm",title:"Download Chart","aria-label":"Download Chart",children:i.jsx(Ne,{className:"w-3 h-3"})})]}),i.jsx("div",{className:"h-80 w-full pb-6",id:"autocorrelation-chart",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(lt,{data:d.autocorrelation,margin:{bottom:20},children:[i.jsx(Qe,{strokeDasharray:"3 3",vertical:!1,stroke:a.gridColor}),i.jsx(Xe,{dataKey:"lag",tick:{fontSize:12,fill:a.axisColor},label:{value:"Lag (Days)",position:"insideBottom",offset:-15,fontSize:12,fill:a.axisColor}}),i.jsx(et,{domain:[-1,1],tick:{fill:a.axisColor}}),i.jsx(qe,{contentStyle:a.tooltipContentStyle,itemStyle:a.tooltipItemStyle,labelStyle:a.tooltipLabelStyle,cursor:{fill:"transparent"},formatter:g=>[g.toFixed(3),"Correlation"]}),i.jsx(Sr,{y:0,stroke:"#9ca3af"}),i.jsx(Ge,{dataKey:"corr",fill:"#f59e0b",radius:[2,2,0,0]})]})})})]})]})},Zd=({profile:n,onBarClick:l})=>{const a=ht(),{data:d,typeMatched:h}=k.useMemo(()=>{var p;if(!n)return{data:[],typeMatched:!1};const m=n.dtype;return m==="Numeric"&&n.histogram?{data:n.histogram.map(g=>({name:`${Number(g.start).toFixed(2)}`,fullName:`${Number(g.start).toFixed(2)} - ${Number(g.end).toFixed(2)}`,count:g.count,rawBin:g})),typeMatched:!0}:m==="Text"&&n.histogram?{data:n.histogram.map(g=>({name:`${Number(g.start).toFixed(0)}`,fullName:`${Number(g.start).toFixed(0)} - ${Number(g.end).toFixed(0)} chars`,count:g.count,rawBin:g})),typeMatched:!0}:m==="DateTime"&&n.histogram?{data:n.histogram.map(g=>({name:new Date(g.start).toLocaleDateString(void 0,{month:"short",year:"2-digit"}),fullName:`${new Date(g.start).toLocaleDateString()} - ${new Date(g.end).toLocaleDateString()}`,count:g.count,rawBin:g})),typeMatched:!0}:m==="Categorical"&&((p=n.categorical_stats)!=null&&p.top_k)?{data:n.categorical_stats.top_k.map(g=>({name:String(g.value).substring(0,15)+(String(g.value).length>15?"...":""),fullName:String(g.value),count:g.count,value:g.value})),typeMatched:!0}:{data:[],typeMatched:!1}},[n]);if(!n)return null;if(!h)return i.jsx("div",{className:"text-gray-500 dark:text-gray-400 text-sm italic p-4 text-center",children:"No distribution data available for this type"});if(d.length===0)return i.jsx("div",{className:"text-gray-500 dark:text-gray-400 text-sm italic p-4 text-center",children:"No data points"});const u=n.dtype;return i.jsxs("div",{className:"w-full h-full flex flex-col",children:[i.jsxs("div",{className:"flex-1 w-full min-h-[250px] relative",children:[n.normality_test&&i.jsxs("div",{className:"absolute top-0 right-0 bg-white/90 dark:bg-gray-800/90 p-2 rounded border border-gray-200 dark:border-gray-700 text-xs z-10 shadow-sm",children:[i.jsxs("div",{className:"font-semibold text-gray-700 dark:text-gray-300 mb-1 flex items-center",children:["Normality Test (",n.normality_test.test_name,")",i.jsx(be,{text:"Normality tests are performed on a sample of up to 5,000 rows. Shapiro-Wilk is used for smaller datasets (<5,000), and Kolmogorov-Smirnov for larger ones. For very large datasets, rely on Skewness and Kurtosis.",align:"right"})]}),i.jsxs("div",{className:"flex justify-between gap-4",children:[i.jsx("span",{className:"text-gray-500",children:"p-value:"}),i.jsx("span",{className:`font-mono ${n.normality_test.is_normal?"text-green-600":"text-red-500"}`,children:n.normality_test.p_value.toExponential(2)})]}),i.jsx("div",{className:"mt-1 text-[10px] text-gray-400",children:n.normality_test.is_normal?"Likely Normal Distribution":"Likely Not Normal"})]}),i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(lt,{data:d,margin:{top:5,right:30,left:20,bottom:30},children:[i.jsx(Qe,{strokeDasharray:"3 3",vertical:!1,stroke:a.gridColor}),i.jsx(Xe,{dataKey:"name",tick:{fontSize:11,fill:a.axisColor},interval:"preserveStartEnd",angle:-45,textAnchor:"end"}),i.jsx(et,{tick:{fontSize:11,fill:a.axisColor}}),i.jsx(qe,{content:({active:m,payload:p})=>{if(m&&p&&p.length){const g=p[0].payload;return i.jsxs("div",{style:a.tooltipContentStyle,className:"text-xs p-2 rounded shadow-lg",children:[i.jsx("p",{className:"font-semibold mb-1",children:g.fullName}),i.jsxs("p",{children:["Count: ",g.count]}),l&&i.jsx("p",{className:"text-blue-300 mt-1 italic",children:"Click to filter"})]})}return null}}),i.jsx(Ge,{dataKey:"count",radius:[4,4,0,0],onClick:m=>l&&l(m),className:l?"cursor-pointer hover:opacity-80":"",children:d.map((m,p)=>i.jsx(Cs,{fill:u==="Numeric"?"#3b82f6":"#8b5cf6"},`cell-${p}`))})]})})]}),i.jsx(Si,{caption:`Distribution data table for ${n.name}`,filename:`${n.name}-distribution`,columns:[{key:"fullName",label:"Bin / Value"},{key:"count",label:"Count"}],rows:d.map(m=>({fullName:m.fullName,count:m.count}))})]})};var $d=Symbol.for("react.lazy"),Ni=So[" use ".trim().toString()];function Hd(n){return typeof n=="object"&&n!==null&&"then"in n}function Br(n){return n!=null&&typeof n=="object"&&"$$typeof"in n&&n.$$typeof===$d&&"_payload"in n&&Hd(n._payload)}function Wd(n){const l=qd(n),a=k.forwardRef((d,h)=>{let{children:u,...m}=d;Br(u)&&typeof Ni=="function"&&(u=Ni(u._payload));const p=k.Children.toArray(u),g=p.find(Gd);if(g){const N=g.props.children,_=p.map(v=>v===g?k.Children.count(N)>1?k.Children.only(null):k.isValidElement(N)?N.props.children:null:v);return i.jsx(l,{...m,ref:h,children:k.isValidElement(N)?k.cloneElement(N,void 0,_):null})}return i.jsx(l,{...m,ref:h,children:u})});return a.displayName=`${n}.Slot`,a}var Vd=Wd("Slot");function qd(n){const l=k.forwardRef((a,d)=>{let{children:h,...u}=a;if(Br(h)&&typeof Ni=="function"&&(h=Ni(h._payload)),k.isValidElement(h)){const m=Yd(h),p=Kd(u,h.props);return h.type!==k.Fragment&&(p.ref=d?Ro(d,m):m),k.cloneElement(h,p)}return k.Children.count(h)>1?k.Children.only(null):null});return l.displayName=`${n}.SlotClone`,l}var Ud=Symbol("radix.slottable");function Gd(n){return k.isValidElement(n)&&typeof n.type=="function"&&"__radixId"in n.type&&n.type.__radixId===Ud}function Kd(n,l){const a={...l};for(const d in l){const h=n[d],u=l[d];/^on[A-Z]/.test(d)?h&&u?a[d]=(...p)=>{const g=u(...p);return h(...p),g}:h&&(a[d]=h):d==="style"?a[d]={...h,...u}:d==="className"&&(a[d]=[h,u].filter(Boolean).join(" "))}return{...n,...a}}function Yd(n){var d,h;let l=(d=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:d.get,a=l&&"isReactWarning"in l&&l.isReactWarning;return a?n.ref:(l=(h=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:h.get,a=l&&"isReactWarning"in l&&l.isReactWarning,a?n.props.ref:n.props.ref||n.ref)}const Kn=n=>typeof n=="boolean"?`${n}`:n===0?"0":n,Yn=Tr,Fr=(n,l)=>a=>{var d;if((l==null?void 0:l.variants)==null)return Yn(n,a==null?void 0:a.class,a==null?void 0:a.className);const{variants:h,defaultVariants:u}=l,m=Object.keys(h).map(N=>{const _=a==null?void 0:a[N],v=u==null?void 0:u[N];if(_===null)return null;const b=Kn(_)||Kn(v);return h[N][b]}),p=a&&Object.entries(a).reduce((N,_)=>{let[v,b]=_;return b===void 0||(N[v]=b),N},{}),g=l==null||(d=l.compoundVariants)===null||d===void 0?void 0:d.reduce((N,_)=>{let{class:v,className:b,...j}=_;return Object.entries(j).every(C=>{let[w,S]=C;return Array.isArray(S)?S.includes({...u,...p}[w]):{...u,...p}[w]===S})?[...N,v,b]:N},[]);return Yn(n,m,g,a==null?void 0:a.class,a==null?void 0:a.className)},Jd=Fr("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"action-primary",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"action-secondary",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Xt=k.forwardRef(({className:n,variant:l,size:a,asChild:d=!1,...h},u)=>{const m=d?Vd:"button";return i.jsx(m,{className:Jd({variant:l,size:a,className:n}),ref:u,...h})});Xt.displayName="Button";function Zr(...n){return Bo(Tr(n))}const Qd=Fr("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function dt({className:n,variant:l,...a}){return i.jsx("div",{className:Zr(Qd({variant:l}),n),...a})}function Xd({profile:n}){var a;let l=[];return n.histogram?l=n.histogram.map(d=>({name:String(d.start),count:d.count})):(a=n.categorical_stats)!=null&&a.top_k&&(l=n.categorical_stats.top_k.slice(0,10).map(d=>({name:String(d.value),count:d.count}))),i.jsxs("div",{className:"flex items-center justify-between w-full pr-4",children:[i.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground mr-auto",children:[i.jsx(ec,{profile:n}),i.jsx(tc,{profile:n})]}),l.length>0&&i.jsx("div",{className:"h-8 w-24 hidden sm:block opacity-70",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsx(lt,{data:l,children:i.jsx(Ge,{dataKey:"count",fill:n.dtype==="Numeric"?"#3b82f6":n.dtype==="Categorical"?"#8b5cf6":"#10b981",radius:[1,1,0,0]})})})})]})}function ec({profile:n}){var l,a,d,h,u;return i.jsx(i.Fragment,{children:n.numeric_stats?i.jsxs(i.Fragment,{children:[i.jsxs("span",{children:["Mean: ",i.jsx("span",{className:"font-mono text-foreground",children:(l=n.numeric_stats.mean)==null?void 0:l.toFixed(2)})]}),i.jsxs("span",{children:["Std: ",i.jsx("span",{className:"font-mono text-foreground",children:(a=n.numeric_stats.std)==null?void 0:a.toFixed(2)})]}),i.jsxs("span",{children:["Min: ",i.jsx("span",{className:"font-mono text-foreground",children:(d=n.numeric_stats.min)==null?void 0:d.toFixed(2)})]}),i.jsxs("span",{children:["Max: ",i.jsx("span",{className:"font-mono text-foreground",children:(h=n.numeric_stats.max)==null?void 0:h.toFixed(2)})]})]}):n.categorical_stats?i.jsxs(i.Fragment,{children:[i.jsxs("span",{children:["Unique: ",i.jsx("span",{className:"font-mono text-foreground",children:n.categorical_stats.unique_count})]}),((u=n.categorical_stats.top_k)==null?void 0:u[0])&&i.jsxs("span",{children:["Top: ",i.jsx("span",{className:"font-mono text-foreground",children:String(n.categorical_stats.top_k[0].value).slice(0,20)})]})]}):null})}function tc({profile:n}){return i.jsxs(i.Fragment,{children:[n.normality_test&&n.normality_test.is_normal&&i.jsx(dt,{variant:"outline",className:"text-[10px] h-4 text-purple-600 dark:text-purple-400 border-purple-200 dark:border-purple-800 bg-purple-50 dark:bg-purple-900/20",children:"Normal Dist"}),n.normality_test&&!n.normality_test.is_normal&&i.jsx(dt,{variant:"outline",className:"text-[10px] h-4 text-amber-600 dark:text-amber-400 border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20",children:"Not Normal"})]})}function ic({profile:n}){return i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("span",{className:"font-medium text-sm truncate",children:n.name}),i.jsx(dt,{variant:"outline",className:`text-[10px] h-5 px-1 ${Nl(n.dtype)}`,children:n.dtype}),n.is_unique&&i.jsx(dt,{variant:"secondary",className:"text-[10px] h-5",children:"ID"}),n.is_constant&&i.jsx(dt,{variant:"destructive",className:"text-[10px] h-5",children:"Constant"})]})}function sc({profile:n,isExcluded:l,onToggleExclude:a}){return i.jsxs("div",{className:"flex items-center gap-4 px-2",children:[i.jsxs("div",{className:"flex flex-col items-end w-24",children:[i.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[i.jsx("span",{className:"text-[10px] text-muted-foreground",children:n.missing_percentage>0?`${n.missing_percentage.toFixed(1)}% Missing`:"100% Present"}),i.jsx(be,{text:"Green bar indicates the percentage of valid (non-null) data. Full green means no missing values.",align:"end",size:"sm"})]}),i.jsx("div",{className:"w-full h-1.5 bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full ${n.missing_percentage>0?"bg-amber-400":"bg-green-500"}`,style:{width:`${Math.max(100-n.missing_percentage,0)}%`}})})]}),i.jsx("div",{className:"h-8 w-[1px] bg-border mx-2"}),i.jsx(Xt,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:d=>{d.stopPropagation(),a(n.name,!l)},title:l?"Include in analysis":"Exclude from analysis","aria-label":l?"Include in analysis":"Exclude from analysis",children:l?i.jsx(ii,{size:16}):i.jsx(vr,{size:16})})]})}function Le(n,l,a=""){return typeof n=="number"&&Number.isFinite(n)?`${n.toFixed(l)}${a}`:"—"}function nc({profile:n}){return i.jsxs("div",{className:"space-y-4",children:[i.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Statistics"}),i.jsxs("div",{className:"bg-background rounded-md border p-3 text-sm space-y-2 font-mono",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Missing"}),i.jsxs("span",{children:[n.missing_count," (",n.missing_percentage.toFixed(2),"%)"]})]}),n.numeric_stats&&i.jsx(rc,{stats:n.numeric_stats,vif:n.vif}),n.text_stats&&i.jsx(lc,{stats:n.text_stats}),n.categorical_stats&&i.jsx(dc,{stats:n.categorical_stats})]})]})}function rc({stats:n,vif:l}){return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Mean"}),i.jsx("span",{children:Le(n.mean,4)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Std Dev"}),i.jsx("span",{children:Le(n.std,4)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Variance"}),i.jsx("span",{children:Le(n.variance===void 0&&n.std!=null?n.std**2:n.variance,4)})]}),i.jsx("div",{className:"my-2 border-t border-dashed"}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Min"}),i.jsx("span",{children:Le(n.min,4)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"25% (Q1)"}),i.jsx("span",{children:Le(n.q25,4)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Median"}),i.jsx("span",{children:Le(n.median,4)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"75% (Q3)"}),i.jsx("span",{children:Le(n.q75,4)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Max"}),i.jsx("span",{children:Le(n.max,4)})]}),i.jsx("div",{className:"my-2 border-t border-dashed"}),i.jsx(ac,{stats:n}),i.jsx("div",{className:"my-2 border-t border-dashed"}),i.jsx(oc,{stats:n,vif:l})]})}function ac({stats:n}){return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Skewness"}),i.jsx("span",{children:Le(n.skewness,4)})]}),n.skewness!=null&&i.jsx("div",{className:"text-[10px] text-muted-foreground pl-2",children:Math.abs(n.skewness)<.5?"↳ Symmetric":Math.abs(n.skewness)<1?"↳ Moderately Skewed":"↳ Highly Skewed"}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Kurtosis"}),i.jsx("span",{children:Le(n.kurtosis,4)})]}),n.kurtosis!=null&&i.jsx("div",{className:"text-[10px] text-muted-foreground pl-2",children:Math.abs(n.kurtosis)<.5?"↳ Mesokurtic (Normal-like)":n.kurtosis>0?"↳ Leptokurtic (Heavy Tails)":"↳ Platykurtic (Light Tails)"})]})}function oc({stats:n,vif:l}){return i.jsxs(i.Fragment,{children:[n.zeros_count!=null&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Zeros"}),i.jsx("span",{children:n.zeros_count})]}),n.negatives_count!=null&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Negatives"}),i.jsx("span",{children:n.negatives_count})]}),l!=null&&i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsxs("span",{className:"text-muted-foreground flex items-center gap-1",children:["VIF",i.jsx(be,{text:"Variance Inflation Factor. VIF > 5 = high multicollinearity, VIF > 10 = severe.",size:"sm"})]}),i.jsx("span",{className:l>5?"text-red-500 font-semibold":l>2?"text-amber-500":"text-green-500",children:l.toFixed(2)})]})]})}function lc({stats:n}){var l;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Avg Length"}),i.jsxs("span",{children:[(l=n.avg_length)==null?void 0:l.toFixed(1)," chars"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Min Length"}),i.jsx("span",{children:n.min_length})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Max Length"}),i.jsx("span",{children:n.max_length})]}),n.sentiment_distribution&&i.jsx(cc,{distribution:n.sentiment_distribution}),n.common_words&&n.common_words.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"my-2 border-t border-dashed"}),i.jsx("div",{className:"text-xs font-semibold mb-1",children:"Common Words"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:n.common_words.slice(0,10).map((a,d)=>i.jsxs(dt,{variant:"secondary",className:"text-[10px] h-4",children:[a.word??a.value," (",a.count,")"]},d))})]})]})}function dc({stats:n}){var l,a,d,h;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Unique"}),i.jsx("span",{children:n.unique_count})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Mode"}),i.jsx("span",{className:"truncate max-w-[100px]",title:String((a=(l=n.top_k)==null?void 0:l[0])==null?void 0:a.value),children:String(((h=(d=n.top_k)==null?void 0:d[0])==null?void 0:h.value)||"-")})]}),n.rare_labels_count!=null&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-muted-foreground",children:"Rare Labels"}),i.jsx("span",{children:n.rare_labels_count})]}),n.top_k&&n.top_k.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"my-2 border-t border-dashed"}),i.jsx("div",{className:"text-xs font-semibold mb-1",children:"Top Categories"}),i.jsx("div",{className:"space-y-1",children:n.top_k.slice(0,5).map((u,m)=>i.jsxs("div",{className:"flex justify-between text-xs",children:[i.jsx("span",{className:"truncate max-w-[120px]",title:String(u.value),children:String(u.value)}),i.jsx("span",{className:"text-muted-foreground",children:u.count})]},m))})]})]})}function cc({distribution:n}){const l=n.positive||0,a=n.neutral||0,d=n.negative||0;return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"my-2 border-t border-dashed"}),i.jsx("div",{className:"text-xs font-semibold mb-1",children:"Sentiment"}),i.jsxs("div",{className:"flex h-3 rounded-full overflow-hidden w-full bg-secondary",children:[i.jsx("div",{className:"bg-green-500 h-full",style:{width:`${l*100}%`},title:`Positive: ${(l*100).toFixed(1)}%`}),i.jsx("div",{className:"bg-gray-400 h-full",style:{width:`${a*100}%`},title:`Neutral: ${(a*100).toFixed(1)}%`}),i.jsx("div",{className:"bg-red-500 h-full",style:{width:`${d*100}%`},title:`Negative: ${(d*100).toFixed(1)}%`})]}),i.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-1 px-1",children:[i.jsxs("span",{children:["Pos: ",(l*100).toFixed(0),"%"]}),i.jsxs("span",{children:["Neu: ",(a*100).toFixed(0),"%"]}),i.jsxs("span",{children:["Neg: ",(d*100).toFixed(0),"%"]})]})]})}const Jn=({profile:n,isExpanded:l,onToggleExpand:a,onToggleExclude:d,isExcluded:h,handleAddFilter:u,handleAddFilters:m})=>{const p=k.useRef(null),[g,N]=k.useState("idle"),_=async()=>{if(p.current){N("downloading");try{const b=document.documentElement.classList.contains("dark"),j=await Ns(p.current,{backgroundColor:b?"#1f2937":"#ffffff",pixelRatio:2}),C=document.createElement("a");C.href=j,C.download=`${n.name}_distribution.png`,C.click()}catch(b){console.error("Failed to download chart",b),Qt.error("Chart download failed",String(b))}finally{N("done"),setTimeout(()=>N("idle"),1200)}}},v=b=>{var j;if(n.dtype==="Categorical"||n.dtype==="Boolean"){const C=b.value!==void 0?b.value:b.name;u(n.name,C,"==")}else if(n.dtype==="Numeric"&&b.rawBin){const C=(j=n.histogram)==null?void 0:j[0];m([{column:n.name,value:b.rawBin.start,operator:b.rawBin.start===(C==null?void 0:C.start)?">=":">"},{column:n.name,value:b.rawBin.end,operator:"<="}])}};return i.jsxs("div",{className:`border rounded-lg mb-2 transition-all ${l?"border-primary/50 shadow-md bg-card/50":"border-border bg-card"}`,children:[i.jsxs("div",{className:"flex items-center p-3 hover:bg-accent/50 cursor-pointer rounded-t-lg",...Pi(a),children:[i.jsx("div",{className:"mr-2 text-muted-foreground",children:l?i.jsx(Li,{size:18}):i.jsx(yr,{size:18})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx(ic,{profile:n}),!l&&i.jsx(Xd,{profile:n})]}),i.jsx(sc,{profile:n,isExcluded:h,onToggleExclude:d})]}),l&&i.jsx("div",{className:"p-4 border-t border-border bg-card/30 animate-in slide-in-from-top-2 duration-200",children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 items-stretch",children:[i.jsx(nc,{profile:n}),i.jsxs("div",{className:"md:col-span-2 flex flex-col min-h-[300px]",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Distribution"}),i.jsx(Xt,{size:"icon",variant:"outline",className:"h-8 w-8",title:"Download Chart",onClick:_,disabled:g!=="idle",children:g==="downloading"?i.jsx(je,{size:16,className:"animate-spin"}):g==="done"?i.jsx(Jt,{size:16,className:"text-green-500"}):i.jsx(Ne,{size:16})})]}),i.jsx("div",{className:"flex-1 bg-background rounded-md border p-4 min-h-0",ref:p,children:i.jsx(Zd,{profile:n,onBarClick:v})})]})]})})]})},$r=k.forwardRef(({className:n,type:l,...a},d)=>i.jsx("input",{type:l,className:Zr("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",n),ref:d,...a}));$r.displayName="Input";const hc=({profile:n,handleToggleExclude:l,handleAddFilter:a,handleAddFilters:d})=>{const[h,u]=k.useState(""),[m,p]=k.useState(new Set);Fo(()=>p(new Set),m.size>0);const g=j=>{const C=new Set(m);C.has(j)?C.delete(j):C.add(j),p(C)},N=()=>{p(new Set(Object.keys(n.columns)))},_=()=>{p(new Set)},v=Object.values(n.columns).filter(j=>j.name.toLowerCase().includes(h.toLowerCase())),b=(n.excluded_columns??[]).filter(j=>j.toLowerCase().includes(h.toLowerCase()));return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center gap-4 bg-card p-2 rounded-lg border",children:[i.jsxs("div",{className:"relative flex-1 max-w-sm",children:[i.jsx(To,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none z-10"}),i.jsx($r,{placeholder:"Search variables...",className:"pl-8 h-9",value:h,onChange:j=>u(j.target.value)})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xt,{variant:"outline",size:"sm",onClick:N,className:"h-9 text-xs",children:"Expand All"}),i.jsx(Xt,{variant:"outline",size:"sm",onClick:_,className:"h-9 text-xs",children:"Collapse All"})]}),i.jsxs("div",{className:"ml-auto text-sm text-muted-foreground px-2",children:["Showing ",v.length," of ",Object.keys(n.columns).length," variables"]})]}),i.jsxs("div",{className:"space-y-2",children:[v.map(j=>i.jsx(Jn,{profile:j,isExpanded:m.has(j.name),onToggleExpand:()=>g(j.name),onToggleExclude:l,isExcluded:!1,handleAddFilter:a,handleAddFilters:d},j.name)),b.length>0&&i.jsxs("div",{className:"mt-8",children:[i.jsxs("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2 text-muted-foreground",children:["Excluded Variables ",i.jsx(dt,{variant:"secondary",children:b.length})]}),b.map(j=>i.jsx(Jn,{profile:{name:j,dtype:"Excluded",missing_count:0,missing_percentage:0},isExpanded:m.has(j),onToggleExpand:()=>g(j),onToggleExclude:l,isExcluded:!0,handleAddFilter:a,handleAddFilters:d},j))]})]})]})};function uc({profile:n,scatterX:l,scatterY:a,scatterZ:d,scatterColor:h,is3D:u}){return i.jsx(i.Fragment,{children:l&&a?u&&d?i.jsx(Ar,{data:n.sample_data??[],xKey:l,yKey:a,zKey:d,labelKey:h||void 0,xLabel:l,yLabel:a,zLabel:d}):i.jsx(zr,{data:n.sample_data??[],xKey:l,yKey:a,labelKey:h||void 0,xLabel:l,yLabel:a}):i.jsx("div",{className:"h-64 flex items-center justify-center bg-gray-50 dark:bg-gray-900 rounded text-gray-400 text-sm",children:"Select X and Y variables to generate scatter plot."})})}const mc=({profile:n,downloadChart:l,scatterX:a,setScatterX:d,scatterY:h,setScatterY:u,scatterZ:m,setScatterZ:p,scatterColor:g,setScatterColor:N,is3D:_,setIs3D:v})=>{const b=k.useMemo(()=>(n==null?void 0:n.sample_data)??[],[n==null?void 0:n.sample_data]),j=k.useMemo(()=>Mr(si(b,g||void 0)),[b,g]),C=k.useMemo(()=>{const T=[{key:a,label:a||"X"},{key:h,label:h||"Y"}];return _&&m&&T.push({key:m,label:m}),g&&T.push({key:g,label:g}),T},[a,h,m,g,_]),w=k.useMemo(()=>b.map(T=>T),[b]);if(!(n!=null&&n.columns)||!(n!=null&&n.sample_data))return i.jsx(ct,{icon:i.jsx(Kt,{className:"w-12 h-12 text-slate-300 dark:text-slate-600"}),title:"No Data Available",description:"Sample data is required for bivariate analysis."});const S=!!(a&&h&&n.sample_data.length>0),E=S?"Download Chart":"Select X and Y variables to enable download";return i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Kt,{className:"w-5 h-5 mr-2 text-blue-500"}),"Bivariate Analysis (Scatter Plot)",i.jsx(be,{text:"Visualize the relationship between two numeric variables."})]}),i.jsx("button",{disabled:!S,onClick:()=>l("bivariate-chart","bivariate-analysis","Bivariate Analysis",`${a} vs ${h}`),className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 disabled:opacity-50",title:E,"aria-label":E,children:i.jsx(Ne,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-6 items-end",children:[i.jsxs("div",{children:[i.jsx("span",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:"X Axis"}),i.jsxs("select",{value:a,onChange:T=>d(T.target.value),className:"block w-full sm:w-48 rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2 border dark:bg-slate-700 dark:border-slate-600 dark:text-white",children:[i.jsx("option",{value:"",children:"Select Variable"}),Object.values(n.columns).filter(T=>T.dtype==="Numeric").map(T=>i.jsx("option",{value:T.name,children:T.name},T.name))]})]}),i.jsxs("div",{children:[i.jsx("span",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Y Axis"}),i.jsxs("select",{value:h,onChange:T=>u(T.target.value),className:"block w-full sm:w-48 rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2 border dark:bg-slate-700 dark:border-slate-600 dark:text-white",children:[i.jsx("option",{value:"",children:"Select Variable"}),Object.values(n.columns).filter(T=>T.dtype==="Numeric").map(T=>i.jsx("option",{value:T.name,children:T.name},T.name))]})]}),_&&i.jsxs("div",{children:[i.jsx("span",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Z Axis"}),i.jsxs("select",{value:m,onChange:T=>p(T.target.value),className:"block w-full sm:w-48 rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2 border dark:bg-slate-700 dark:border-slate-600 dark:text-white",children:[i.jsx("option",{value:"",children:"Select Variable"}),Object.values(n.columns).filter(T=>T.dtype==="Numeric").map(T=>i.jsx("option",{value:T.name,children:T.name},T.name))]})]}),i.jsxs("div",{children:[i.jsx("span",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:"Color By"}),i.jsxs("select",{value:g,onChange:T=>N(T.target.value),className:"block w-full sm:w-48 rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2 border dark:bg-slate-700 dark:border-slate-600 dark:text-white",children:[i.jsx("option",{value:"",children:"None"}),Object.values(n.columns).map(T=>i.jsx("option",{value:T.name,children:T.name},T.name))]})]}),i.jsx("button",{onClick:()=>v(!_),className:`p-2 rounded-md border transition-colors ${_?"bg-blue-50 border-blue-200 text-blue-700 dark:bg-blue-900/20 dark:border-blue-800 dark:text-blue-300":"bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300"}`,title:"Toggle 3D View","aria-label":"Toggle 3D View",children:i.jsx(wr,{className:"w-5 h-5"})})]}),i.jsx("div",{id:"bivariate-chart",children:i.jsx(uc,{profile:n,scatterX:a,scatterY:h,scatterZ:m,scatterColor:g,is3D:_})}),g&&j.length>0&&i.jsx(Ps,{entries:j}),i.jsx(Si,{caption:"Bivariate scatter plot data",filename:"bivariate-analysis",columns:C,rows:w})]})};function fc(n){const{analyzed_rows:l,total_rows:a}=n;return l==null||a==null?{description:"Analyzed row count is unavailable for this saved report.",countLabel:"Reported outliers",percentageLabel:"Reported percentage"}:l{if(!(n!=null&&n.outliers))return i.jsx(ct,{icon:i.jsx(ji,{className:"w-12 h-12 text-slate-300 dark:text-slate-600"}),title:"Outlier analysis unavailable",description:"This report contains no outlier analysis. No reason was recorded."});const l=fc(n.outliers);return n.outliers.total_outliers===0&&n.outliers.top_outliers.length===0?i.jsx(ct,{title:"No outliers detected",description:l.description}):i.jsxs("div",{className:"mt-4 bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-4 flex items-center",children:[i.jsx(ji,{className:"w-5 h-5 mr-2 text-red-500"}),"Outlier Analysis (",n.outliers.method,")",i.jsx(be,{text:"Detects anomalous rows using Isolation Forest. Lower scores indicate higher anomaly."})]}),i.jsx("p",{className:"mb-4 text-sm text-gray-600 dark:text-gray-300",children:l.description}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-6",children:[i.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 p-4 rounded-lg border border-red-100 dark:border-red-800",children:[i.jsx("span",{className:"text-sm text-red-600 dark:text-red-400 block mb-1",children:l.countLabel}),i.jsx("span",{className:"text-2xl font-bold text-red-700 dark:text-red-300",children:n.outliers.total_outliers})]}),i.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 p-4 rounded-lg border border-red-100 dark:border-red-800",children:[i.jsx("span",{className:"text-sm text-red-600 dark:text-red-400 block mb-1",children:l.percentageLabel}),i.jsxs("span",{className:"text-2xl font-bold text-red-700 dark:text-red-300",children:[n.outliers.outlier_percentage.toFixed(2),"%"]})]})]}),i.jsx("h4",{className:"text-md font-medium text-gray-900 dark:text-white mb-3",children:"Top Anomalous Rows"}),i.jsx("div",{className:"overflow-x-auto border border-gray-200 dark:border-gray-700 rounded-lg",children:i.jsxs("table",{className:"min-w-full divide-y divide-gray-200 dark:divide-gray-700",children:[i.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase",children:"Row Index"}),i.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase",children:"Anomaly Score"}),i.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase",children:"Why is this an outlier?"}),n.outliers.top_outliers[0]&&Object.keys(n.outliers.top_outliers[0].values??{}).slice(0,5).map(a=>i.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase",children:a},a))]})}),i.jsxs("tbody",{className:"bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700",children:[n.outliers.top_outliers.length===0&&i.jsx("tr",{children:i.jsx("td",{colSpan:3,className:"px-4 py-3 text-sm text-gray-500",children:"Row-level details are unavailable for this saved report."})}),n.outliers.top_outliers.map(a=>{var d;return i.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-gray-700",children:[i.jsx("td",{className:"px-4 py-3 text-sm font-mono text-gray-500",children:a.index}),i.jsx("td",{className:"px-4 py-3 text-sm font-mono text-red-600",children:((d=a.score)==null?void 0:d.toFixed(4))??"—"}),i.jsx("td",{className:"px-4 py-3 text-sm",children:a.explanation?i.jsx("div",{className:"space-y-1",children:a.explanation.map((h,u)=>i.jsxs("div",{className:"text-xs",children:[i.jsxs("span",{className:"font-semibold text-gray-700 dark:text-gray-300",children:[h.feature,":"]})," ",i.jsx("span",{className:"text-red-600 dark:text-red-400",children:Le(h.value,2)})," ",i.jsxs("span",{className:"text-gray-400",children:["(Median: ",Le(h.median,2),", Diff: ",Le(h.diff_pct,0,"%"),")"]})]},u))}):i.jsx("span",{className:"text-gray-400 text-xs",children:"No explanation available"})}),Object.entries(a.values??{}).slice(0,5).map(([h,u])=>i.jsx("td",{className:"px-4 py-3 text-sm text-gray-900 dark:text-gray-300",children:typeof u=="number"?u.toFixed(2):String(u)},h))]},a.index)})]})]})})]})},Nt=20,Hr=[-1,-.4,-.02,0,.02,.4,1];function ei(n){if(n===null||!Number.isFinite(n))return"rgb(229, 231, 235)";const l=Math.sqrt(Math.min(1,Math.abs(n)));return`rgb(${(n<0?[59,130,246]:[239,68,68]).map(d=>Math.round(255+(d-255)*l)).join(", ")})`}function Wr(n){const l=[],a=n.omitted_columns??[];if(a.length){const h=n.total_columns??n.columns.length+a.length;l.push(`Correlation analysis used the first ${h-a.length} of ${h} numeric columns by column order (${a.length} omitted: ${a.slice(0,5).join(", ")}${a.length>5?", …":""}). These omitted columns are not included in the data table.`)}const d=n.columns.slice(Nt);return d.length&&l.push(`Showing the first ${Nt} of ${n.columns.length} columns (${d.length} omitted from the heatmap: ${d.slice(0,5).join(", ")}${d.length>5?", …":""}). The full computed matrix is available in the data table and CSV.`),l}const pc=({data:n})=>i.jsx(i.Fragment,{children:Wr(n).map(l=>i.jsx("div",{className:"mb-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 text-yellow-800 dark:text-yellow-200 text-sm rounded-md",children:l},l))}),xc=()=>i.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-gray-600 dark:text-gray-300",role:"img","aria-label":"Correlation color scale from negative one (blue) through zero (white) to positive one (red)",children:[Hr.map(n=>i.jsxs("span",{className:"flex flex-col items-center gap-1",children:[i.jsx("span",{className:"h-3 w-6 rounded-sm border border-gray-300",style:{backgroundColor:ei(n)}}),i.jsx("span",{children:n===-1?"−1":n===1?"+1":n})]},n)),i.jsxs("span",{className:"ml-2 flex flex-col items-center gap-1",children:[i.jsx("span",{className:"h-3 w-6 rounded-sm border border-gray-300",style:{backgroundColor:ei(null)}}),i.jsx("span",{children:"Missing"})]})]}),Qn=({data:n})=>{const l=k.useMemo(()=>((n==null?void 0:n.columns)??[]).slice(0,Nt),[n]),a=k.useMemo(()=>((n==null?void 0:n.values)??[]).slice(0,Nt).map(h=>h.slice(0,Nt)),[n]),d=k.useMemo(()=>n!=null&&n.columns?n.columns.map((h,u)=>{const m={row_label:h};return n.columns.forEach((p,g)=>{var N;m[`column_${g}`]=((N=n.values[u])==null?void 0:N[g])??null}),m}):[],[n]);return!n||!n.columns?i.jsx("div",{children:"No correlation data available"}):i.jsxs("div",{className:"overflow-x-auto p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsx(xc,{}),i.jsx(pc,{data:n}),i.jsx("div",{className:"inline-block min-w-full",children:i.jsxs("div",{className:"grid gap-1",style:{gridTemplateColumns:`100px repeat(${l.length}, minmax(50px, 1fr))`,paddingTop:"4.5rem"},children:[i.jsx("div",{className:"p-2"}),l.map((h,u)=>i.jsx("div",{className:"relative p-2 text-xs font-medium text-gray-700 dark:text-gray-300",title:h,children:i.jsx("span",{className:"absolute bottom-1 left-1/2 whitespace-nowrap origin-bottom-left",style:{transform:"rotate(-45deg)"},children:h})},u)),l.map((h,u)=>i.jsxs(Yt.Fragment,{children:[i.jsx("div",{className:"p-2 text-xs font-medium truncate text-right pr-4 text-gray-700 dark:text-gray-300",title:h,children:h}),(a[u]??[]).map((m,p)=>i.jsx("div",{className:"h-10 w-full flex items-center justify-center text-[10px] text-gray-900 dark:text-gray-100 rounded-sm cursor-help transition-opacity hover:opacity-80",style:{backgroundColor:ei(m),color:"#111827"},title:`${h} vs ${l[p]}: ${m!==null?m.toFixed(3):"N/A"}`,children:m!==null?m.toFixed(2):"—"},p))]},u))]})}),i.jsx(Si,{caption:"Full correlation matrix data table",filename:"correlation-matrix",columns:[{key:"row_label",label:"Variable"},...n.columns.map((h,u)=>({key:`column_${u}`,label:h}))],rows:d})]})};function Vr({target:n,reason:l}){if(!n||!l)return null;const a={categorical:`The selected target “${n}” is treated as categorical and is omitted from numeric-only causal discovery and Pearson correlations. Use Target Analysis for categorical associations.`,excluded:`The selected target “${n}” is excluded from this report's analysis.`,unsupported:`The selected target “${n}” is not supported by numeric-only causal discovery or Pearson correlations.`};return i.jsx("p",{className:"mb-4 text-sm text-gray-600 dark:text-gray-400",children:a[l]})}const _c=({profile:n})=>{const[l,a]=k.useState(null),[d,h]=k.useState(null),u=i.jsx(Vr,{target:n.target_col??null,reason:n.causal_target_exclusion_reason??null});if(!n.correlations)return i.jsxs(i.Fragment,{children:[u,i.jsx(ct,{icon:i.jsx(kt,{className:"w-12 h-12 text-slate-300 dark:text-slate-600"}),title:"No Correlation Data",description:"No correlation results were recorded for this report."})]});const m=async(p,g,N)=>{if(p){a(N);try{const _=Cr(),v=Nt,b=p.columns.slice(0,v),j=p.values.slice(0,v).map(K=>K.slice(0,v)),C=60,w=document.createElement("canvas"),S=w.getContext("2d");if(!S)return;S.font="12px sans-serif";let E=0;b.forEach(K=>{const Q=S.measureText(K).width;Q>E&&(E=Q)});const T=E+40,O=E*.7+60,le=Math.max(520,T+b.length*C+50),ge=[];for(const K of Wr(p)){let Q="";for(const q of K.split(" ")){const ee=Q?`${Q} ${q}`:q;Q&&S.measureText(ee).width>le-40?(ge.push(Q),Q=q):Q=ee}Q&&ge.push(Q)}const pe=110+ge.length*18,Pe=O+b.length*C+pe+50;w.width=le,w.height=Pe,S.fillStyle=_.bgColor,S.fillRect(0,0,le,Pe),S.fillStyle=_.textColor,S.font="bold 24px sans-serif",S.textAlign="center",S.fillText(g,le/2,40),S.font="12px sans-serif",S.textBaseline="middle",[...Hr,null].forEach((K,Q)=>{const q=20+Q*60;S.fillStyle=ei(K),S.fillRect(q,60,28,16),S.fillStyle=_.textColor,S.textAlign="left",S.fillText(K===null?"Missing":String(K),q,88)}),ge.forEach((K,Q)=>S.fillText(K,20,112+Q*18)),j.forEach((K,Q)=>{S.fillStyle=_.textColor,S.textAlign="right",S.fillText(b[Q]??"",T-10,O+pe+Q*C+C/2),K.forEach((q,ee)=>{const R=T+ee*C,B=O+pe+Q*C;S.fillStyle=ei(q),S.fillRect(R,B,C-2,C-2),q!==null&&(S.fillStyle="#111827",S.textAlign="center",S.fillText(q.toFixed(2),R+C/2,B+C/2))})}),S.save(),b.forEach((K,Q)=>{const q=T+Q*C+C/2,ee=O+pe-10;S.translate(q,ee),S.rotate(-Math.PI/4),S.fillStyle=_.textColor,S.textAlign="left",S.fillText(K,0,0),S.rotate(Math.PI/4),S.translate(-q,-ee)}),S.restore();const xe=document.createElement("a");xe.download=N,xe.href=w.toDataURL("image/png"),xe.click()}finally{a(null),h(N),setTimeout(()=>h(null),1200)}}};return i.jsxs("div",{className:"space-y-8",children:[u,i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(kt,{className:"w-5 h-5 mr-2 text-blue-500"}),"Feature Correlations (Multicollinearity)"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(be,{text:"Correlation between features only. Use this to detect redundant variables (multicollinearity)."}),i.jsx("button",{onClick:()=>m(n.correlations,"Feature Correlations","feature-correlations.png"),disabled:l!==null,className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm disabled:opacity-50",title:"Download Matrix","aria-label":"Download Matrix",children:l==="feature-correlations.png"?i.jsx(je,{className:"w-4 h-4 animate-spin"}):d==="feature-correlations.png"?i.jsx(Jt,{className:"w-4 h-4 text-green-500"}):i.jsx(Ne,{className:"w-4 h-4"})})]})]}),i.jsx(Qn,{data:n.correlations})]}),n.correlations_with_target&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(kt,{className:"w-5 h-5 mr-2 text-green-500"}),"Target Correlations (Feature Selection)"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(be,{text:"Correlation including the target variable. Use this to identify the most predictive features."}),i.jsx("button",{onClick:()=>m(n.correlations_with_target,"Target Correlations","target-correlations.png"),disabled:l!==null,className:"p-1.5 rounded-md bg-white border border-gray-200 text-gray-500 hover:text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-700 shadow-sm disabled:opacity-50",title:"Download Matrix","aria-label":"Download Matrix",children:l==="target-correlations.png"?i.jsx(je,{className:"w-4 h-4 animate-spin"}):d==="target-correlations.png"?i.jsx(Jt,{className:"w-4 h-4 text-green-500"}):i.jsx(Ne,{className:"w-4 h-4"})})]})]}),i.jsx(Qn,{data:n.correlations_with_target})]})]})},yc=({profile:n,excludedCols:l,handleToggleExclude:a})=>{var h;if(!((h=n==null?void 0:n.sample_data)!=null&&h.length))return i.jsx(ct,{icon:i.jsx(xr,{className:"w-12 h-12 text-slate-300 dark:text-slate-600"}),title:"No Sample Data",description:"No sample rows available for this dataset."});const d=Object.keys(n.sample_data[0]||{}).filter(u=>!l.includes(u)&&!u.endsWith("_encoded"));return i.jsxs("div",{className:"mt-4 overflow-x-auto bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700",children:[i.jsxs("table",{className:"min-w-full divide-y divide-gray-200 dark:divide-gray-700",children:[i.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900",children:i.jsx("tr",{children:d.map(u=>i.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider group",children:i.jsxs("div",{className:"flex items-center gap-2",children:[u,i.jsx("button",{onClick:m=>{m.stopPropagation(),a(u,!0)},className:"p-1 rounded transition-colors opacity-100 md:opacity-0 md:group-hover:opacity-100 focus:opacity-100 hover:bg-red-100 text-gray-400 hover:text-red-500 dark:hover:bg-red-900/30",title:"Exclude from analysis","aria-label":"Exclude from analysis",children:i.jsx(ii,{className:"w-3 h-3"})})]})},u))})}),i.jsx("tbody",{className:"bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700",children:n.sample_data.slice(0,50).map((u,m)=>i.jsx("tr",{children:d.map((p,g)=>i.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400",children:u[p]!==null?String(u[p]):i.jsx("span",{className:"italic text-gray-400",children:"null"})},g))},m))})]}),n.sample_data.length>50&&i.jsxs("div",{className:"p-4 text-center text-sm text-gray-500 border-t border-gray-200 dark:border-gray-700",children:["Showing first 50 rows of ",n.sample_data.length," sample rows."]})]})},vs=150,Xn=40,vc=()=>{const n=document.documentElement.classList.contains("dark");return{borderRadius:"5px",padding:"10px",width:vs,textAlign:"center",borderWidth:"1px",borderStyle:"solid",backgroundColor:n?"#222529":"#ffffff",color:n?"#f3f4f6":"#17102b",borderColor:n?"#666d77":"#b9b3c8"}},bc=n=>{const l=document.documentElement.classList.contains("dark");return n==="directed"?l?"#9acbfa":"#3b4bc4":l?"#abafb7":"#6b6485"},wc=(n,l)=>{const a={type:hs.ArrowClosed,color:l};return n==="bidirected"?{markerStart:a,markerEnd:a}:n==="directed"?{markerEnd:a}:{}},jc=({graph:n})=>{const[l,a,d]=nr([]),[h,u,m]=rr([]),[p,g]=k.useState(0);k.useEffect(()=>{const _=new MutationObserver(()=>{g(v=>v+1)});return _.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>_.disconnect()},[]);const N=k.useCallback((_,v)=>{try{const b=new ki.graphlib.Graph;return b.setDefaultEdgeLabel(()=>({})),b.setGraph({rankdir:"LR",nodesep:80,ranksep:200}),_.forEach(C=>{b.setNode(C.id,{width:vs,height:Xn})}),v.forEach(C=>{b.setEdge(C.source,C.target)}),ki.layout(b),{nodes:_.map(C=>{const w=b.node(C.id);return w?{...C,targetPosition:Ct.Left,sourcePosition:Ct.Right,position:{x:w.x-vs/2,y:w.y-Xn/2}}:{...C,position:{x:Math.random()*500,y:Math.random()*500}}}),edges:v}}catch(b){return console.error("Dagre layout failed:",b),{nodes:_.map((C,w)=>({...C,position:{x:w%3*250,y:Math.floor(w/3)*100}})),edges:v}}},[]);return k.useEffect(()=>{if(!n||!n.nodes||n.nodes.length===0){a([]),u([]);return}const _=new Map(n.nodes.map((C,w)=>[C.id,`causal-node-${w}`])),v=n.nodes.map((C,w)=>({id:`causal-node-${w}`,data:{label:C.label},position:{x:0,y:0},style:vc()})),b=n.edges.flatMap((C,w)=>{const S=_.get(C.source),E=_.get(C.target);if(S===void 0||E===void 0)return[];const T=bc(C.type);return[{id:`e${w}`,source:S,target:E,animated:!0,type:"default",label:C.type==="directed"?"causes":C.type==="bidirected"?"confounded":"related",labelStyle:{fill:"hsl(var(--foreground))",fontSize:12},labelBgStyle:{fill:"hsl(var(--card))"},style:{stroke:T,strokeDasharray:C.type==="directed"?"0":"5 5"},...wc(C.type,T)}]}),j=N(v,b);a(j.nodes),u(j.edges)},[n,N,a,u,p]),i.jsx("div",{className:"space-y-2",children:i.jsx("div",{style:{width:"100%",height:"500px"},className:"border rounded-lg bg-gray-50 dark:bg-gray-900 relative",children:i.jsxs(ar,{nodes:l,edges:h,onNodesChange:d,onEdgesChange:m,fitView:!0,className:"dark:bg-gray-900",children:[i.jsx(or,{className:"dark:bg-gray-900"}),i.jsx(lr,{className:"dark:bg-gray-800 dark:text-white dark:border-gray-700"})]})})})};function kc(n){switch(n){case"all":return"This graph includes all eligible numeric variables; no feature cap was needed.";case"target_correlation":return"This graph includes the selected numeric target and up to 14 numeric features with the strongest absolute Pearson correlations to it.";case"variance":return"This graph includes up to 15 of the highest-variance numeric variables; no eligible numeric target was used for selection.";default:return"Causal discovery is limited to up to 15 numeric variables. Selection details were not recorded for this report."}}const Nc=({profile:n})=>{var m;const l=n.causal_graph,[a,d]=k.useState("idle"),h=k.useCallback(()=>{const p=document.querySelector("#causal-chart .react-flow__viewport");if(!p)return;d("downloading");const N=document.documentElement.classList.contains("dark")?"#111827":"#f9fafb";Ns(p,{backgroundColor:N,pixelRatio:2,filter:_=>{const v=_==null?void 0:_.classList;return v?!v.contains("react-flow__controls")&&!v.contains("react-flow__minimap"):!0}}).then(_=>{const v=document.createElement("a");v.download="causal-discovery.png",v.href=_,v.click()}).catch(_=>{console.error("Causal graph download failed",_),Qt.error("Causal graph download failed",String(_))}).finally(()=>{d("done"),setTimeout(()=>d("idle"),1200)})},[]),u=i.jsx(Vr,{target:n.target_col??null,reason:n.causal_target_exclusion_reason??null});return(m=l==null?void 0:l.nodes)!=null&&m.length?i.jsx("div",{className:"space-y-6 mt-4",children:i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm",children:[i.jsxs("div",{className:"flex justify-between items-center mb-4",children:[i.jsxs("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center",children:[i.jsx(Lt,{className:"w-5 h-5 mr-2 text-purple-500"}),"Causal Discovery (PC Algorithm)",i.jsx(be,{text:"Inferred causal structure using the Peter-Clark algorithm. Arrows (A->B) suggest A causes B. Lines (A-B) suggest correlation without clear direction. Bidirected arrows (A<->B) suggest a hidden common cause."})]}),i.jsx("button",{onClick:h,disabled:a!=="idle",className:"p-2 rounded-md border bg-white border-gray-300 text-gray-700 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 disabled:opacity-50",title:"Download Chart",children:a==="downloading"?i.jsx(je,{className:"w-4 h-4 animate-spin"}):a==="done"?i.jsx(Jt,{className:"w-4 h-4 text-green-500"}):i.jsx(Ne,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"mb-4 text-sm text-gray-600 dark:text-gray-400 bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded border border-yellow-200 dark:border-yellow-800",children:[i.jsx("strong",{children:"Disclaimer:"})," This graph is inferred purely from observational data. Correlation does not imply causation. Use this as a hypothesis generation tool, not absolute truth."]}),u,i.jsx("div",{id:"causal-chart",children:i.jsx(jc,{graph:l})}),i.jsx("p",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:kc(l.selection_method)})]})}):i.jsxs("div",{className:"p-8 text-center text-gray-500",children:[i.jsx(Lt,{className:"w-12 h-12 mx-auto mb-4 opacity-50"}),i.jsx("p",{children:"No causal graph available. No reason was recorded for this report."}),u]})},er=220,tr=100;function Cc(n,l){if(n.feature===void 0||n.threshold===void 0)return"";const a=l==null?void 0:l[n.feature];if(a){const d=a.filter((h,u)=>u<=n.threshold);return`${n.feature} in [${d.join(", ")}]`}return`${n.feature} <= ${n.threshold.toFixed(2)}`}const Lc=({data:n})=>{const l=n.is_leaf,a=n.value.reduce((u,m)=>u+m,0),d=n.value.length>0?Math.max(...n.value):0,h=a>0?d/a*100:0;return i.jsxs("div",{className:`px-4 py-3 shadow-md rounded-md border-2 ${l?"border-green-500 bg-green-50 dark:bg-green-900/20":"border-blue-500 bg-white dark:bg-gray-800"} min-w-[200px]`,children:[i.jsx(Zn,{type:"target",position:Ct.Left,className:"w-3 h-3 !bg-gray-400"}),i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsx("div",{className:"font-bold text-sm text-gray-900 dark:text-white border-b pb-1 mb-1",children:l?i.jsxs("span",{className:"flex items-center gap-2 text-green-700 dark:text-green-400",children:[i.jsx(ur,{className:"w-4 h-4"}),"Prediction: ",n.class_name]}):i.jsxs("span",{className:"flex items-center gap-2 text-blue-700 dark:text-blue-400",children:[i.jsx(Eo,{className:"w-4 h-4"}),Cc(n,n.categories)]})}),i.jsxs("div",{className:"text-xs text-gray-600 dark:text-gray-300 space-y-1",children:[i.jsxs(Lr,{children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsxs(gs,{children:[i.jsx(ps,{asChild:!0,children:i.jsx("span",{className:"cursor-help border-b border-dotted border-gray-400",children:"Samples:"})}),i.jsx(xs,{children:i.jsx("p",{children:"The number of data points that fall into this rule bucket."})})]}),i.jsx("span",{className:"font-mono",children:n.samples})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsxs(gs,{children:[i.jsx(ps,{asChild:!0,children:i.jsx("span",{className:"cursor-help border-b border-dotted border-gray-400",children:"Purity:"})}),i.jsx(xs,{children:i.jsx("p",{className:"max-w-xs",children:"The percentage of samples in this node that belong to the majority class. Higher purity means a clearer separation."})})]}),i.jsxs("span",{className:`font-mono ${h>80?"text-green-600 font-bold":""}`,children:[h.toFixed(1),"%"]})]})]}),i.jsx("div",{className:"w-full h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full mt-1 overflow-hidden flex",children:n.value.map((u,m)=>i.jsx("div",{style:{width:`${a>0?u/a*100:0}%`,backgroundColor:`hsl(${m*137.5}, 70%, 50%)`},title:`Class ${m}: ${u}`},m))})]})]}),i.jsx(Zn,{type:"source",position:Ct.Right,className:"w-3 h-3 !bg-gray-400"})]})},Pc={decision:Lc},Sc=({tree:n})=>{const[l,a,d]=nr([]),[h,u,m]=rr([]),p=k.useCallback((g,N)=>{try{const _=new ki.graphlib.Graph;return _.setDefaultEdgeLabel(()=>({})),_.setGraph({rankdir:"LR",nodesep:50,ranksep:150}),g.forEach(b=>{_.setNode(b.id,{width:er,height:tr})}),N.forEach(b=>{_.setEdge(b.source,b.target)}),ki.layout(_),{nodes:g.map(b=>{const j=_.node(b.id);return{...b,targetPosition:Ct.Left,sourcePosition:Ct.Right,position:{x:j?j.x-er/2:0,y:j?j.y-tr/2:0}}}),edges:N}}catch(_){return console.error("Dagre layout failed:",_),{nodes:g,edges:N}}},[]);return k.useEffect(()=>{if(!n||!n.nodes||n.nodes.length===0)return;const g=n.nodes.map(v=>({id:v.id.toString(),type:"decision",data:{...v,categories:n.categories},position:{x:0,y:0}})),N=[];n.nodes.forEach(v=>{v.children&&v.children.length>0&&(v.children[0]!==void 0&&N.push({id:`e${v.id}-${v.children[0]}`,source:v.id.toString(),target:v.children[0].toString(),label:"True",type:"smoothstep",style:{stroke:"#22c55e",strokeWidth:2},labelStyle:{fill:"#22c55e",fontWeight:700},markerEnd:{type:hs.ArrowClosed,color:"#22c55e"}}),v.children[1]!==void 0&&N.push({id:`e${v.id}-${v.children[1]}`,source:v.id.toString(),target:v.children[1].toString(),label:"False",type:"smoothstep",style:{stroke:"#ef4444",strokeWidth:2},labelStyle:{fill:"#ef4444",fontWeight:700},markerEnd:{type:hs.ArrowClosed,color:"#ef4444"}}))});const _=p(g,N);a(_.nodes),u(_.edges)},[n,p,a,u]),i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{style:{width:"100%",height:"600px"},className:"border rounded-lg bg-gray-50 dark:bg-gray-900 relative",children:i.jsxs(ar,{nodes:l,edges:h,onNodesChange:d,onEdgesChange:m,nodeTypes:Pc,fitView:!0,className:"dark:bg-gray-900",children:[i.jsx(or,{className:"dark:bg-gray-900",gap:16,size:1}),i.jsx(lr,{className:"dark:bg-gray-800 dark:text-white dark:border-gray-700"})]})}),i.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 italic flex items-center gap-1",children:[i.jsx(Pt,{className:"w-3 h-3"}),"This tree is a ",i.jsx("strong",{children:"surrogate (explanatory) model"})," trained on your data to surface readable rules. Do not treat it as a production-grade predictor. Green paths mean the condition is met (True); red paths mean it is not (False)."]})]})},Tc=({profile:n})=>{const l=n==null?void 0:n.rule_tree,a=ht();return l?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsxs("div",{className:"flex items-center justify-between mb-6",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2",children:[i.jsx(ms,{className:"w-5 h-5 text-blue-600"}),"Decision Tree Analysis"]}),i.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:["This is a ",i.jsx("strong",{children:"surrogate model"}),": a simple decision tree trained on your dataset to approximate the relationship between features and the target. Use it for interpretation (human-readable rules), not as a causal claim or a production model."]})]}),l.accuracy&&i.jsx(Lr,{children:i.jsxs(gs,{children:[i.jsx(ps,{asChild:!0,children:i.jsxs("div",{className:"text-sm bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 px-3 py-1 rounded-full border border-blue-200 dark:border-blue-800 cursor-help",children:["Tree Fidelity: ",i.jsxs("strong",{children:[(l.accuracy*100).toFixed(1),"%"]})]})}),i.jsx(xs,{children:i.jsxs("p",{className:"max-w-xs",children:[i.jsx("strong",{children:"Tree Fidelity:"})," How closely this surrogate tree matches the patterns in your data (higher is better). If fidelity is low, treat extracted rules as exploratory."]})})]})})]}),i.jsx(Sc,{tree:l})]}),l.feature_importances&&l.feature_importances.length>0&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsxs("h3",{className:"text-md font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2",children:[i.jsx(Mo,{className:"w-5 h-5 text-blue-600"}),"Feature Importance (Surrogate Model)"]}),i.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mb-4",children:["Importances reflect what the ",i.jsx("strong",{children:"surrogate tree"})," used to split the data. They may differ from a more complex model’s importances."]}),i.jsx("div",{className:"h-80 w-full",children:i.jsx(Ze,{width:"100%",height:"100%",children:i.jsxs(lt,{data:l.feature_importances.slice(0,10),layout:"vertical",margin:{top:5,right:30,left:40,bottom:5},children:[i.jsx(Qe,{strokeDasharray:"3 3",horizontal:!0,vertical:!1,stroke:a.gridColor}),i.jsx(Xe,{type:"number",domain:[0,"auto"],hide:!0}),i.jsx(et,{dataKey:"feature",type:"category",width:150,tick:{fontSize:12,fill:a.axisColor},interval:0}),i.jsx(qe,{formatter:d=>[(d*100).toFixed(1)+"%","Importance"],contentStyle:a.tooltipContentStyle,cursor:{fill:"transparent"}}),i.jsx(Ge,{dataKey:"importance",radius:[0,4,4,0],barSize:20,children:l.feature_importances.slice(0,10).map((d,h)=>i.jsx(Cs,{fill:`hsl(217, 91%, ${60-h*3}%)`},`cell-${h}`))})]})})}),i.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-2 text-center",children:"Showing top 10 features driving the decision rules."})]}),l.rules&&l.rules.length>0&&i.jsxs("div",{className:"bg-white dark:bg-gray-800 p-6 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700",children:[i.jsx("h3",{className:"text-md font-semibold text-gray-900 dark:text-white mb-4",children:"Segmentation-Decision Tree (Surrogate Model)"}),i.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:l.rules.map((d,h)=>i.jsx("div",{className:"p-3 bg-gray-50 dark:bg-gray-900 rounded border border-gray-100 dark:border-gray-700 text-sm font-mono text-gray-700 dark:text-gray-300",children:d},h))})]})]}):i.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-8",children:[i.jsx(ms,{className:"w-12 h-12 mb-4 text-gray-300 dark:text-gray-600"}),i.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-2",children:"Decision Tree Not Available"}),i.jsx("p",{className:"text-center max-w-md mb-4",children:"No decision tree was recorded for this report. No reason was recorded."})]})},Ec=20,ot=new Map;function bs(n){return n.filter_value===void 0?n.name:n.filter_value}function qt(n){return JSON.stringify([bs(n)])}function ir(n,l){if(ot.delete(n),ot.set(n,l),ot.size>Ec){const a=ot.keys().next().value;a!==void 0&&ot.delete(a)}}function Mc({datasetId:n,measureCol:l,measureAgg:a,initialFilters:d}){const h=d.map(({column:u,operator:m,value:p})=>{const g=m==="in"&&Array.isArray(p)?[...new Set(p.map(N=>JSON.stringify(N)))].sort():p;return JSON.stringify([u,m,g])});return JSON.stringify([n,l,a,[...new Set(h)].sort()])}const Ac=n=>{const l=Mc(n);return i.jsx(zc,{...n,cacheKey:l},l)},zc=({datasetId:n,measureCol:l,measureAgg:a,columns:d,initialFilters:h,cacheKey:u,resetVersion:m=0})=>{const[p,g]=k.useState([]),[N,_]=k.useState(!1),[v,b]=k.useState(null),[j,C]=k.useState(null),[w,S]=k.useState([null]),E=k.useRef(null),T=k.useRef(null),O=k.useRef(0),le=k.useRef(m),[ge,pe]=k.useState([]);k.useEffect(()=>{E.current&&E.current.scrollTo({left:E.current.scrollWidth,behavior:"smooth"})},[p.length]);const Pe=()=>{if(!T.current)return;const R=[],B=T.current.getBoundingClientRect();p.forEach((F,X)=>{if(X>=p.length-1)return;const re=F.items.findIndex(z=>qt(z)===F.selectedItemKey);if(re<0)return;const A=`node-${X}-${re}`,ae=document.getElementById(A);if(ae){const z=ae.getBoundingClientRect(),H=z.right-B.left,se=z.top+z.height/2-B.top;let ne,U;const W=p[X+1];if(!W)return;if(W.selectedItemKey){const $=W.items.findIndex(Oe=>qt(Oe)===W.selectedItemKey),ce=`node-${X+1}-${$}`,ye=document.getElementById(ce);if(ye){const Oe=ye.getBoundingClientRect();ne=Oe.left-B.left,U=Oe.top+Oe.height/2-B.top}else return}else{const $=`list-${X+1}`,ce=document.getElementById($);if(ce){const ye=ce.getBoundingClientRect();ne=ye.left-B.left,U=ye.top+ye.height/2-B.top}else return}if(ne!==void 0&&U!==void 0){const $=(H+ne)/2,ce=`M ${H} ${se} C ${$} ${se}, ${$} ${U}, ${ne} ${U}`;R.push({d:ce})}}}),pe(R)};Yt.useLayoutEffect(()=>{Pe()},[p,j]),k.useEffect(()=>{p.length>0&&ir(u,{levels:p,splitPath:w})},[p,w,u]),k.useEffect(()=>{le.current!==m&&(ot.delete(u),le.current=m),C(null),b(null);const R=ot.get(u);return R?(g(R.levels),S(R.splitPath),ir(u,R),_(!1)):(g([]),S([null]),xe()),()=>{O.current+=1}},[u,m]);const xe=async()=>{const R=++O.current;b(null),_(!0);try{const B=await Ke.getDecomposition(n,l==="count"?null:l,a,"",h);if(R!==O.current)return;g([{id:"root",splitColumn:null,items:B,selectedItemKey:null,filters:h}]),S([null])}catch(B){R===O.current&&(console.error(B),b({message:"Could not load decomposition.",retry:()=>{xe()}}))}finally{R===O.current&&_(!1)}},K=(R,B)=>{var ae,z,H,se,ne;const F=p[R];if(!F||!F.selectedItemKey)return;const X=F.items.find(U=>qt(U)===F.selectedItemKey);if(!X)return;const re=B.currentTarget.getBoundingClientRect(),A=(ae=E.current)==null?void 0:ae.getBoundingClientRect();if(A){let U=re.right-A.left+10,W=re.top-A.top;const $=((H=(z=E.current)==null?void 0:z.parentElement)==null?void 0:H.clientWidth)||window.innerWidth;U+260>$&&(U=re.left-A.left-270);const ce=((ne=(se=E.current)==null?void 0:se.parentElement)==null?void 0:ne.clientHeight)||window.innerHeight;W+300>ce&&(W=ce-310),C({levelIndex:R,item:X,x:U,y:W})}},Q=async(R,B)=>{const F=++O.current;b(null),C(null);const X=p[R];if(!X)return;const re={...X,selectedItemKey:qt(B)},A=p.map((z,H)=>H===R?re:z),ae=w[R+1];if(ae){_(!0);try{const z=[...re.filters];re.splitColumn&&z.push({column:re.splitColumn,operator:"==",value:bs(B)});const H=await Ke.getDecomposition(n,l==="count"?null:l,a,ae,z);if(F!==O.current)return;const se={id:`level-${R+1}`,splitColumn:ae,items:H,selectedItemKey:null,filters:z},ne=[...A.slice(0,R+1),se];g(ne),S(w.slice(0,R+2))}catch(z){F===O.current&&(console.error(z),b({message:`Could not refresh ${ae}. Previous results are still shown.`,retry:()=>{Q(R,B)}}))}finally{F===O.current&&_(!1)}}else _(!1),g(A)},q=async(R,B=j)=>{if(!B)return;const{levelIndex:F,item:X}=B;C(null),b(null);const re=++O.current;_(!0);try{const A=p[F];if(!A)return;const ae=[...A.filters];A.splitColumn&&ae.push({column:A.splitColumn,operator:"==",value:bs(X)});const z=await Ke.getDecomposition(n,l==="count"?null:l,a,R,ae);if(re!==O.current)return;const H={id:`level-${F+1}`,splitColumn:R,items:z,selectedItemKey:null,filters:ae},se=[...p.slice(0,F+1),H];g(se);const ne=[...w.slice(0,F+1),R];S(ne)}catch(A){re===O.current&&(console.error(A),b({message:`Could not split by ${R}. Previous results are still shown.`,retry:()=>{q(R,B)}}))}finally{re===O.current&&_(!1)}},ee=R=>{O.current+=1,b(null),_(!1),C(null),g(p.slice(0,R)),S(w.slice(0,R))};return i.jsxs("div",{className:"relative w-full h-[600px] bg-slate-50 dark:bg-slate-900 overflow-hidden flex flex-col",children:[v&&i.jsxs("div",{role:"alert",className:"m-3 p-3 rounded border border-red-200 bg-red-50 text-red-700 text-sm",children:[i.jsx("p",{children:v.message}),i.jsx("button",{onClick:v.retry,disabled:N,className:"mt-2 underline font-medium",children:"Retry"})]}),N&&i.jsx("div",{className:"absolute top-2 right-2 z-50",children:i.jsx(je,{className:"w-5 h-5 animate-spin text-blue-500"})}),i.jsx("div",{className:"flex-1 overflow-x-auto overflow-y-hidden",ref:E,children:i.jsxs("div",{className:"flex h-full p-8 min-w-max gap-12 relative",ref:T,children:[p.map((R,B)=>i.jsxs("div",{className:"flex flex-col w-[200px] h-full relative z-10",children:[i.jsxs("div",{id:`header-${B}`,className:"flex items-center justify-between mb-4 bg-white dark:bg-slate-800 p-2 rounded shadow-sm border border-slate-200 dark:border-slate-700",children:[i.jsx("span",{className:"font-semibold text-sm text-slate-700 dark:text-slate-200",children:R.splitColumn||"Total"}),i.jsxs("div",{className:"flex items-center gap-1",children:[B===p.length-1&&i.jsx("button",{onClick:F=>K(B,F),className:` diff --git a/static/ml_canvas/assets/GeoDistanceSettings-q_f9JrLj.js b/static/ml_canvas/assets/GeoDistanceSettings-B1xj7Hl4.js similarity index 98% rename from static/ml_canvas/assets/GeoDistanceSettings-q_f9JrLj.js rename to static/ml_canvas/assets/GeoDistanceSettings-B1xj7Hl4.js index a70a3a40b..763a49776 100644 --- a/static/ml_canvas/assets/GeoDistanceSettings-q_f9JrLj.js +++ b/static/ml_canvas/assets/GeoDistanceSettings-B1xj7Hl4.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as g}from"./vendor-utils-_6D5wMFs.js";import{c as v,e as y,f as C,g as j,h as $,i as k,k as D,V as p}from"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";function w(s){var b,N;const t=(b=v(s||"").find(a=>a.datasetId))==null?void 0:b.datasetId,{data:n,isLoading:c}=y(t),i=C(s),r=j(a=>a.nodes),o=j(a=>a.edges),d=j(a=>a.predictedSchemas),x=g.useMemo(()=>$(s,r,o),[s,r,o]),u=(N=o.find(a=>a.target===s))==null?void 0:N.source,m=u?d[u]:void 0,f=(m?m.columns.map(a=>({name:a,dtype:m.dtypes[a]??""})):Object.values((n==null?void 0:n.columns)??{})).filter(a=>/^(?:u?int\d*|float\d*|double|long|short|number|decimal(?:\([^)]*\))?)$/i.test(a.dtype)).filter(a=>!i.has(a.name)&&!x.has(a.name)).map(a=>a.name);return{datasetId:t,numericColumns:f,isLoading:c&&!m}}const h="w-full min-w-0 px-2 py-1.5 text-sm border rounded bg-background";function S({label:s,field:l,value:t,columns:n,isLoading:c,onChange:i}){const r=g.useId();return e.jsxs(p,{field:l,className:"space-y-1",children:[e.jsx("label",{htmlFor:r,className:"block text-xs font-medium",children:s}),e.jsxs("select",{id:r,className:h,value:t,disabled:c,onChange:o=>i(o.target.value),children:[e.jsx("option",{value:"",children:"Select a numeric column"}),t&&!n.includes(t)&&e.jsxs("option",{value:t,disabled:!0,children:[t," (unavailable)"]}),n.map(o=>e.jsx("option",{value:o,children:o},o))]})]})}function _({config:s,onChange:l}){const t=g.useId();return e.jsxs("div",{className:"min-w-0 space-y-4",children:[e.jsxs(p,{field:"method",className:"space-y-1",children:[e.jsx("label",{htmlFor:`${t}-method`,className:"block text-xs font-medium",children:"Distance method"}),e.jsxs("select",{id:`${t}-method`,"aria-describedby":`${t}-method-help`,className:h,value:s.method,onChange:n=>l({...s,method:n.target.value}),children:[e.jsx("option",{value:"haversine",children:"Haversine (great-circle)"}),e.jsx("option",{value:"euclidean",children:"Euclidean (local approximation)"})]}),e.jsx("p",{id:`${t}-method-help`,className:"text-xs text-muted-foreground",children:s.method==="euclidean"?"Flat-earth approximation for nearby points. Use Haversine for longer distances or points across the date line.":"Great-circle distance along the Earth's surface. Recommended for geographic coordinates."})]}),e.jsxs(p,{field:"unit",className:"space-y-1",children:[e.jsx("label",{htmlFor:`${t}-unit`,className:"block text-xs font-medium",children:"Distance unit"}),e.jsxs("select",{id:`${t}-unit`,className:h,value:s.unit,onChange:n=>l({...s,unit:n.target.value}),children:[e.jsx("option",{value:"km",children:"Kilometres (km)"}),e.jsx("option",{value:"mi",children:"Miles (mi)"})]})]}),e.jsxs(p,{field:"output_column",className:"space-y-1",children:[e.jsx("label",{htmlFor:`${t}-output`,className:"block text-xs font-medium",children:"Output column (optional)"}),e.jsx("input",{id:`${t}-output`,type:"text",className:h,value:s.output_column??"",placeholder:`geo_distance_${s.unit}`,"aria-describedby":`${t}-output-help`,onChange:n=>l({...s,output_column:n.target.value})}),e.jsxs("p",{id:`${t}-output-help`,className:"text-xs text-muted-foreground",children:["Leave blank to use ",e.jsxs("span",{className:"break-all",children:["geo_distance_",s.unit]}),"."," ","An existing column with this name is replaced; other columns are kept."]})]})]})}function O({config:s,onChange:l,nodeId:t}){const{datasetId:n,numericColumns:c,isLoading:i}=w(t),[r,o]=k();return e.jsxs("div",{ref:r,className:"w-full min-w-0 p-4 space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose latitude and longitude in degrees for each point. Each row produces one distance."}),!n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connect a dataset node to see available columns."}),i&&e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"Loading columns..."}),!i&&c.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No numeric columns available."}),e.jsxs("div",{className:`grid gap-4 ${o?"grid-cols-2":"grid-cols-1"}`,children:[e.jsx("div",{className:"min-w-0 space-y-4",children:D.map(({field:d,label:x})=>e.jsx(S,{field:d,label:x,columns:c,value:s[d]??"",isLoading:i,onChange:u=>l({...s,[d]:u})},d))}),e.jsx(_,{config:s,onChange:l})]})]})}export{O as default}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as g}from"./vendor-utils-_6D5wMFs.js";import{c as v,e as y,f as C,g as j,h as $,i as k,k as D,V as p}from"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";function w(s){var b,N;const t=(b=v(s||"").find(a=>a.datasetId))==null?void 0:b.datasetId,{data:n,isLoading:c}=y(t),i=C(s),r=j(a=>a.nodes),o=j(a=>a.edges),d=j(a=>a.predictedSchemas),x=g.useMemo(()=>$(s,r,o),[s,r,o]),u=(N=o.find(a=>a.target===s))==null?void 0:N.source,m=u?d[u]:void 0,f=(m?m.columns.map(a=>({name:a,dtype:m.dtypes[a]??""})):Object.values((n==null?void 0:n.columns)??{})).filter(a=>/^(?:u?int\d*|float\d*|double|long|short|number|decimal(?:\([^)]*\))?)$/i.test(a.dtype)).filter(a=>!i.has(a.name)&&!x.has(a.name)).map(a=>a.name);return{datasetId:t,numericColumns:f,isLoading:c&&!m}}const h="w-full min-w-0 px-2 py-1.5 text-sm border rounded bg-background";function S({label:s,field:l,value:t,columns:n,isLoading:c,onChange:i}){const r=g.useId();return e.jsxs(p,{field:l,className:"space-y-1",children:[e.jsx("label",{htmlFor:r,className:"block text-xs font-medium",children:s}),e.jsxs("select",{id:r,className:h,value:t,disabled:c,onChange:o=>i(o.target.value),children:[e.jsx("option",{value:"",children:"Select a numeric column"}),t&&!n.includes(t)&&e.jsxs("option",{value:t,disabled:!0,children:[t," (unavailable)"]}),n.map(o=>e.jsx("option",{value:o,children:o},o))]})]})}function _({config:s,onChange:l}){const t=g.useId();return e.jsxs("div",{className:"min-w-0 space-y-4",children:[e.jsxs(p,{field:"method",className:"space-y-1",children:[e.jsx("label",{htmlFor:`${t}-method`,className:"block text-xs font-medium",children:"Distance method"}),e.jsxs("select",{id:`${t}-method`,"aria-describedby":`${t}-method-help`,className:h,value:s.method,onChange:n=>l({...s,method:n.target.value}),children:[e.jsx("option",{value:"haversine",children:"Haversine (great-circle)"}),e.jsx("option",{value:"euclidean",children:"Euclidean (local approximation)"})]}),e.jsx("p",{id:`${t}-method-help`,className:"text-xs text-muted-foreground",children:s.method==="euclidean"?"Flat-earth approximation for nearby points. Use Haversine for longer distances or points across the date line.":"Great-circle distance along the Earth's surface. Recommended for geographic coordinates."})]}),e.jsxs(p,{field:"unit",className:"space-y-1",children:[e.jsx("label",{htmlFor:`${t}-unit`,className:"block text-xs font-medium",children:"Distance unit"}),e.jsxs("select",{id:`${t}-unit`,className:h,value:s.unit,onChange:n=>l({...s,unit:n.target.value}),children:[e.jsx("option",{value:"km",children:"Kilometres (km)"}),e.jsx("option",{value:"mi",children:"Miles (mi)"})]})]}),e.jsxs(p,{field:"output_column",className:"space-y-1",children:[e.jsx("label",{htmlFor:`${t}-output`,className:"block text-xs font-medium",children:"Output column (optional)"}),e.jsx("input",{id:`${t}-output`,type:"text",className:h,value:s.output_column??"",placeholder:`geo_distance_${s.unit}`,"aria-describedby":`${t}-output-help`,onChange:n=>l({...s,output_column:n.target.value})}),e.jsxs("p",{id:`${t}-output-help`,className:"text-xs text-muted-foreground",children:["Leave blank to use ",e.jsxs("span",{className:"break-all",children:["geo_distance_",s.unit]}),"."," ","An existing column with this name is replaced; other columns are kept."]})]})]})}function O({config:s,onChange:l,nodeId:t}){const{datasetId:n,numericColumns:c,isLoading:i}=w(t),[r,o]=k();return e.jsxs("div",{ref:r,className:"w-full min-w-0 p-4 space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose latitude and longitude in degrees for each point. Each row produces one distance."}),!n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connect a dataset node to see available columns."}),i&&e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"Loading columns..."}),!i&&c.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No numeric columns available."}),e.jsxs("div",{className:`grid gap-4 ${o?"grid-cols-2":"grid-cols-1"}`,children:[e.jsx("div",{className:"min-w-0 space-y-4",children:D.map(({field:d,label:x})=>e.jsx(S,{field:d,label:x,columns:c,value:s[d]??"",isLoading:i,onChange:u=>l({...s,[d]:u})},d))}),e.jsx(_,{config:s,onChange:l})]})]})}export{O as default}; diff --git a/static/ml_canvas/assets/InferencePage-CxgKkiJo.js b/static/ml_canvas/assets/InferencePage-D5u_4kVQ.js similarity index 99% rename from static/ml_canvas/assets/InferencePage-CxgKkiJo.js rename to static/ml_canvas/assets/InferencePage-D5u_4kVQ.js index 53730ba09..951db2884 100644 --- a/static/ml_canvas/assets/InferencePage-CxgKkiJo.js +++ b/static/ml_canvas/assets/InferencePage-D5u_4kVQ.js @@ -1,4 +1,4 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as d,Z as _e,e as me,B as Oe,P as jt,f as Q,I as he,X as De,U as Pe,J as Le,K as pe,W as wt,N as be,O as Je,m as Ve,h as Ue,Q as kt,V as Nt,Y as vt,_ as St,$ as Ct,D as Rt}from"./vendor-utils-_6D5wMFs.js";import{d as fe,D as Ee,t as M,j as It,B as Ot,a as Et,G as Ft,b as Mt,E as Tt}from"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";const se=`[ +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as d,Z as _e,e as me,B as Oe,P as jt,f as Q,I as he,X as De,U as Pe,J as Le,K as pe,W as wt,N as be,O as Je,m as Ve,h as Ue,Q as kt,V as Nt,Y as vt,_ as St,$ as Ct,D as Rt}from"./vendor-utils-_6D5wMFs.js";import{d as fe,D as Ee,t as M,j as It,B as Ot,a as Et,G as Ft,b as Mt,E as Tt}from"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";const se=`[ { "feature1": 0.5, "feature2": 1.2 diff --git a/static/ml_canvas/assets/ModelRegistry-lyme2_ha.js b/static/ml_canvas/assets/ModelRegistry-B8Vj7yFC.js similarity index 99% rename from static/ml_canvas/assets/ModelRegistry-lyme2_ha.js rename to static/ml_canvas/assets/ModelRegistry-B8Vj7yFC.js index 4f1768f5a..d0d4cd16c 100644 --- a/static/ml_canvas/assets/ModelRegistry-lyme2_ha.js +++ b/static/ml_canvas/assets/ModelRegistry-B8Vj7yFC.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as d,A as q,B,e as L,l as ne,F as de,m as oe,n as ce,o as xe,p as me}from"./vendor-utils-_6D5wMFs.js";import{Q as pe,l as ue,n as he,o as ge,q as G,r as fe,s as be,w as S,a as ye,u as je,p as ke,L as Ne,E as $,b as ve,R as P,M as H,t as U}from"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";var we=class extends pe{constructor(s,l){super(s,l)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){s._type="infinite",super.setOptions(s)}getOptimisticResult(s){return s._type="infinite",super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,l){var b,p;const{state:c}=s,r=super.createResult(s,l),{isFetching:j,isRefetching:m,isError:o,isRefetchError:w}=r,g=(p=(b=c.fetchMeta)==null?void 0:b.fetchMore)==null?void 0:p.direction,u=o&&g==="forward",k=j&&g==="forward",f=o&&g==="backward",x=j&&g==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:he(l,c.data),hasPreviousPage:ue(l,c.data),isFetchNextPageError:u,isFetchingNextPage:k,isFetchPreviousPageError:f,isFetchingPreviousPage:x,isRefetchError:w&&!u&&!f,isRefetching:m&&!k&&!x}}};function _e(s,l){return ge(s,we)}const h={all:["registry"],stats:()=>[...h.all,"stats"],models:()=>[...h.all,"models"],artifacts:s=>[...h.all,"artifacts",s]},Pe=3e4,D=10,Se=s=>{s.invalidateQueries({queryKey:h.models()}),s.invalidateQueries({queryKey:h.stats()})},Ce=()=>G({queryKey:h.stats(),queryFn:async()=>(await S.get("/registry/stats")).data,staleTime:Pe}),Me=()=>_e({queryKey:h.models(),initialPageParam:0,queryFn:async({pageParam:s})=>{const l=s*D,c=new URLSearchParams({skip:String(l),limit:String(D)});return(await S.get(`/registry/models?${c.toString()}`)).data},getNextPageParam:(s,l)=>s.lengthG({queryKey:s?h.artifacts(s):["registry","artifacts","idle"],enabled:!!s,queryFn:async()=>(await S.get(`/registry/artifacts/${s}`)).data}),Fe=()=>{const s=fe();return be({mutationFn:async l=>(await S.post(`/deployment/deploy/${l}`)).data,onSuccess:()=>Se(s)})},Le=s=>!s||s.toLowerCase()==="unknown",$e=20,Oe=()=>{const s=ye(),[l]=je(),c=Ce(),r=Me(),j=Fe(),m=c.data??null,o=d.useMemo(()=>{var t;return((t=r.data)==null?void 0:t.pages.flat())??[]},[r.data]),w=r.isFetching,g=r.error?r.error.message:null,u=r.hasNextPage??!1,[k,f]=d.useState(null),x=d.useMemo(()=>k?o.find(t=>`${t.model_type}-${t.dataset_id}`===k)??null:null,[k,o]),E=j.isPending?j.variables??null:null,b=d.useMemo(()=>ke(l),[l]),p=(b==null?void 0:b.ref.kind)==="modelVersion"?b.ref.jobId:null,C=d.useRef(null),[J,I]=d.useState(!1);d.useEffect(()=>{var a;if(!p||C.current===p)return;const t=o.find(i=>i.versions.some(n=>n.job_id===p));if(t){C.current=p,f(`${t.model_type}-${t.dataset_id}`),I(!1);return}if(u&&!r.isFetchingNextPage&&(((a=r.data)==null?void 0:a.pages.length)??0)<$e){r.fetchNextPage();return}u||(C.current=p,I(!0))},[p,o,u,r]);const[z,M]=d.useState(null),T=Re(z),y=T.data??null,W=T.isFetching,[R,X]=d.useState(""),[O,Z]=d.useState(""),[N,_]=d.useState(null),Y=t=>{M(t)},Q=d.useRef(null);d.useEffect(()=>{const t=Q.current;if(!t)return;const a=new IntersectionObserver(i=>{var n;(n=i[0])!=null&&n.isIntersecting&&!r.isFetchingNextPage&&u&&r.fetchNextPage()});return a.observe(t),()=>{a.disconnect()}},[r,u]);const ee=async(t,a)=>{const i=a&&a.job_id!==t.job_id?` This replaces the currently active version ${a.version} (job ${a.job_id}).`:"";await s({title:"Deploy model version?",message:`Deploy version ${t.version} (job ${t.job_id}) of ${t.model_type}?${i}`,confirmLabel:"Deploy",variant:"danger"})&&await V(t)},V=async t=>{_(null);try{await j.mutateAsync(t.job_id),U.success("Model deployed",`Version ${t.version} (job ${t.job_id}) is now active.`)}catch(a){const i=a.message||"Deploy failed.";_({jobId:t.job_id,version:t.version,message:i}),U.error(`Failed to deploy version ${t.version}`,i)}},K=t=>{switch(t.toLowerCase()){case"completed":return"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400";case"failed":return"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400";case"running":return"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400";default:return"bg-gray-100 text-gray-800 dark:bg-slate-700 dark:text-slate-300"}},te=t=>{const a=t.score||t.accuracy||t.f1_score||t.rmse||t.mse;if(a!==void 0)return typeof a=="number"?a.toFixed(4):String(a);const n=Object.keys(t)[0];if(n){const v=t[n];return`${n}: ${typeof v=="number"?v.toFixed(4):v}`}return"-"},se=t=>t.toLowerCase()==="tuning"?"Advanced Training":t.toLowerCase()==="training"?"Standard Training":t.charAt(0).toUpperCase()+t.slice(1),F=o.filter(t=>{const a=(t.dataset_name||"").toLowerCase().includes(R.toLowerCase())||(t.dataset_id||"").toLowerCase().includes(R.toLowerCase()),i=t.model_type.toLowerCase().includes(O.toLowerCase());return a&&i}),ae=()=>e.jsxs("div",{className:"p-6",children:[" ",W?e.jsxs("div",{className:"flex justify-center py-8 text-slate-500 dark:text-slate-400",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mr-2"}),"Loading artifacts..."]}):!y||y.files.length===0?e.jsx("div",{className:"text-center py-8 text-slate-500 dark:text-slate-400",children:"No artifacts found."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-100 dark:border-blue-800",children:[y.storage_type==="s3"?e.jsx(ce,{size:20,className:"text-blue-600 dark:text-blue-400 flex-shrink-0"}):e.jsx(xe,{size:20,className:"text-slate-600 dark:text-slate-400 flex-shrink-0"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-blue-700 dark:text-blue-300",children:y.storage_type==="s3"?"S3 Bucket Storage":"Local Storage"}),e.jsx("span",{className:"text-xs font-mono text-slate-600 dark:text-slate-400 truncate",title:y.base_uri,children:y.base_uri})]})]}),e.jsx("ul",{className:"space-y-2",children:y.files.map((t,a)=>e.jsxs("li",{className:"flex items-center gap-3 p-3 rounded-lg bg-slate-50 dark:bg-slate-700/30 border border-slate-100 dark:border-slate-700",children:[e.jsx(me,{size:18,className:"text-slate-400"}),e.jsx("span",{className:"text-sm font-mono text-slate-700 dark:text-slate-300 break-all",children:t})]},a))})]})]}),re=()=>e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-8",children:[e.jsx(A,{title:"Total Versions",value:(m==null?void 0:m.total_versions)||0,icon:e.jsx(B,{className:"text-blue-500"})}),e.jsx(A,{title:"Active Deployments",value:(m==null?void 0:m.active_deployments)||0,icon:e.jsx(De,{className:"text-green-500"}),valueColor:"text-green-600 dark:text-green-400"}),e.jsx(A,{title:"Model Types",value:o.length,icon:e.jsx(q,{className:"text-purple-500"}),valueColor:"text-purple-600 dark:text-purple-400"})]}),le=()=>e.jsx(H,{isOpen:!!x,onClose:()=>{f(null),_(null)},title:x==null?void 0:x.model_type,size:"4xl",footer:e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{onClick:()=>{f(null),_(null)},className:"px-4 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-md text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors",children:"Close"})}),children:x&&e.jsxs("div",{className:"p-6",children:[e.jsx("p",{className:"text-sm text-slate-500 dark:text-slate-400 mb-4",children:"Version History"}),N&&e.jsx("div",{className:"mb-4",children:e.jsx($,{error:`Failed to deploy version ${N.version} (job ${N.jobId}): ${N.message}`,onRetry:()=>{const t=x.versions.find(a=>a.job_id===N.jobId);return t?V(t):void 0}})}),e.jsxs("table",{className:"min-w-full divide-y divide-slate-200 dark:divide-slate-700",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Version"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Job"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Date"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Metrics"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Status"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Action"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-200 dark:divide-slate-700",children:x.versions.map(t=>{const a=x.versions.find(n=>n.is_deployed)??null,i=E===t.job_id;return e.jsxs("tr",{className:`hover:bg-slate-50 dark:hover:bg-slate-700/30 ${t.is_deployed?"bg-green-50/50 dark:bg-green-900/10":""}`,children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm font-medium text-slate-900 dark:text-white",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-mono",children:["v",t.version]}),t.is_deployed&&e.jsx("span",{className:"text-xs bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-1.5 py-0.5 rounded border border-green-200 dark:border-green-800",children:"Deployed"})]})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm",children:e.jsx(P,{recordRef:{kind:"job",jobId:t.job_id},label:t.job_id.slice(0,8),origin:"/registry"})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:new Date(t.created_at).toLocaleString()}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm text-slate-600 dark:text-slate-300 font-mono",children:te(t.metrics)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsx("span",{className:`px-2 py-0.5 inline-flex text-xs leading-5 font-semibold rounded-full ${K(t.status)}`,children:t.status})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-right text-sm font-medium",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>{Y(t.job_id)},className:"text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200",title:"View Artifacts",children:e.jsx(de,{size:16})}),t.status==="completed"&&!t.is_deployed&&e.jsxs("button",{onClick:()=>{ee(t,a)},disabled:i,"aria-label":`Deploy version ${t.version} (job ${t.job_id})`,className:"text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 disabled:opacity-50 flex items-center gap-1",children:[i?e.jsx("span",{className:"animate-spin h-3 w-3 border-b-2 border-current rounded-full"}):e.jsx(oe,{size:14}),"Deploy"]}),t.is_deployed&&(t.deployment_id!==void 0?e.jsx(P,{recordRef:{kind:"deployment",deploymentId:t.deployment_id},label:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(L,{size:14})," Active"]}),origin:"/registry",className:"text-xs"}):e.jsxs("span",{className:"text-green-600 dark:text-green-400 text-xs flex items-center gap-1",children:[e.jsx(L,{size:14})," Active"]}))]})})]},t.job_id)})})]})]})});return w&&!m&&o.length===0?e.jsx("div",{className:"p-8",children:e.jsx(Ne,{message:"Loading registry..."})}):g?e.jsx("div",{className:"p-8",children:e.jsx($,{error:g,onRetry:()=>r.refetch()})}):e.jsxs("div",{className:"p-8 min-h-screen bg-slate-50 dark:bg-slate-900 text-slate-900 dark:text-slate-100 transition-colors duration-200",children:[e.jsxs("div",{className:"mb-8 flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight text-slate-900 dark:text-white",children:"Model Registry"}),e.jsx("p",{className:"text-slate-600 dark:text-slate-400 mt-1",children:"Manage versions, track metrics, and deploy your best models."})]}),e.jsx("button",{onClick:()=>{r.refetch(),c.refetch()},className:"px-4 py-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-md text-sm font-medium hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors shadow-sm",children:"Refresh"})]}),re(),J&&e.jsx("div",{className:"mb-6",children:e.jsx($,{error:"The linked model version could not be found in the registry. It may have been removed, or is on a page not yet loaded."})}),e.jsxs("div",{className:"mb-6 flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1",children:"Filter by Model Type"}),e.jsx("input",{type:"text",placeholder:"e.g. RandomForest",value:O,onChange:t=>{Z(t.target.value)},className:"w-full px-4 py-2 rounded-md border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1",children:"Filter by Dataset"}),e.jsx("input",{type:"text",placeholder:"e.g. Iris Dataset",value:R,onChange:t=>{X(t.target.value)},className:"w-full px-4 py-2 rounded-md border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]})]}),e.jsxs("div",{className:"bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/50",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(q,{size:20,className:"text-slate-400"}),"Registered Models"]}),e.jsxs("span",{className:"text-sm text-slate-500 dark:text-slate-400",children:["Showing ",F.length," of ",o.length," models"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-slate-200 dark:divide-slate-700",children:[e.jsx("thead",{className:"bg-slate-50 dark:bg-slate-900/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Model Type"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Dataset"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Latest Version"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Source"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Created At"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Status"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Deployments"}),e.jsx("th",{className:"px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Actions"})]})}),e.jsx("tbody",{className:"bg-white dark:bg-slate-800 divide-y divide-slate-200 dark:divide-slate-700",children:F.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:e.jsx(ve,{icon:e.jsx(B,{size:48,className:"text-slate-300 dark:text-slate-600"}),title:"No models found matching your filters."})})}):F.map(t=>{const a=t.latest_version;if(!a)return null;const i=`${t.model_type}-${t.dataset_id}`,n=t.versions.find(ie=>ie.is_deployed)??null,v=!Le(t.dataset_id);return e.jsxs("tr",{className:"hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors",children:[e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm font-medium text-slate-900 dark:text-white",children:t.model_type}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:e.jsx("div",{className:"flex flex-col",children:e.jsxs("div",{className:"flex items-center gap-2",children:[v?e.jsx(P,{recordRef:{kind:"dataset",datasetId:t.dataset_id},label:t.dataset_name,className:"font-medium"}):e.jsx("span",{className:"font-medium text-slate-700 dark:text-slate-300",title:"No target available",children:t.dataset_name||"Unknown dataset"}),t.dataset_type&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-slate-600 uppercase",children:t.dataset_type})]})})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:e.jsxs("span",{className:"font-mono bg-slate-100 dark:bg-slate-700 px-2 py-1 rounded text-xs",children:["v",a.version]})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:se(a.source)}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:new Date(a.created_at).toLocaleDateString()}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx("span",{className:`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${K(a.status)}`,children:a.status})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm",children:n?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-green-600 dark:text-green-400 font-medium bg-green-50 dark:bg-green-900/20 px-2 py-1 rounded-full text-xs",children:[e.jsx(L,{size:12})," Active"]}),n.deployment_id!==void 0?e.jsx(P,{recordRef:{kind:"deployment",deploymentId:n.deployment_id},label:`v${n.version}`,origin:"/registry"}):e.jsxs("span",{className:"text-xs text-slate-400 italic",title:"No target available",children:["v",n.version]})]}):e.jsx("span",{className:"text-slate-400 dark:text-slate-600 text-xs",children:"None"})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-right text-sm font-medium",children:e.jsxs("button",{onClick:()=>{f(`${t.model_type}-${t.dataset_id}`)},className:"text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 flex items-center justify-end gap-1 ml-auto",children:["View Versions ",e.jsx(ne,{size:16})]})})]},i)})})]})})]}),e.jsx("div",{ref:Q,className:"h-1","aria-hidden":"true"}),w&&o.length>0&&e.jsxs("div",{className:"py-4 flex justify-center text-slate-500 dark:text-slate-400",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mr-2"}),"Loading more models..."]}),le(),e.jsx(H,{isOpen:!!z,onClose:()=>{M(null)},title:"Artifacts",size:"2xl",zIndex:"z-[60]",footer:e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{onClick:()=>{M(null)},className:"px-4 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-md text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors",children:"Close"})}),children:ae()})]})},A=({title:s,value:l,icon:c,valueColor:r="text-slate-900 dark:text-white"})=>e.jsxs("div",{className:"bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:s}),e.jsx("div",{className:`mt-2 text-3xl font-bold ${r}`,children:l})]}),e.jsx("div",{className:"p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg",children:c})]}),De=({className:s})=>e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),e.jsx("path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),e.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),e.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]});export{Oe as ModelRegistry}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as d,A as q,B,e as L,l as ne,F as de,m as oe,n as ce,o as xe,p as me}from"./vendor-utils-_6D5wMFs.js";import{Q as pe,l as ue,n as he,o as ge,q as G,r as fe,s as be,w as S,a as ye,u as je,p as ke,L as Ne,E as $,b as ve,R as P,M as H,t as U}from"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";var we=class extends pe{constructor(s,l){super(s,l)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){s._type="infinite",super.setOptions(s)}getOptimisticResult(s){return s._type="infinite",super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,l){var b,p;const{state:c}=s,r=super.createResult(s,l),{isFetching:j,isRefetching:m,isError:o,isRefetchError:w}=r,g=(p=(b=c.fetchMeta)==null?void 0:b.fetchMore)==null?void 0:p.direction,u=o&&g==="forward",k=j&&g==="forward",f=o&&g==="backward",x=j&&g==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:he(l,c.data),hasPreviousPage:ue(l,c.data),isFetchNextPageError:u,isFetchingNextPage:k,isFetchPreviousPageError:f,isFetchingPreviousPage:x,isRefetchError:w&&!u&&!f,isRefetching:m&&!k&&!x}}};function _e(s,l){return ge(s,we)}const h={all:["registry"],stats:()=>[...h.all,"stats"],models:()=>[...h.all,"models"],artifacts:s=>[...h.all,"artifacts",s]},Pe=3e4,D=10,Se=s=>{s.invalidateQueries({queryKey:h.models()}),s.invalidateQueries({queryKey:h.stats()})},Ce=()=>G({queryKey:h.stats(),queryFn:async()=>(await S.get("/registry/stats")).data,staleTime:Pe}),Me=()=>_e({queryKey:h.models(),initialPageParam:0,queryFn:async({pageParam:s})=>{const l=s*D,c=new URLSearchParams({skip:String(l),limit:String(D)});return(await S.get(`/registry/models?${c.toString()}`)).data},getNextPageParam:(s,l)=>s.lengthG({queryKey:s?h.artifacts(s):["registry","artifacts","idle"],enabled:!!s,queryFn:async()=>(await S.get(`/registry/artifacts/${s}`)).data}),Fe=()=>{const s=fe();return be({mutationFn:async l=>(await S.post(`/deployment/deploy/${l}`)).data,onSuccess:()=>Se(s)})},Le=s=>!s||s.toLowerCase()==="unknown",$e=20,Oe=()=>{const s=ye(),[l]=je(),c=Ce(),r=Me(),j=Fe(),m=c.data??null,o=d.useMemo(()=>{var t;return((t=r.data)==null?void 0:t.pages.flat())??[]},[r.data]),w=r.isFetching,g=r.error?r.error.message:null,u=r.hasNextPage??!1,[k,f]=d.useState(null),x=d.useMemo(()=>k?o.find(t=>`${t.model_type}-${t.dataset_id}`===k)??null:null,[k,o]),E=j.isPending?j.variables??null:null,b=d.useMemo(()=>ke(l),[l]),p=(b==null?void 0:b.ref.kind)==="modelVersion"?b.ref.jobId:null,C=d.useRef(null),[J,I]=d.useState(!1);d.useEffect(()=>{var a;if(!p||C.current===p)return;const t=o.find(i=>i.versions.some(n=>n.job_id===p));if(t){C.current=p,f(`${t.model_type}-${t.dataset_id}`),I(!1);return}if(u&&!r.isFetchingNextPage&&(((a=r.data)==null?void 0:a.pages.length)??0)<$e){r.fetchNextPage();return}u||(C.current=p,I(!0))},[p,o,u,r]);const[z,M]=d.useState(null),T=Re(z),y=T.data??null,W=T.isFetching,[R,X]=d.useState(""),[O,Z]=d.useState(""),[N,_]=d.useState(null),Y=t=>{M(t)},Q=d.useRef(null);d.useEffect(()=>{const t=Q.current;if(!t)return;const a=new IntersectionObserver(i=>{var n;(n=i[0])!=null&&n.isIntersecting&&!r.isFetchingNextPage&&u&&r.fetchNextPage()});return a.observe(t),()=>{a.disconnect()}},[r,u]);const ee=async(t,a)=>{const i=a&&a.job_id!==t.job_id?` This replaces the currently active version ${a.version} (job ${a.job_id}).`:"";await s({title:"Deploy model version?",message:`Deploy version ${t.version} (job ${t.job_id}) of ${t.model_type}?${i}`,confirmLabel:"Deploy",variant:"danger"})&&await V(t)},V=async t=>{_(null);try{await j.mutateAsync(t.job_id),U.success("Model deployed",`Version ${t.version} (job ${t.job_id}) is now active.`)}catch(a){const i=a.message||"Deploy failed.";_({jobId:t.job_id,version:t.version,message:i}),U.error(`Failed to deploy version ${t.version}`,i)}},K=t=>{switch(t.toLowerCase()){case"completed":return"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400";case"failed":return"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400";case"running":return"bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400";default:return"bg-gray-100 text-gray-800 dark:bg-slate-700 dark:text-slate-300"}},te=t=>{const a=t.score||t.accuracy||t.f1_score||t.rmse||t.mse;if(a!==void 0)return typeof a=="number"?a.toFixed(4):String(a);const n=Object.keys(t)[0];if(n){const v=t[n];return`${n}: ${typeof v=="number"?v.toFixed(4):v}`}return"-"},se=t=>t.toLowerCase()==="tuning"?"Advanced Training":t.toLowerCase()==="training"?"Standard Training":t.charAt(0).toUpperCase()+t.slice(1),F=o.filter(t=>{const a=(t.dataset_name||"").toLowerCase().includes(R.toLowerCase())||(t.dataset_id||"").toLowerCase().includes(R.toLowerCase()),i=t.model_type.toLowerCase().includes(O.toLowerCase());return a&&i}),ae=()=>e.jsxs("div",{className:"p-6",children:[" ",W?e.jsxs("div",{className:"flex justify-center py-8 text-slate-500 dark:text-slate-400",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mr-2"}),"Loading artifacts..."]}):!y||y.files.length===0?e.jsx("div",{className:"text-center py-8 text-slate-500 dark:text-slate-400",children:"No artifacts found."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-100 dark:border-blue-800",children:[y.storage_type==="s3"?e.jsx(ce,{size:20,className:"text-blue-600 dark:text-blue-400 flex-shrink-0"}):e.jsx(xe,{size:20,className:"text-slate-600 dark:text-slate-400 flex-shrink-0"}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-blue-700 dark:text-blue-300",children:y.storage_type==="s3"?"S3 Bucket Storage":"Local Storage"}),e.jsx("span",{className:"text-xs font-mono text-slate-600 dark:text-slate-400 truncate",title:y.base_uri,children:y.base_uri})]})]}),e.jsx("ul",{className:"space-y-2",children:y.files.map((t,a)=>e.jsxs("li",{className:"flex items-center gap-3 p-3 rounded-lg bg-slate-50 dark:bg-slate-700/30 border border-slate-100 dark:border-slate-700",children:[e.jsx(me,{size:18,className:"text-slate-400"}),e.jsx("span",{className:"text-sm font-mono text-slate-700 dark:text-slate-300 break-all",children:t})]},a))})]})]}),re=()=>e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-8",children:[e.jsx(A,{title:"Total Versions",value:(m==null?void 0:m.total_versions)||0,icon:e.jsx(B,{className:"text-blue-500"})}),e.jsx(A,{title:"Active Deployments",value:(m==null?void 0:m.active_deployments)||0,icon:e.jsx(De,{className:"text-green-500"}),valueColor:"text-green-600 dark:text-green-400"}),e.jsx(A,{title:"Model Types",value:o.length,icon:e.jsx(q,{className:"text-purple-500"}),valueColor:"text-purple-600 dark:text-purple-400"})]}),le=()=>e.jsx(H,{isOpen:!!x,onClose:()=>{f(null),_(null)},title:x==null?void 0:x.model_type,size:"4xl",footer:e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{onClick:()=>{f(null),_(null)},className:"px-4 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-md text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors",children:"Close"})}),children:x&&e.jsxs("div",{className:"p-6",children:[e.jsx("p",{className:"text-sm text-slate-500 dark:text-slate-400 mb-4",children:"Version History"}),N&&e.jsx("div",{className:"mb-4",children:e.jsx($,{error:`Failed to deploy version ${N.version} (job ${N.jobId}): ${N.message}`,onRetry:()=>{const t=x.versions.find(a=>a.job_id===N.jobId);return t?V(t):void 0}})}),e.jsxs("table",{className:"min-w-full divide-y divide-slate-200 dark:divide-slate-700",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Version"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Job"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Date"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Metrics"}),e.jsx("th",{className:"px-4 py-2 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Status"}),e.jsx("th",{className:"px-4 py-2 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase",children:"Action"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-200 dark:divide-slate-700",children:x.versions.map(t=>{const a=x.versions.find(n=>n.is_deployed)??null,i=E===t.job_id;return e.jsxs("tr",{className:`hover:bg-slate-50 dark:hover:bg-slate-700/30 ${t.is_deployed?"bg-green-50/50 dark:bg-green-900/10":""}`,children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm font-medium text-slate-900 dark:text-white",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-mono",children:["v",t.version]}),t.is_deployed&&e.jsx("span",{className:"text-xs bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 px-1.5 py-0.5 rounded border border-green-200 dark:border-green-800",children:"Deployed"})]})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm",children:e.jsx(P,{recordRef:{kind:"job",jobId:t.job_id},label:t.job_id.slice(0,8),origin:"/registry"})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:new Date(t.created_at).toLocaleString()}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-sm text-slate-600 dark:text-slate-300 font-mono",children:te(t.metrics)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsx("span",{className:`px-2 py-0.5 inline-flex text-xs leading-5 font-semibold rounded-full ${K(t.status)}`,children:t.status})}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-right text-sm font-medium",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>{Y(t.job_id)},className:"text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200",title:"View Artifacts",children:e.jsx(de,{size:16})}),t.status==="completed"&&!t.is_deployed&&e.jsxs("button",{onClick:()=>{ee(t,a)},disabled:i,"aria-label":`Deploy version ${t.version} (job ${t.job_id})`,className:"text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 disabled:opacity-50 flex items-center gap-1",children:[i?e.jsx("span",{className:"animate-spin h-3 w-3 border-b-2 border-current rounded-full"}):e.jsx(oe,{size:14}),"Deploy"]}),t.is_deployed&&(t.deployment_id!==void 0?e.jsx(P,{recordRef:{kind:"deployment",deploymentId:t.deployment_id},label:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(L,{size:14})," Active"]}),origin:"/registry",className:"text-xs"}):e.jsxs("span",{className:"text-green-600 dark:text-green-400 text-xs flex items-center gap-1",children:[e.jsx(L,{size:14})," Active"]}))]})})]},t.job_id)})})]})]})});return w&&!m&&o.length===0?e.jsx("div",{className:"p-8",children:e.jsx(Ne,{message:"Loading registry..."})}):g?e.jsx("div",{className:"p-8",children:e.jsx($,{error:g,onRetry:()=>r.refetch()})}):e.jsxs("div",{className:"p-8 min-h-screen bg-slate-50 dark:bg-slate-900 text-slate-900 dark:text-slate-100 transition-colors duration-200",children:[e.jsxs("div",{className:"mb-8 flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold tracking-tight text-slate-900 dark:text-white",children:"Model Registry"}),e.jsx("p",{className:"text-slate-600 dark:text-slate-400 mt-1",children:"Manage versions, track metrics, and deploy your best models."})]}),e.jsx("button",{onClick:()=>{r.refetch(),c.refetch()},className:"px-4 py-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-md text-sm font-medium hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors shadow-sm",children:"Refresh"})]}),re(),J&&e.jsx("div",{className:"mb-6",children:e.jsx($,{error:"The linked model version could not be found in the registry. It may have been removed, or is on a page not yet loaded."})}),e.jsxs("div",{className:"mb-6 flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1",children:"Filter by Model Type"}),e.jsx("input",{type:"text",placeholder:"e.g. RandomForest",value:O,onChange:t=>{Z(t.target.value)},className:"w-full px-4 py-2 rounded-md border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1",children:"Filter by Dataset"}),e.jsx("input",{type:"text",placeholder:"e.g. Iris Dataset",value:R,onChange:t=>{X(t.target.value)},className:"w-full px-4 py-2 rounded-md border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]})]}),e.jsxs("div",{className:"bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center bg-slate-50/50 dark:bg-slate-800/50",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(q,{size:20,className:"text-slate-400"}),"Registered Models"]}),e.jsxs("span",{className:"text-sm text-slate-500 dark:text-slate-400",children:["Showing ",F.length," of ",o.length," models"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full divide-y divide-slate-200 dark:divide-slate-700",children:[e.jsx("thead",{className:"bg-slate-50 dark:bg-slate-900/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Model Type"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Dataset"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Latest Version"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Source"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Created At"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Status"}),e.jsx("th",{className:"px-6 py-3 text-left text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Deployments"}),e.jsx("th",{className:"px-6 py-3 text-right text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:"Actions"})]})}),e.jsx("tbody",{className:"bg-white dark:bg-slate-800 divide-y divide-slate-200 dark:divide-slate-700",children:F.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:e.jsx(ve,{icon:e.jsx(B,{size:48,className:"text-slate-300 dark:text-slate-600"}),title:"No models found matching your filters."})})}):F.map(t=>{const a=t.latest_version;if(!a)return null;const i=`${t.model_type}-${t.dataset_id}`,n=t.versions.find(ie=>ie.is_deployed)??null,v=!Le(t.dataset_id);return e.jsxs("tr",{className:"hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors",children:[e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm font-medium text-slate-900 dark:text-white",children:t.model_type}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:e.jsx("div",{className:"flex flex-col",children:e.jsxs("div",{className:"flex items-center gap-2",children:[v?e.jsx(P,{recordRef:{kind:"dataset",datasetId:t.dataset_id},label:t.dataset_name,className:"font-medium"}):e.jsx("span",{className:"font-medium text-slate-700 dark:text-slate-300",title:"No target available",children:t.dataset_name||"Unknown dataset"}),t.dataset_type&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-medium bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400 border border-slate-200 dark:border-slate-600 uppercase",children:t.dataset_type})]})})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:e.jsxs("span",{className:"font-mono bg-slate-100 dark:bg-slate-700 px-2 py-1 rounded text-xs",children:["v",a.version]})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:se(a.source)}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm text-slate-500 dark:text-slate-400",children:new Date(a.created_at).toLocaleDateString()}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap",children:e.jsx("span",{className:`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${K(a.status)}`,children:a.status})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-sm",children:n?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-green-600 dark:text-green-400 font-medium bg-green-50 dark:bg-green-900/20 px-2 py-1 rounded-full text-xs",children:[e.jsx(L,{size:12})," Active"]}),n.deployment_id!==void 0?e.jsx(P,{recordRef:{kind:"deployment",deploymentId:n.deployment_id},label:`v${n.version}`,origin:"/registry"}):e.jsxs("span",{className:"text-xs text-slate-400 italic",title:"No target available",children:["v",n.version]})]}):e.jsx("span",{className:"text-slate-400 dark:text-slate-600 text-xs",children:"None"})}),e.jsx("td",{className:"px-6 py-4 whitespace-nowrap text-right text-sm font-medium",children:e.jsxs("button",{onClick:()=>{f(`${t.model_type}-${t.dataset_id}`)},className:"text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 flex items-center justify-end gap-1 ml-auto",children:["View Versions ",e.jsx(ne,{size:16})]})})]},i)})})]})})]}),e.jsx("div",{ref:Q,className:"h-1","aria-hidden":"true"}),w&&o.length>0&&e.jsxs("div",{className:"py-4 flex justify-center text-slate-500 dark:text-slate-400",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mr-2"}),"Loading more models..."]}),le(),e.jsx(H,{isOpen:!!z,onClose:()=>{M(null)},title:"Artifacts",size:"2xl",zIndex:"z-[60]",footer:e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{onClick:()=>{M(null)},className:"px-4 py-2 bg-white dark:bg-slate-800 border border-slate-300 dark:border-slate-600 rounded-md text-sm font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors",children:"Close"})}),children:ae()})]})},A=({title:s,value:l,icon:c,valueColor:r="text-slate-900 dark:text-white"})=>e.jsxs("div",{className:"bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wider",children:s}),e.jsx("div",{className:`mt-2 text-3xl font-bold ${r}`,children:l})]}),e.jsx("div",{className:"p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg",children:c})]}),De=({className:s})=>e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),e.jsx("path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),e.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),e.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]});export{Oe as ModelRegistry}; diff --git a/static/ml_canvas/assets/SlowNodesPage-aiRJX30H.js b/static/ml_canvas/assets/SlowNodesPage-CVIoKIrD.js similarity index 99% rename from static/ml_canvas/assets/SlowNodesPage-aiRJX30H.js rename to static/ml_canvas/assets/SlowNodesPage-CVIoKIrD.js index cf2410086..7df2bae66 100644 --- a/static/ml_canvas/assets/SlowNodesPage-aiRJX30H.js +++ b/static/ml_canvas/assets/SlowNodesPage-CVIoKIrD.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as o,T as K,c as U,f as z,L as W,H,h as M,C as Y,i as O,j as _,S as q}from"./vendor-utils-_6D5wMFs.js";import{u as X,m as G,t as J,C as Q,M as V,b as Z,R as ee,N as te}from"./index-BXksgzya.js";import{R as se,B as re,C as ae,X as ne,Y as le,T as ie,h as oe,j as de}from"./vendor-charts-CwfdE1jD.js";const $=[1,7,30,90],F=[10,25,50],ce=["total_seconds","avg_seconds","p95_seconds","count","max_seconds"],xe=t=>t!==null&&ce.includes(t),L=["#3b82f6","#8b5cf6","#ec4899","#f59e0b","#10b981","#06b6d4","#ef4444","#a855f7","#eab308","#14b8a6"],b=t=>{if(t<1)return`${(t*1e3).toFixed(0)} ms`;if(t<60)return`${t.toFixed(2)} s`;const n=Math.floor(t/60),l=t-n*60;return`${n}m ${l.toFixed(1)}s`},me=t=>t?t.replace("T"," ").slice(0,16):"Unknown time",Ne=()=>{const[t,n]=X(),l=Number(t.get("days")),i=Number(t.get("limit")),x=t.get("sort"),s=t.get("investigate"),[r,u]=o.useState($.includes(l)?l:7),[m,k]=o.useState(F.includes(i)?i:10),[c,A]=o.useState(null),[v,S]=o.useState(!1),[C,I]=o.useState(null),[d,g]=o.useState(xe(x)?x:"total_seconds"),[y,R]=o.useState(s),N=o.useRef(0);o.useEffect(()=>{const a=new URLSearchParams;a.set("days",String(r)),a.set("limit",String(m)),a.set("sort",d),y&&a.set("investigate",y),n(a,{replace:!0})},[r,m,d,y]);const w=o.useCallback(async()=>{const a=++N.current;S(!0),I(null);try{const h=await G.getSlowNodes(r,m);if(a!==N.current)return;A(h)}catch(h){if(a!==N.current)return;const T=h.message||"Failed to load slow-nodes telemetry";I(T),J.error(T)}finally{a===N.current&&S(!1)}},[r,m]);o.useEffect(()=>{w()},[w]);const p=o.useMemo(()=>c?[...c.aggregates].sort((a,h)=>h[d]-a[d]):[],[c,d]),P=o.useMemo(()=>p.length===0?1:Math.max(...p.map(a=>a.total_seconds)),[p]),D=o.useMemo(()=>{if(p.length===0)return .001;const a=Math.min(...p.map(h=>h.total_seconds));return Math.max(a*.5,.001)},[p]),E=o.useMemo(()=>({days:String(r),limit:String(m),sort:d}),[r,m,d]),B=o.useMemo(()=>p.find(a=>a.step_type===y)??null,[p,y]);return e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 p-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-semibold text-gray-800 dark:text-gray-100 flex items-center gap-2",children:[e.jsx(K,{className:"w-6 h-6 text-blue-500"}),"Slow Nodes"]}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Workspace-wide step-type runtime aggregated from completed jobs in the last window. Use it to spot the cheapest optimisation wins."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"inline-flex rounded-md overflow-hidden border border-gray-200 dark:border-gray-700",children:$.map(a=>e.jsx("button",{onClick:()=>u(a),className:`px-2.5 py-1 text-xs font-medium tabular-nums border-r last:border-r-0 border-gray-200 dark:border-gray-700 transition-colors ${a===r?"bg-blue-600 text-white":"bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/30"}`,children:a===1?"24 h":`${a} d`},a))}),e.jsx("div",{className:"inline-flex rounded-md overflow-hidden border border-gray-200 dark:border-gray-700",children:F.map(a=>e.jsxs("button",{onClick:()=>k(a),className:`px-2.5 py-1 text-xs font-medium tabular-nums border-r last:border-r-0 border-gray-200 dark:border-gray-700 transition-colors ${a===m?"bg-blue-600 text-white":"bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/30"}`,title:`Show top ${a} step types`,children:["Top ",a]},a))}),e.jsxs("button",{onClick:()=>void w(),disabled:v,className:"flex items-center gap-1.5 text-xs px-3 py-1.5 rounded bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 border border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(U,{className:`w-3 h-3 ${v?"animate-spin":""}`}),"Refresh"]})]})]}),e.jsx(ue,{data:c}),C&&e.jsxs("div",{className:"mb-4 flex items-start gap-2 p-3 rounded border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm",children:[e.jsx(z,{className:"w-4 h-4 shrink-0 mt-0.5"}),e.jsx("span",{children:C})]}),e.jsx(be,{sortedAggregates:p,sortKey:d,chartFloor:D,data:c,days:r}),e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900/40 border-b border-gray-200 dark:border-gray-700",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400",children:"Step type"}),e.jsx(f,{k:"count",label:"Runs",title:"Number of executions",sortKey:d,onSort:g}),e.jsx(f,{k:"total_seconds",label:"Total",title:"Cumulative time across all runs",sortKey:d,onSort:g}),e.jsx(f,{k:"avg_seconds",label:"Avg",title:"Mean wall-clock time per run",sortKey:d,onSort:g}),e.jsx(f,{k:"p95_seconds",label:"p95",title:"95th-percentile worst-case run",sortKey:d,onSort:g}),e.jsx(f,{k:"max_seconds",label:"Max",title:"Slowest single run",sortKey:d,onSort:g}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400","aria-label":"Distribution",children:"Share"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400",children:"Investigate"})]})}),e.jsx(he,{isLoading:v,data:c,sortedAggregates:p,days:r,peakTotal:P,setInvestigateStep:R})]})})}),e.jsx(pe,{aggregate:B,days:(c==null?void 0:c.days)??r,unit:(c==null?void 0:c.unit)??"seconds",filters:E,onClose:()=>R(null)})]})},j=({icon:t,label:n,value:l})=>e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-3 flex items-center gap-3",children:[e.jsx("div",{className:"shrink-0 w-8 h-8 rounded bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center",children:t}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-gray-500 dark:text-gray-400",children:n}),e.jsx("div",{className:"font-semibold text-gray-800 dark:text-gray-100 tabular-nums truncate",children:l})]})]}),f=({k:t,label:n,title:l,sortKey:i,onSort:x})=>{const s=i===t;return e.jsx("th",{scope:"col","aria-sort":s?"descending":"none",className:"text-right px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400",children:e.jsxs("button",{type:"button",onClick:()=>x(t),title:l,"aria-label":`Sort by ${n}${s?" (currently sorted, descending)":""}`,className:`inline-flex items-center gap-1 select-none ${s?"text-blue-600 dark:text-blue-300":""}`,children:[n,s&&e.jsx("span",{"aria-hidden":"true",children:"▾"})]})})},pe=({aggregate:t,days:n,unit:l,filters:i,onClose:x})=>e.jsx(V,{isOpen:t!==null,onClose:x,title:t?`Investigate: ${t.step_type}`:void 0,size:"2xl",children:t&&e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:["Aggregated over the last ",n," day",n===1?"":"s"," across"," ",t.count.toLocaleString()," run",t.count===1?"":"s",", in"," ",l,"."," ",t.is_single_run&&e.jsx("span",{className:"font-medium text-amber-700 dark:text-amber-400",children:"This reflects a single run's measurement, not a statistical summary — treat it as one data point."})]}),!t.is_single_run&&!t.sample_is_representative&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300 text-sm",children:[e.jsx(_,{className:"w-4 h-4 shrink-0 mt-0.5","aria-hidden":"true"}),e.jsx("span",{children:"The sample node shown in the table is an outlier for this step type — it is not representative of a typical run."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2",children:"Contributing runs"}),t.contributing_runs.length===0?e.jsx(Z,{title:"Investigation unavailable",description:"This aggregate has no retained per-run detail to drill into."}):e.jsx("ul",{className:"space-y-2",children:t.contributing_runs.map(s=>e.jsxs("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 p-2 rounded border border-gray-100 dark:border-gray-800 text-sm",children:[s.is_outlier&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-medium text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/30 rounded px-1.5 py-0.5",children:[e.jsx(_,{className:"w-3 h-3","aria-hidden":"true"}),"Outlier"]}),e.jsx("span",{className:"font-mono tabular-nums font-medium text-gray-800 dark:text-gray-100",children:b(s.execution_seconds)}),e.jsx("span",{className:"text-gray-400 text-xs",children:me(s.finished_at)}),e.jsx(ee,{recordRef:{kind:"job",jobId:s.job_id},origin:"/slow-nodes",filters:i}),e.jsx(te,{nodeId:s.node_id,jobId:s.job_id,pipelineId:s.pipeline_id,label:"Inspect node",origin:"/slow-nodes",filters:i})]},`${s.job_id}-${s.node_id}`))})]})]})});function ue({data:t}){return e.jsx(e.Fragment,{children:t&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 mb-6",children:[e.jsx(j,{icon:e.jsx(W,{className:"w-4 h-4 text-blue-500"}),label:"Step types",value:String(t.aggregates.length)}),e.jsx(j,{icon:e.jsx(H,{className:"w-4 h-4 text-blue-500"}),label:"Node runs",value:t.total_node_runs.toLocaleString()}),e.jsx(j,{icon:e.jsx(M,{className:"w-4 h-4 text-blue-500"}),label:"Jobs scanned",value:t.total_jobs_scanned.toLocaleString()}),e.jsx(j,{icon:e.jsx(Y,{className:"w-4 h-4 text-blue-500"}),label:"Window",value:`${t.days} day${t.days===1?"":"s"}`}),e.jsx(j,{icon:e.jsx(O,{className:"w-4 h-4 text-blue-500"}),label:"Unit",value:t.unit})]})})}function be({sortedAggregates:t,sortKey:n,chartFloor:l,data:i,days:x}){return e.jsx(e.Fragment,{children:t.length>0&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(M,{className:"w-4 h-4 text-blue-500"}),e.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-200",children:"Total time by step type"}),e.jsxs("span",{className:"text-[11px] text-gray-400",children:["(",n==="total_seconds"?"sorted by total":`sorted by ${n.replace("_seconds","")}`,", log scale — totals span orders of magnitude)"]})]}),e.jsx("div",{className:"h-56",children:e.jsx(se,{width:"100%",height:"100%",children:e.jsxs(re,{data:t.map(s=>({step_type:s.step_type,total:Math.max(Number(s.total_seconds.toFixed(3)),l),totalRaw:Number(s.total_seconds.toFixed(3)),avg:Number(s.avg_seconds.toFixed(3)),runs:s.count})),margin:{top:4,right:8,left:8,bottom:28},children:[e.jsx(ae,{strokeDasharray:"3 3",className:"stroke-gray-200 dark:stroke-slate-700",vertical:!1}),e.jsx(ne,{dataKey:"step_type",tick:{fill:"hsl(var(--muted-foreground))",fontSize:10},angle:-25,textAnchor:"end",interval:0,height:50}),e.jsx(le,{scale:"log",domain:[l,"auto"],allowDataOverflow:!0,tick:{fill:"hsl(var(--muted-foreground))",fontSize:10},tickFormatter:s=>b(s),width:64}),e.jsx(ie,{contentStyle:{backgroundColor:"hsl(var(--popover))",borderColor:"hsl(var(--border))",color:"hsl(var(--popover-foreground))",borderRadius:6,fontSize:12},itemStyle:{color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--muted-foreground))"},formatter:(s,r,u)=>{var m;if(r==="runs")return[s,"Runs"];if(r==="total"){const k=(m=u==null?void 0:u.payload)==null?void 0:m.totalRaw;return[b(k??s),"Total time"]}return[b(s),"Avg per run"]}}),e.jsx(oe,{dataKey:"total",radius:[3,3,0,0],children:t.map((s,r)=>e.jsx(de,{fill:L[r%L.length]},`bar-${r}`))})]})})}),e.jsx(Q,{caption:"Total time by step type — text/table alternative to the bar chart",filename:`slow-nodes-${(i==null?void 0:i.days)??x}d`,columns:[{key:"step_type",label:"Step type"},{key:"runs",label:"Runs"},{key:"total",label:"Total (s)"},{key:"avg",label:"Avg (s)"},{key:"p95",label:"p95 (s)"},{key:"max",label:"Max (s)"}],rows:t.map(s=>({step_type:s.step_type,runs:s.count,total:Number(s.total_seconds.toFixed(3)),avg:Number(s.avg_seconds.toFixed(3)),p95:Number(s.p95_seconds.toFixed(3)),max:Number(s.max_seconds.toFixed(3))}))})]})})}function he({isLoading:t,data:n,sortedAggregates:l,days:i,peakTotal:x,setInvestigateStep:s}){return e.jsx("tbody",{children:t&&!n?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-8 text-center text-gray-400 italic",children:"Loading…"})}):l.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-8 text-center text-gray-400",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(O,{className:"w-8 h-8 opacity-40"}),e.jsxs("span",{className:"italic",children:["No node-timing data in the last ",i," day",i===1?"":"s","."]}),e.jsx("span",{className:"text-[11px] not-italic text-gray-500",children:"Pre-existing jobs are silently skipped — re-run a pipeline to seed this view."})]})})}):l.map(r=>{const u=r.total_seconds/x*100;return e.jsxs("tr",{className:"border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-mono font-medium text-gray-800 dark:text-gray-100",children:r.step_type}),e.jsxs("div",{className:"text-[10px] text-gray-400",children:[r.count.toLocaleString()," run",r.count===1?"":"s"," · last ",i," day",i===1?"":"s",r.is_single_run&&e.jsx("span",{className:"ml-1 text-amber-600 dark:text-amber-400",children:"(single run — not a trend)"})]}),r.sample_node_id&&e.jsxs("div",{className:"text-[10px] text-gray-400 truncate max-w-[260px] flex items-center gap-1",title:r.sample_node_id,children:[!r.sample_is_representative&&e.jsx(_,{className:"w-3 h-3 text-amber-500 shrink-0","aria-label":"Sample node is an outlier, not representative"}),e.jsxs("span",{children:[r.sample_is_representative?"e.g. ":"e.g. (outlier) ",r.sample_node_id]})]})]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:r.count.toLocaleString()}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums font-medium text-gray-800 dark:text-gray-100",children:b(r.total_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:b(r.avg_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:b(r.p95_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:b(r.max_seconds)}),e.jsx("td",{className:"px-3 py-2 w-48",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 h-2 bg-gray-100 dark:bg-gray-700/50 rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500",style:{width:`${u}%`}})}),e.jsxs("span",{className:"text-[10px] text-gray-400 tabular-nums w-10 text-right",children:[u.toFixed(0),"%"]})]})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("button",{type:"button",onClick:()=>s(r.step_type),className:"inline-flex items-center gap-1 text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline","aria-label":`Investigate ${r.step_type} runs`,children:[e.jsx(q,{className:"w-3 h-3","aria-hidden":"true"}),"Investigate"]})})]},r.step_type)})})}export{Ne as SlowNodesPage}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{a as o,T as K,c as U,f as z,L as W,H,h as M,C as Y,i as O,j as _,S as q}from"./vendor-utils-_6D5wMFs.js";import{u as X,m as G,t as J,C as Q,M as V,b as Z,R as ee,N as te}from"./index-DYMv5Ibu.js";import{R as se,B as re,C as ae,X as ne,Y as le,T as ie,h as oe,j as de}from"./vendor-charts-CwfdE1jD.js";const $=[1,7,30,90],F=[10,25,50],ce=["total_seconds","avg_seconds","p95_seconds","count","max_seconds"],xe=t=>t!==null&&ce.includes(t),L=["#3b82f6","#8b5cf6","#ec4899","#f59e0b","#10b981","#06b6d4","#ef4444","#a855f7","#eab308","#14b8a6"],b=t=>{if(t<1)return`${(t*1e3).toFixed(0)} ms`;if(t<60)return`${t.toFixed(2)} s`;const n=Math.floor(t/60),l=t-n*60;return`${n}m ${l.toFixed(1)}s`},me=t=>t?t.replace("T"," ").slice(0,16):"Unknown time",Ne=()=>{const[t,n]=X(),l=Number(t.get("days")),i=Number(t.get("limit")),x=t.get("sort"),s=t.get("investigate"),[r,u]=o.useState($.includes(l)?l:7),[m,k]=o.useState(F.includes(i)?i:10),[c,A]=o.useState(null),[v,S]=o.useState(!1),[C,I]=o.useState(null),[d,g]=o.useState(xe(x)?x:"total_seconds"),[y,R]=o.useState(s),N=o.useRef(0);o.useEffect(()=>{const a=new URLSearchParams;a.set("days",String(r)),a.set("limit",String(m)),a.set("sort",d),y&&a.set("investigate",y),n(a,{replace:!0})},[r,m,d,y]);const w=o.useCallback(async()=>{const a=++N.current;S(!0),I(null);try{const h=await G.getSlowNodes(r,m);if(a!==N.current)return;A(h)}catch(h){if(a!==N.current)return;const T=h.message||"Failed to load slow-nodes telemetry";I(T),J.error(T)}finally{a===N.current&&S(!1)}},[r,m]);o.useEffect(()=>{w()},[w]);const p=o.useMemo(()=>c?[...c.aggregates].sort((a,h)=>h[d]-a[d]):[],[c,d]),P=o.useMemo(()=>p.length===0?1:Math.max(...p.map(a=>a.total_seconds)),[p]),D=o.useMemo(()=>{if(p.length===0)return .001;const a=Math.min(...p.map(h=>h.total_seconds));return Math.max(a*.5,.001)},[p]),E=o.useMemo(()=>({days:String(r),limit:String(m),sort:d}),[r,m,d]),B=o.useMemo(()=>p.find(a=>a.step_type===y)??null,[p,y]);return e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 p-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-semibold text-gray-800 dark:text-gray-100 flex items-center gap-2",children:[e.jsx(K,{className:"w-6 h-6 text-blue-500"}),"Slow Nodes"]}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:"Workspace-wide step-type runtime aggregated from completed jobs in the last window. Use it to spot the cheapest optimisation wins."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"inline-flex rounded-md overflow-hidden border border-gray-200 dark:border-gray-700",children:$.map(a=>e.jsx("button",{onClick:()=>u(a),className:`px-2.5 py-1 text-xs font-medium tabular-nums border-r last:border-r-0 border-gray-200 dark:border-gray-700 transition-colors ${a===r?"bg-blue-600 text-white":"bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/30"}`,children:a===1?"24 h":`${a} d`},a))}),e.jsx("div",{className:"inline-flex rounded-md overflow-hidden border border-gray-200 dark:border-gray-700",children:F.map(a=>e.jsxs("button",{onClick:()=>k(a),className:`px-2.5 py-1 text-xs font-medium tabular-nums border-r last:border-r-0 border-gray-200 dark:border-gray-700 transition-colors ${a===m?"bg-blue-600 text-white":"bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/30"}`,title:`Show top ${a} step types`,children:["Top ",a]},a))}),e.jsxs("button",{onClick:()=>void w(),disabled:v,className:"flex items-center gap-1.5 text-xs px-3 py-1.5 rounded bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 border border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(U,{className:`w-3 h-3 ${v?"animate-spin":""}`}),"Refresh"]})]})]}),e.jsx(ue,{data:c}),C&&e.jsxs("div",{className:"mb-4 flex items-start gap-2 p-3 rounded border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300 text-sm",children:[e.jsx(z,{className:"w-4 h-4 shrink-0 mt-0.5"}),e.jsx("span",{children:C})]}),e.jsx(be,{sortedAggregates:p,sortKey:d,chartFloor:D,data:c,days:r}),e.jsx("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-50 dark:bg-gray-900/40 border-b border-gray-200 dark:border-gray-700",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400",children:"Step type"}),e.jsx(f,{k:"count",label:"Runs",title:"Number of executions",sortKey:d,onSort:g}),e.jsx(f,{k:"total_seconds",label:"Total",title:"Cumulative time across all runs",sortKey:d,onSort:g}),e.jsx(f,{k:"avg_seconds",label:"Avg",title:"Mean wall-clock time per run",sortKey:d,onSort:g}),e.jsx(f,{k:"p95_seconds",label:"p95",title:"95th-percentile worst-case run",sortKey:d,onSort:g}),e.jsx(f,{k:"max_seconds",label:"Max",title:"Slowest single run",sortKey:d,onSort:g}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400","aria-label":"Distribution",children:"Share"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400",children:"Investigate"})]})}),e.jsx(he,{isLoading:v,data:c,sortedAggregates:p,days:r,peakTotal:P,setInvestigateStep:R})]})})}),e.jsx(pe,{aggregate:B,days:(c==null?void 0:c.days)??r,unit:(c==null?void 0:c.unit)??"seconds",filters:E,onClose:()=>R(null)})]})},j=({icon:t,label:n,value:l})=>e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-3 flex items-center gap-3",children:[e.jsx("div",{className:"shrink-0 w-8 h-8 rounded bg-blue-50 dark:bg-blue-900/30 flex items-center justify-center",children:t}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-gray-500 dark:text-gray-400",children:n}),e.jsx("div",{className:"font-semibold text-gray-800 dark:text-gray-100 tabular-nums truncate",children:l})]})]}),f=({k:t,label:n,title:l,sortKey:i,onSort:x})=>{const s=i===t;return e.jsx("th",{scope:"col","aria-sort":s?"descending":"none",className:"text-right px-3 py-2 text-[11px] uppercase tracking-wider font-semibold text-gray-500 dark:text-gray-400",children:e.jsxs("button",{type:"button",onClick:()=>x(t),title:l,"aria-label":`Sort by ${n}${s?" (currently sorted, descending)":""}`,className:`inline-flex items-center gap-1 select-none ${s?"text-blue-600 dark:text-blue-300":""}`,children:[n,s&&e.jsx("span",{"aria-hidden":"true",children:"▾"})]})})},pe=({aggregate:t,days:n,unit:l,filters:i,onClose:x})=>e.jsx(V,{isOpen:t!==null,onClose:x,title:t?`Investigate: ${t.step_type}`:void 0,size:"2xl",children:t&&e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:["Aggregated over the last ",n," day",n===1?"":"s"," across"," ",t.count.toLocaleString()," run",t.count===1?"":"s",", in"," ",l,"."," ",t.is_single_run&&e.jsx("span",{className:"font-medium text-amber-700 dark:text-amber-400",children:"This reflects a single run's measurement, not a statistical summary — treat it as one data point."})]}),!t.is_single_run&&!t.sample_is_representative&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-700 dark:text-amber-300 text-sm",children:[e.jsx(_,{className:"w-4 h-4 shrink-0 mt-0.5","aria-hidden":"true"}),e.jsx("span",{children:"The sample node shown in the table is an outlier for this step type — it is not representative of a typical run."})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-2",children:"Contributing runs"}),t.contributing_runs.length===0?e.jsx(Z,{title:"Investigation unavailable",description:"This aggregate has no retained per-run detail to drill into."}):e.jsx("ul",{className:"space-y-2",children:t.contributing_runs.map(s=>e.jsxs("li",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 p-2 rounded border border-gray-100 dark:border-gray-800 text-sm",children:[s.is_outlier&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] font-medium text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/30 rounded px-1.5 py-0.5",children:[e.jsx(_,{className:"w-3 h-3","aria-hidden":"true"}),"Outlier"]}),e.jsx("span",{className:"font-mono tabular-nums font-medium text-gray-800 dark:text-gray-100",children:b(s.execution_seconds)}),e.jsx("span",{className:"text-gray-400 text-xs",children:me(s.finished_at)}),e.jsx(ee,{recordRef:{kind:"job",jobId:s.job_id},origin:"/slow-nodes",filters:i}),e.jsx(te,{nodeId:s.node_id,jobId:s.job_id,pipelineId:s.pipeline_id,label:"Inspect node",origin:"/slow-nodes",filters:i})]},`${s.job_id}-${s.node_id}`))})]})]})});function ue({data:t}){return e.jsx(e.Fragment,{children:t&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3 mb-6",children:[e.jsx(j,{icon:e.jsx(W,{className:"w-4 h-4 text-blue-500"}),label:"Step types",value:String(t.aggregates.length)}),e.jsx(j,{icon:e.jsx(H,{className:"w-4 h-4 text-blue-500"}),label:"Node runs",value:t.total_node_runs.toLocaleString()}),e.jsx(j,{icon:e.jsx(M,{className:"w-4 h-4 text-blue-500"}),label:"Jobs scanned",value:t.total_jobs_scanned.toLocaleString()}),e.jsx(j,{icon:e.jsx(Y,{className:"w-4 h-4 text-blue-500"}),label:"Window",value:`${t.days} day${t.days===1?"":"s"}`}),e.jsx(j,{icon:e.jsx(O,{className:"w-4 h-4 text-blue-500"}),label:"Unit",value:t.unit})]})})}function be({sortedAggregates:t,sortKey:n,chartFloor:l,data:i,days:x}){return e.jsx(e.Fragment,{children:t.length>0&&e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(M,{className:"w-4 h-4 text-blue-500"}),e.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-gray-200",children:"Total time by step type"}),e.jsxs("span",{className:"text-[11px] text-gray-400",children:["(",n==="total_seconds"?"sorted by total":`sorted by ${n.replace("_seconds","")}`,", log scale — totals span orders of magnitude)"]})]}),e.jsx("div",{className:"h-56",children:e.jsx(se,{width:"100%",height:"100%",children:e.jsxs(re,{data:t.map(s=>({step_type:s.step_type,total:Math.max(Number(s.total_seconds.toFixed(3)),l),totalRaw:Number(s.total_seconds.toFixed(3)),avg:Number(s.avg_seconds.toFixed(3)),runs:s.count})),margin:{top:4,right:8,left:8,bottom:28},children:[e.jsx(ae,{strokeDasharray:"3 3",className:"stroke-gray-200 dark:stroke-slate-700",vertical:!1}),e.jsx(ne,{dataKey:"step_type",tick:{fill:"hsl(var(--muted-foreground))",fontSize:10},angle:-25,textAnchor:"end",interval:0,height:50}),e.jsx(le,{scale:"log",domain:[l,"auto"],allowDataOverflow:!0,tick:{fill:"hsl(var(--muted-foreground))",fontSize:10},tickFormatter:s=>b(s),width:64}),e.jsx(ie,{contentStyle:{backgroundColor:"hsl(var(--popover))",borderColor:"hsl(var(--border))",color:"hsl(var(--popover-foreground))",borderRadius:6,fontSize:12},itemStyle:{color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--muted-foreground))"},formatter:(s,r,u)=>{var m;if(r==="runs")return[s,"Runs"];if(r==="total"){const k=(m=u==null?void 0:u.payload)==null?void 0:m.totalRaw;return[b(k??s),"Total time"]}return[b(s),"Avg per run"]}}),e.jsx(oe,{dataKey:"total",radius:[3,3,0,0],children:t.map((s,r)=>e.jsx(de,{fill:L[r%L.length]},`bar-${r}`))})]})})}),e.jsx(Q,{caption:"Total time by step type — text/table alternative to the bar chart",filename:`slow-nodes-${(i==null?void 0:i.days)??x}d`,columns:[{key:"step_type",label:"Step type"},{key:"runs",label:"Runs"},{key:"total",label:"Total (s)"},{key:"avg",label:"Avg (s)"},{key:"p95",label:"p95 (s)"},{key:"max",label:"Max (s)"}],rows:t.map(s=>({step_type:s.step_type,runs:s.count,total:Number(s.total_seconds.toFixed(3)),avg:Number(s.avg_seconds.toFixed(3)),p95:Number(s.p95_seconds.toFixed(3)),max:Number(s.max_seconds.toFixed(3))}))})]})})}function he({isLoading:t,data:n,sortedAggregates:l,days:i,peakTotal:x,setInvestigateStep:s}){return e.jsx("tbody",{children:t&&!n?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-8 text-center text-gray-400 italic",children:"Loading…"})}):l.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"px-3 py-8 text-center text-gray-400",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(O,{className:"w-8 h-8 opacity-40"}),e.jsxs("span",{className:"italic",children:["No node-timing data in the last ",i," day",i===1?"":"s","."]}),e.jsx("span",{className:"text-[11px] not-italic text-gray-500",children:"Pre-existing jobs are silently skipped — re-run a pipeline to seed this view."})]})})}):l.map(r=>{const u=r.total_seconds/x*100;return e.jsxs("tr",{className:"border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-mono font-medium text-gray-800 dark:text-gray-100",children:r.step_type}),e.jsxs("div",{className:"text-[10px] text-gray-400",children:[r.count.toLocaleString()," run",r.count===1?"":"s"," · last ",i," day",i===1?"":"s",r.is_single_run&&e.jsx("span",{className:"ml-1 text-amber-600 dark:text-amber-400",children:"(single run — not a trend)"})]}),r.sample_node_id&&e.jsxs("div",{className:"text-[10px] text-gray-400 truncate max-w-[260px] flex items-center gap-1",title:r.sample_node_id,children:[!r.sample_is_representative&&e.jsx(_,{className:"w-3 h-3 text-amber-500 shrink-0","aria-label":"Sample node is an outlier, not representative"}),e.jsxs("span",{children:[r.sample_is_representative?"e.g. ":"e.g. (outlier) ",r.sample_node_id]})]})]}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:r.count.toLocaleString()}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums font-medium text-gray-800 dark:text-gray-100",children:b(r.total_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:b(r.avg_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:b(r.p95_seconds)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-gray-700 dark:text-gray-200",children:b(r.max_seconds)}),e.jsx("td",{className:"px-3 py-2 w-48",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 h-2 bg-gray-100 dark:bg-gray-700/50 rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500",style:{width:`${u}%`}})}),e.jsxs("span",{className:"text-[10px] text-gray-400 tabular-nums w-10 text-right",children:[u.toFixed(0),"%"]})]})}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("button",{type:"button",onClick:()=>s(r.step_type),className:"inline-flex items-center gap-1 text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline","aria-label":`Investigate ${r.step_type} runs`,children:[e.jsx(q,{className:"w-3 h-3","aria-hidden":"true"}),"Investigate"]})})]},r.step_type)})})}export{Ne as SlowNodesPage}; diff --git a/static/ml_canvas/assets/TemplatesGalleryModal-sEhNFzeh.js b/static/ml_canvas/assets/TemplatesGalleryModal-CbchbwFl.js similarity index 99% rename from static/ml_canvas/assets/TemplatesGalleryModal-sEhNFzeh.js rename to static/ml_canvas/assets/TemplatesGalleryModal-CbchbwFl.js index 08a9da700..4d4666585 100644 --- a/static/ml_canvas/assets/TemplatesGalleryModal-sEhNFzeh.js +++ b/static/ml_canvas/assets/TemplatesGalleryModal-CbchbwFl.js @@ -1 +1 @@ -import{j as e}from"./vendor-flow-bDma3vSM.js";import{L as A,q as R,p as $,s as O,t as U,a as h,u as D,U as M,v as k}from"./vendor-utils-_6D5wMFs.js";import{x as P,v as S,y as B,e as G,F as H,M as z,a as W,g as w,t as _}from"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";function V(s,t){return t?s==="dataset_node"?{datasetId:t.datasetId,datasetName:t.datasetName}:s==="TrainTestSplitter"?{datasetId:t.datasetId,target_column:t.targetColumn}:t.targetColumn&&["classification","regression","text_classification","EnsembleNode"].includes(s)?{target_column:t.targetColumn}:(s==="TextCleaning"||s==="tfidf_vectorizer")&&t.textColumn?{columns:[t.textColumn]}:{}:{}}function K(s,t){const c=new Map,m=[];for(const a of s.nodes){const u=P.get(a.type);if(!u)continue;const n=`${a.type}-${S()}`;c.set(a.localId,n),m.push({id:n,type:"custom",position:a.position,data:{definitionType:a.type,catalogType:a.type,...u.getDefaultConfig(),...a.data??{},...V(a.type,t)}})}const d=[];for(const a of s.edges){const u=c.get(a.source),n=c.get(a.target);!u||!n||d.push({id:`e-${u}-${n}-${S().slice(0,8)}`,source:u,target:n,...a.sourceHandle?{sourceHandle:a.sourceHandle}:{},...a.targetHandle?{targetHandle:a.targetHandle}:{}})}return{nodes:m,edges:d}}const X=280,Y=140,o=s=>80+s*X,r=s=>80+s*Y,q={id:"tabular_classification",name:"Tabular Classification",description:"Classic supervised pipeline: dataset → drop ids → split → impute → encode → scale → train. The split runs before any data-dependent preprocessing so transformers fit on train data only. Bind your dataset, set the target column on the split node, and Run All.",category:"classification",icon:A,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"drop",type:"drop_missing_columns",position:{x:o(1),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(2),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(3),y:r(0)}},{localId:"enc",type:"encoding",position:{x:o(4),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(5),y:r(0)}},{localId:"train",type:"classification",position:{x:o(6),y:r(0)}}],edges:[{source:"ds",target:"drop"},{source:"drop",target:"split"},{source:"split",target:"imp"},{source:"imp",target:"enc"},{source:"enc",target:"scl"},{source:"scl",target:"train"}]},J={id:"tabular_regression",name:"Tabular Regression",description:"Regression starter: dataset → split → impute → outlier removal → scale → train. The split runs before any data-dependent preprocessing so transformers fit on train data only. Pick a numeric target column on the split node before running.",category:"regression",icon:R,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(1),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(2),y:r(0)}},{localId:"out",type:"outlier",position:{x:o(3),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(4),y:r(0)}},{localId:"train",type:"regression",position:{x:o(5),y:r(0)},data:{model_type:"linear_regression"}}],edges:[{source:"ds",target:"split"},{source:"split",target:"imp"},{source:"imp",target:"out"},{source:"out",target:"scl"},{source:"scl",target:"train"}]},Q={id:"text_classification",name:"Text Classification",description:"Text → numbers → model: dataset → split → text cleaning → TF-IDF vectorizer → Logistic Regression. The split runs first so the TF-IDF vocabulary is learned from train data only. Point the Text Cleaning and TF-IDF nodes at your raw-text column, pick the label column on the split, then Run All. (TF-IDF + Logistic Regression is the standard strong baseline for text.)",category:"text",icon:$,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(1),y:r(0)}},{localId:"clean",type:"TextCleaning",position:{x:o(2),y:r(0)}},{localId:"vec",type:"tfidf_vectorizer",position:{x:o(3),y:r(0)},data:{drop_original:!0}},{localId:"train",type:"text_classification",position:{x:o(4),y:r(0)},data:{model_type:"logistic_regression"}}],edges:[{source:"ds",target:"split"},{source:"split",target:"clean"},{source:"clean",target:"vec"},{source:"vec",target:"train"}]},Z={id:"customer_segmentation",name:"Customer Segmentation",description:"Unsupervised clustering starter: dataset → impute → scale → Segmentation (K-Means). No target column needed — set the number of clusters on the Segmentation node, then Run All. View results in the Experiments page’s Segmentation tab.",category:"clustering",icon:O,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(1),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(2),y:r(0)}},{localId:"train",type:"SegmentationNode",position:{x:o(3),y:r(0)}}],edges:[{source:"ds",target:"imp"},{source:"imp",target:"scl"},{source:"scl",target:"train"}]},ee={id:"ensemble_classification",name:"Ensemble Classification",description:"Combine multiple models for stronger predictions: dataset → drop ids → split → impute → encode → scale → Ensemble (Voting Classifier). The split runs before any data-dependent preprocessing so transformers fit on train data only. Bind your dataset, set the target column on the split node, adjust base models if needed, then Run All.",category:"ensemble",icon:U,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"drop",type:"drop_missing_columns",position:{x:o(1),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(2),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(3),y:r(0)}},{localId:"enc",type:"encoding",position:{x:o(4),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(5),y:r(0)}},{localId:"train",type:"EnsembleNode",position:{x:o(6),y:r(0)}}],edges:[{source:"ds",target:"drop"},{source:"drop",target:"split"},{source:"split",target:"imp"},{source:"imp",target:"enc"},{source:"enc",target:"scl"},{source:"scl",target:"train"}]},te=[q,J,Q,Z,ee],F={tabular_classification:{title:"Predict a category",example:"Will a customer stay or leave?",needs:"A table with a known outcome for each training row.",outcome:"Compare predicted categories with known outcomes in Experiments.",steps:["Select data","Split","Prepare features","Train classifier"]},tabular_regression:{title:"Estimate a value",example:"How much could a home sell for?",needs:"Numeric features and a numeric target, such as price or demand.",outcome:"Inspect prediction errors and see how closely estimates match real values.",steps:["Select data","Split","Clean & scale","Train regressor"]},text_classification:{title:"Make sense of text",example:"Sort messages into useful categories.",needs:"A text column and a separate column containing its category.",outcome:"Evaluate a text classifier built with TF-IDF and logistic regression.",steps:["Select text","Split","Clean & vectorize","Classify"]},customer_segmentation:{title:"Discover customer groups",example:"Find customers with similar behaviour.",needs:"Numeric features describing each customer. No target column needed.",outcome:"Explore the resulting groups in the Experiments Segmentation tab.",steps:["Select data","Fill missing values","Scale","Find groups"]},ensemble_classification:{title:"Combine model predictions",example:"Try a voting ensemble for your classification task.",needs:"A table with known categories. Review the base models before training.",outcome:"Evaluate combined predictions; compare with a single-model run to check whether they help.",steps:["Select data","Split","Prepare features","Voting ensemble"]}};function se({id:s,category:t,schema:c,target:m,text:d,disabled:a,onTarget:u,onText:n}){var g;if(c.isError)return e.jsxs("p",{role:"alert",className:"text-sm text-destructive",children:["Could not load columns. ",e.jsx("button",{type:"button",className:"underline",onClick:()=>{c.refetch()},children:"Retry"})]});if(c.isLoading)return e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading columns…"});if(t==="clustering")return e.jsx("p",{className:"rounded-md bg-muted p-3 text-sm",children:"No target needed. Select useful numeric features and review the number of groups in Canvas."});const x=Object.values(((g=c.data)==null?void 0:g.columns)??{}),p=x.filter(i=>/object|string|category|text|utf8/i.test(String(i.dtype))&&i.name!==m);return e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:`${s}-target`,className:"block text-sm font-medium",children:"Target column"}),e.jsxs("select",{id:`${s}-target`,value:m,disabled:a,onChange:i=>u(i.target.value),className:"w-full rounded-md border bg-background p-2.5 text-sm",children:[e.jsx("option",{value:"",children:"Choose what to predict"}),x.map(i=>e.jsxs("option",{value:i.name,children:[i.name," (",i.dtype,")"]},i.name))]}),t==="regression"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose a numeric target for regression."}),t==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:`${s}-text`,className:"block text-sm font-medium",children:"Text column"}),e.jsxs("select",{id:`${s}-text`,value:d,disabled:a,onChange:i=>n(i.target.value),className:"w-full rounded-md border bg-background p-2.5 text-sm",children:[e.jsx("option",{value:"",children:"Choose the text to classify"}),p.map(i=>e.jsx("option",{value:i.name,children:i.name},i.name))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used by both text cleaning and TF-IDF. The target is excluded."})]})]})}function ae(s,t,c,m,d){if(!c||t.isError||t.isLoading||!t.data)return!1;const a=Object.values(t.data.columns).map(u=>u.name);return s!=="clustering"&&!a.includes(m)?!1:s==="text"?d!==m&&a.includes(d):!0}function oe({template:s,opening:t,onBack:c,onOpen:m}){var I,T;const d=h.useId(),[a,u]=h.useState({datasetId:"",datasetName:""}),[n,x]=h.useState(""),[p,g]=h.useState(""),[i,j]=h.useState(!1),y=B(),v=G(a.datasetId),b=F[s.id],E=ae(s.category,v,a.datasetId,n,p);function N(l,f){u({datasetId:l,datasetName:f}),x(""),g(""),j(!1)}return e.jsxs("div",{className:"space-y-5 p-4 sm:p-6",children:[e.jsxs("button",{type:"button",onClick:c,disabled:t,className:"flex items-center gap-2 rounded text-sm text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx(D,{className:"h-4 w-4","aria-hidden":"true"})," All templates"]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_1.1fr]",children:[e.jsxs("section",{className:"space-y-5 rounded-xl border border-primary/20 bg-primary/5 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-widest text-primary",children:s.name}),e.jsx("h3",{className:"mt-2 text-2xl font-semibold tracking-tight",children:b.title}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:b.example})]}),e.jsx("ol",{"aria-label":"Workflow preview",className:"space-y-3",children:b.steps.map((l,f)=>e.jsxs("li",{className:"flex items-center gap-3 text-sm",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-primary/25 text-xs font-semibold text-primary",children:f+1}),l]},l))}),e.jsxs("div",{className:"border-t border-primary/15 pt-4",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"What you will get"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:b.outcome})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Connect your data"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:b.needs})]}),i?e.jsx(H,{onUploadComplete:N,onCancel:()=>j(!1)}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:`${d}-dataset`,className:"block text-sm font-medium",children:"Dataset"}),e.jsxs("select",{id:`${d}-dataset`,value:a.datasetId,disabled:y.isLoading||t,className:"w-full rounded-md border bg-background p-2.5 text-sm",onChange:l=>{var C;const f=(C=y.data)==null?void 0:C.find(L=>String(L.id)===l.target.value);N(l.target.value,(f==null?void 0:f.name)??"")},children:[e.jsx("option",{value:"",children:y.isLoading?"Loading datasets…":"Choose a dataset"}),(I=y.data)==null?void 0:I.map(l=>e.jsx("option",{value:String(l.id),children:l.name},l.id)),a.datasetId&&!((T=y.data)!=null&&T.some(l=>String(l.id)===a.datasetId))&&e.jsx("option",{value:a.datasetId,children:a.datasetName})]}),e.jsx(re,{query:y}),e.jsxs("button",{type:"button",disabled:t,onClick:()=>j(!0),className:"flex items-center gap-2 rounded text-sm font-medium text-primary focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx(M,{className:"h-4 w-4","aria-hidden":"true"})," Upload a dataset"]})]}),a.datasetId&&e.jsx(se,{id:d,category:s.category,schema:v,target:n,text:p,disabled:t,onTarget:l=>{x(l),l===p&&g("")},onText:g}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("button",{type:"button",disabled:!E||t,onClick:()=>m({...a,targetColumn:n,textColumn:p}),className:"flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40",children:[t?"Opening…":"Open in Canvas"," ",e.jsx(k,{className:"h-4 w-4","aria-hidden":"true"})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Review feature selection and model settings in Canvas before running."})]})]})]})]})]})}function re({query:s}){var t;return s.isError?e.jsxs("p",{role:"alert",className:"text-sm text-destructive",children:["Could not load datasets. ",e.jsx("button",{type:"button",className:"underline",onClick:()=>{s.refetch()},children:"Retry"})]}):s.isLoading||(t=s.data)!=null&&t.length?null:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload your first dataset to start this workflow."})}function ue({isOpen:s,onClose:t}){return e.jsx(z,{isOpen:s,onClose:t,title:"Start from a template",size:"5xl",children:s&&e.jsx(ne,{onClose:t})})}function ne({onClose:s}){const[t,c]=h.useState(null),[m,d]=h.useState(!1),a=W();async function u(n,x){d(!0);try{if(w.getState().nodes.length>0&&!await a({title:"Replace current canvas?",message:`Loading "${n.name}" will replace your current canvas. Continue?`,confirmLabel:"Load template",variant:"danger"}))return;const{nodes:p,edges:g}=K(n,x);if(p.length!==n.nodes.length){_.error("Template could not be loaded","A required node type is unavailable.");return}w.getState().setGraph(p,g),_.success(`Loaded "${n.name}"`,"Review the node settings, then Run All."),s()}finally{d(!1)}}return t?e.jsx(oe,{template:t,opening:m,onBack:()=>c(null),onOpen:n=>{u(t,n)}}):e.jsxs("div",{className:"space-y-5 p-4 sm:p-6",children:[e.jsxs("div",{className:"max-w-2xl space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-primary",children:"Your next experiment"}),e.jsx("h3",{className:"text-2xl font-semibold tracking-tight",children:"What would you like to discover?"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starting point. Connect your data, choose what to predict, and make the workflow your own."})]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:te.map((n,x)=>{const p=F[n.id],g=n.icon;return e.jsxs("button",{type:"button","data-testid":`template-card-${n.id}`,onClick:()=>c(n),className:`group flex flex-col gap-3 rounded-xl border p-4 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${x===0?"border-primary/35 bg-primary/5 md:col-span-2":"border-border bg-card hover:border-primary/40 hover:bg-accent/30"}`,children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsx("span",{className:"rounded-lg bg-primary/10 p-2 text-primary",children:e.jsx(g,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x===0?"A good place to start":n.name})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-lg font-semibold tracking-tight",children:p.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:p.example})]}),e.jsxs("div",{className:"flex w-full items-center justify-between gap-3 border-t border-border/60 pt-3 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n.nodes.length," connected steps · ",n.category]}),e.jsxs("span",{className:"flex items-center gap-2 font-medium text-primary",children:["Set up ",e.jsx(k,{className:"h-4 w-4","aria-hidden":"true"})]})]})]},n.id)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All five workflows are editable. Training starts only when you run the pipeline."})]})}export{ue as TemplatesGalleryModal}; +import{j as e}from"./vendor-flow-bDma3vSM.js";import{L as A,q as R,p as $,s as O,t as U,a as h,u as D,U as M,v as k}from"./vendor-utils-_6D5wMFs.js";import{x as P,v as S,y as B,e as G,F as H,M as z,a as W,g as w,t as _}from"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";function V(s,t){return t?s==="dataset_node"?{datasetId:t.datasetId,datasetName:t.datasetName}:s==="TrainTestSplitter"?{datasetId:t.datasetId,target_column:t.targetColumn}:t.targetColumn&&["classification","regression","text_classification","EnsembleNode"].includes(s)?{target_column:t.targetColumn}:(s==="TextCleaning"||s==="tfidf_vectorizer")&&t.textColumn?{columns:[t.textColumn]}:{}:{}}function K(s,t){const c=new Map,m=[];for(const a of s.nodes){const u=P.get(a.type);if(!u)continue;const n=`${a.type}-${S()}`;c.set(a.localId,n),m.push({id:n,type:"custom",position:a.position,data:{definitionType:a.type,catalogType:a.type,...u.getDefaultConfig(),...a.data??{},...V(a.type,t)}})}const d=[];for(const a of s.edges){const u=c.get(a.source),n=c.get(a.target);!u||!n||d.push({id:`e-${u}-${n}-${S().slice(0,8)}`,source:u,target:n,...a.sourceHandle?{sourceHandle:a.sourceHandle}:{},...a.targetHandle?{targetHandle:a.targetHandle}:{}})}return{nodes:m,edges:d}}const X=280,Y=140,o=s=>80+s*X,r=s=>80+s*Y,q={id:"tabular_classification",name:"Tabular Classification",description:"Classic supervised pipeline: dataset → drop ids → split → impute → encode → scale → train. The split runs before any data-dependent preprocessing so transformers fit on train data only. Bind your dataset, set the target column on the split node, and Run All.",category:"classification",icon:A,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"drop",type:"drop_missing_columns",position:{x:o(1),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(2),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(3),y:r(0)}},{localId:"enc",type:"encoding",position:{x:o(4),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(5),y:r(0)}},{localId:"train",type:"classification",position:{x:o(6),y:r(0)}}],edges:[{source:"ds",target:"drop"},{source:"drop",target:"split"},{source:"split",target:"imp"},{source:"imp",target:"enc"},{source:"enc",target:"scl"},{source:"scl",target:"train"}]},J={id:"tabular_regression",name:"Tabular Regression",description:"Regression starter: dataset → split → impute → outlier removal → scale → train. The split runs before any data-dependent preprocessing so transformers fit on train data only. Pick a numeric target column on the split node before running.",category:"regression",icon:R,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(1),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(2),y:r(0)}},{localId:"out",type:"outlier",position:{x:o(3),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(4),y:r(0)}},{localId:"train",type:"regression",position:{x:o(5),y:r(0)},data:{model_type:"linear_regression"}}],edges:[{source:"ds",target:"split"},{source:"split",target:"imp"},{source:"imp",target:"out"},{source:"out",target:"scl"},{source:"scl",target:"train"}]},Q={id:"text_classification",name:"Text Classification",description:"Text → numbers → model: dataset → split → text cleaning → TF-IDF vectorizer → Logistic Regression. The split runs first so the TF-IDF vocabulary is learned from train data only. Point the Text Cleaning and TF-IDF nodes at your raw-text column, pick the label column on the split, then Run All. (TF-IDF + Logistic Regression is the standard strong baseline for text.)",category:"text",icon:$,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(1),y:r(0)}},{localId:"clean",type:"TextCleaning",position:{x:o(2),y:r(0)}},{localId:"vec",type:"tfidf_vectorizer",position:{x:o(3),y:r(0)},data:{drop_original:!0}},{localId:"train",type:"text_classification",position:{x:o(4),y:r(0)},data:{model_type:"logistic_regression"}}],edges:[{source:"ds",target:"split"},{source:"split",target:"clean"},{source:"clean",target:"vec"},{source:"vec",target:"train"}]},Z={id:"customer_segmentation",name:"Customer Segmentation",description:"Unsupervised clustering starter: dataset → impute → scale → Segmentation (K-Means). No target column needed — set the number of clusters on the Segmentation node, then Run All. View results in the Experiments page’s Segmentation tab.",category:"clustering",icon:O,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(1),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(2),y:r(0)}},{localId:"train",type:"SegmentationNode",position:{x:o(3),y:r(0)}}],edges:[{source:"ds",target:"imp"},{source:"imp",target:"scl"},{source:"scl",target:"train"}]},ee={id:"ensemble_classification",name:"Ensemble Classification",description:"Combine multiple models for stronger predictions: dataset → drop ids → split → impute → encode → scale → Ensemble (Voting Classifier). The split runs before any data-dependent preprocessing so transformers fit on train data only. Bind your dataset, set the target column on the split node, adjust base models if needed, then Run All.",category:"ensemble",icon:U,nodes:[{localId:"ds",type:"dataset_node",position:{x:o(0),y:r(0)}},{localId:"drop",type:"drop_missing_columns",position:{x:o(1),y:r(0)}},{localId:"split",type:"TrainTestSplitter",position:{x:o(2),y:r(0)}},{localId:"imp",type:"imputation_node",position:{x:o(3),y:r(0)}},{localId:"enc",type:"encoding",position:{x:o(4),y:r(0)}},{localId:"scl",type:"scale_numeric_features",position:{x:o(5),y:r(0)}},{localId:"train",type:"EnsembleNode",position:{x:o(6),y:r(0)}}],edges:[{source:"ds",target:"drop"},{source:"drop",target:"split"},{source:"split",target:"imp"},{source:"imp",target:"enc"},{source:"enc",target:"scl"},{source:"scl",target:"train"}]},te=[q,J,Q,Z,ee],F={tabular_classification:{title:"Predict a category",example:"Will a customer stay or leave?",needs:"A table with a known outcome for each training row.",outcome:"Compare predicted categories with known outcomes in Experiments.",steps:["Select data","Split","Prepare features","Train classifier"]},tabular_regression:{title:"Estimate a value",example:"How much could a home sell for?",needs:"Numeric features and a numeric target, such as price or demand.",outcome:"Inspect prediction errors and see how closely estimates match real values.",steps:["Select data","Split","Clean & scale","Train regressor"]},text_classification:{title:"Make sense of text",example:"Sort messages into useful categories.",needs:"A text column and a separate column containing its category.",outcome:"Evaluate a text classifier built with TF-IDF and logistic regression.",steps:["Select text","Split","Clean & vectorize","Classify"]},customer_segmentation:{title:"Discover customer groups",example:"Find customers with similar behaviour.",needs:"Numeric features describing each customer. No target column needed.",outcome:"Explore the resulting groups in the Experiments Segmentation tab.",steps:["Select data","Fill missing values","Scale","Find groups"]},ensemble_classification:{title:"Combine model predictions",example:"Try a voting ensemble for your classification task.",needs:"A table with known categories. Review the base models before training.",outcome:"Evaluate combined predictions; compare with a single-model run to check whether they help.",steps:["Select data","Split","Prepare features","Voting ensemble"]}};function se({id:s,category:t,schema:c,target:m,text:d,disabled:a,onTarget:u,onText:n}){var g;if(c.isError)return e.jsxs("p",{role:"alert",className:"text-sm text-destructive",children:["Could not load columns. ",e.jsx("button",{type:"button",className:"underline",onClick:()=>{c.refetch()},children:"Retry"})]});if(c.isLoading)return e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading columns…"});if(t==="clustering")return e.jsx("p",{className:"rounded-md bg-muted p-3 text-sm",children:"No target needed. Select useful numeric features and review the number of groups in Canvas."});const x=Object.values(((g=c.data)==null?void 0:g.columns)??{}),p=x.filter(i=>/object|string|category|text|utf8/i.test(String(i.dtype))&&i.name!==m);return e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:`${s}-target`,className:"block text-sm font-medium",children:"Target column"}),e.jsxs("select",{id:`${s}-target`,value:m,disabled:a,onChange:i=>u(i.target.value),className:"w-full rounded-md border bg-background p-2.5 text-sm",children:[e.jsx("option",{value:"",children:"Choose what to predict"}),x.map(i=>e.jsxs("option",{value:i.name,children:[i.name," (",i.dtype,")"]},i.name))]}),t==="regression"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose a numeric target for regression."}),t==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:`${s}-text`,className:"block text-sm font-medium",children:"Text column"}),e.jsxs("select",{id:`${s}-text`,value:d,disabled:a,onChange:i=>n(i.target.value),className:"w-full rounded-md border bg-background p-2.5 text-sm",children:[e.jsx("option",{value:"",children:"Choose the text to classify"}),p.map(i=>e.jsx("option",{value:i.name,children:i.name},i.name))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used by both text cleaning and TF-IDF. The target is excluded."})]})]})}function ae(s,t,c,m,d){if(!c||t.isError||t.isLoading||!t.data)return!1;const a=Object.values(t.data.columns).map(u=>u.name);return s!=="clustering"&&!a.includes(m)?!1:s==="text"?d!==m&&a.includes(d):!0}function oe({template:s,opening:t,onBack:c,onOpen:m}){var I,T;const d=h.useId(),[a,u]=h.useState({datasetId:"",datasetName:""}),[n,x]=h.useState(""),[p,g]=h.useState(""),[i,j]=h.useState(!1),y=B(),v=G(a.datasetId),b=F[s.id],E=ae(s.category,v,a.datasetId,n,p);function N(l,f){u({datasetId:l,datasetName:f}),x(""),g(""),j(!1)}return e.jsxs("div",{className:"space-y-5 p-4 sm:p-6",children:[e.jsxs("button",{type:"button",onClick:c,disabled:t,className:"flex items-center gap-2 rounded text-sm text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx(D,{className:"h-4 w-4","aria-hidden":"true"})," All templates"]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_1.1fr]",children:[e.jsxs("section",{className:"space-y-5 rounded-xl border border-primary/20 bg-primary/5 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-widest text-primary",children:s.name}),e.jsx("h3",{className:"mt-2 text-2xl font-semibold tracking-tight",children:b.title}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:b.example})]}),e.jsx("ol",{"aria-label":"Workflow preview",className:"space-y-3",children:b.steps.map((l,f)=>e.jsxs("li",{className:"flex items-center gap-3 text-sm",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-primary/25 text-xs font-semibold text-primary",children:f+1}),l]},l))}),e.jsxs("div",{className:"border-t border-primary/15 pt-4",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"What you will get"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:b.outcome})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Connect your data"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:b.needs})]}),i?e.jsx(H,{onUploadComplete:N,onCancel:()=>j(!1)}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:`${d}-dataset`,className:"block text-sm font-medium",children:"Dataset"}),e.jsxs("select",{id:`${d}-dataset`,value:a.datasetId,disabled:y.isLoading||t,className:"w-full rounded-md border bg-background p-2.5 text-sm",onChange:l=>{var C;const f=(C=y.data)==null?void 0:C.find(L=>String(L.id)===l.target.value);N(l.target.value,(f==null?void 0:f.name)??"")},children:[e.jsx("option",{value:"",children:y.isLoading?"Loading datasets…":"Choose a dataset"}),(I=y.data)==null?void 0:I.map(l=>e.jsx("option",{value:String(l.id),children:l.name},l.id)),a.datasetId&&!((T=y.data)!=null&&T.some(l=>String(l.id)===a.datasetId))&&e.jsx("option",{value:a.datasetId,children:a.datasetName})]}),e.jsx(re,{query:y}),e.jsxs("button",{type:"button",disabled:t,onClick:()=>j(!0),className:"flex items-center gap-2 rounded text-sm font-medium text-primary focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx(M,{className:"h-4 w-4","aria-hidden":"true"})," Upload a dataset"]})]}),a.datasetId&&e.jsx(se,{id:d,category:s.category,schema:v,target:n,text:p,disabled:t,onTarget:l=>{x(l),l===p&&g("")},onText:g}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("button",{type:"button",disabled:!E||t,onClick:()=>m({...a,targetColumn:n,textColumn:p}),className:"flex w-full items-center justify-center gap-2 rounded-lg bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40",children:[t?"Opening…":"Open in Canvas"," ",e.jsx(k,{className:"h-4 w-4","aria-hidden":"true"})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Review feature selection and model settings in Canvas before running."})]})]})]})]})]})}function re({query:s}){var t;return s.isError?e.jsxs("p",{role:"alert",className:"text-sm text-destructive",children:["Could not load datasets. ",e.jsx("button",{type:"button",className:"underline",onClick:()=>{s.refetch()},children:"Retry"})]}):s.isLoading||(t=s.data)!=null&&t.length?null:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload your first dataset to start this workflow."})}function ue({isOpen:s,onClose:t}){return e.jsx(z,{isOpen:s,onClose:t,title:"Start from a template",size:"5xl",children:s&&e.jsx(ne,{onClose:t})})}function ne({onClose:s}){const[t,c]=h.useState(null),[m,d]=h.useState(!1),a=W();async function u(n,x){d(!0);try{if(w.getState().nodes.length>0&&!await a({title:"Replace current canvas?",message:`Loading "${n.name}" will replace your current canvas. Continue?`,confirmLabel:"Load template",variant:"danger"}))return;const{nodes:p,edges:g}=K(n,x);if(p.length!==n.nodes.length){_.error("Template could not be loaded","A required node type is unavailable.");return}w.getState().setGraph(p,g),_.success(`Loaded "${n.name}"`,"Review the node settings, then Run All."),s()}finally{d(!1)}}return t?e.jsx(oe,{template:t,opening:m,onBack:()=>c(null),onOpen:n=>{u(t,n)}}):e.jsxs("div",{className:"space-y-5 p-4 sm:p-6",children:[e.jsxs("div",{className:"max-w-2xl space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-primary",children:"Your next experiment"}),e.jsx("h3",{className:"text-2xl font-semibold tracking-tight",children:"What would you like to discover?"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starting point. Connect your data, choose what to predict, and make the workflow your own."})]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:te.map((n,x)=>{const p=F[n.id],g=n.icon;return e.jsxs("button",{type:"button","data-testid":`template-card-${n.id}`,onClick:()=>c(n),className:`group flex flex-col gap-3 rounded-xl border p-4 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${x===0?"border-primary/35 bg-primary/5 md:col-span-2":"border-border bg-card hover:border-primary/40 hover:bg-accent/30"}`,children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsx("span",{className:"rounded-lg bg-primary/10 p-2 text-primary",children:e.jsx(g,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x===0?"A good place to start":n.name})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-lg font-semibold tracking-tight",children:p.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:p.example})]}),e.jsxs("div",{className:"flex w-full items-center justify-between gap-3 border-t border-border/60 pt-3 text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[n.nodes.length," connected steps · ",n.category]}),e.jsxs("span",{className:"flex items-center gap-2 font-medium text-primary",children:["Set up ",e.jsx(k,{className:"h-4 w-4","aria-hidden":"true"})]})]})]},n.id)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All five workflows are editable. Training starts only when you run the pipeline."})]})}export{ue as TemplatesGalleryModal}; diff --git a/static/ml_canvas/assets/abnfDiagram-VCTEODGH-Bv6eSEHt.js b/static/ml_canvas/assets/abnfDiagram-VCTEODGH-C_J13ClI.js similarity index 83% rename from static/ml_canvas/assets/abnfDiagram-VCTEODGH-Bv6eSEHt.js rename to static/ml_canvas/assets/abnfDiagram-VCTEODGH-C_J13ClI.js index 5562b8fda..393b448ef 100644 --- a/static/ml_canvas/assets/abnfDiagram-VCTEODGH-Bv6eSEHt.js +++ b/static/ml_canvas/assets/abnfDiagram-VCTEODGH-C_J13ClI.js @@ -1 +1 @@ -import{g as p,r as u,d as a}from"./chunk-SVP7TREG-Bg03xQLN.js";import{p as f}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{_ as n,l as o}from"./mermaid.core-BCO0YdKy.js";import"./vendor-flow-bDma3vSM.js";import{M as c,b as d}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),m=t?parseInt(t,10):0,l=s?parseInt(s,10):1/0;return{min:m,max:l}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},C={parser:R,db:a,renderer:u,styles:p};export{C as diagram}; +import{g as p,r as u,d as a}from"./chunk-SVP7TREG-CbDuCHXJ.js";import{p as f}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{_ as n,l as o}from"./mermaid.core-BRmiRRt4.js";import"./vendor-flow-bDma3vSM.js";import{M as c,b as d}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var v=d().RailroadAbnf.parser.LangiumParser,i=n(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=n(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=n(e=>{if(e.includes("*")){const[t,s]=e.split("*"),m=t?parseInt(t,10):0,l=s?parseInt(s,10):1/0;return{min:m,max:l}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=n(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=n(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=n(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=n(e=>{f(e,a),e.title&&a.setTitle(e.title),e.rules.map(r=>a.addRule(P(r)))},"populateDb"),R={parse:n(e=>{a.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:a}},C={parser:R,db:a,renderer:u,styles:p};export{C as diagram}; diff --git a/static/ml_canvas/assets/architectureDiagram-5GKGNRK7-CSxe9SIw.js b/static/ml_canvas/assets/architectureDiagram-5GKGNRK7-D0TnY4Wf.js similarity index 99% rename from static/ml_canvas/assets/architectureDiagram-5GKGNRK7-CSxe9SIw.js rename to static/ml_canvas/assets/architectureDiagram-5GKGNRK7-D0TnY4Wf.js index df4c08d1d..0229de4c2 100644 --- a/static/ml_canvas/assets/architectureDiagram-5GKGNRK7-CSxe9SIw.js +++ b/static/ml_canvas/assets/architectureDiagram-5GKGNRK7-D0TnY4Wf.js @@ -1,4 +1,4 @@ -import{p as qe}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{_ as ct,C as Qe,Y as Je,l as Fe,b as Ke,a as je,m as _e,n as tr,g as er,s as rr,o as ir,z as ar,x as nr,A as or,c as Ee,ap as Te,a4 as pe,i as sr,p as hr,a5 as lr,aq as fr}from"./mermaid.core-BCO0YdKy.js";import{p as cr}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import{c as be}from"./cytoscape.esm-Bch-eiPH.js";import{g as gr}from"./vendor-utils-_6D5wMFs.js";import{s as ur}from"./vendor-flow-bDma3vSM.js";import"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";var he={exports:{}},le={exports:{}},fe={exports:{}},dr=fe.exports,De;function vr(){return De||(De=1,(function(I,M){(function(x,N){I.exports=N()})(dr,function(){return(function(C){var x={};function N(v){if(x[v])return x[v].exports;var l=x[v]={i:v,l:!1,exports:{}};return C[v].call(l.exports,l,l.exports,N),l.l=!0,l.exports}return N.m=C,N.c=x,N.i=function(v){return v},N.d=function(v,l,n){N.o(v,l)||Object.defineProperty(v,l,{configurable:!1,enumerable:!0,get:n})},N.n=function(v){var l=v&&v.__esModule?function(){return v.default}:function(){return v};return N.d(l,"a",l),l},N.o=function(v,l){return Object.prototype.hasOwnProperty.call(v,l)},N.p="",N(N.s=28)})([(function(C,x,N){function v(){}v.QUALITY=1,v.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,v.DEFAULT_INCREMENTAL=!1,v.DEFAULT_ANIMATION_ON_LAYOUT=!0,v.DEFAULT_ANIMATION_DURING_LAYOUT=!1,v.DEFAULT_ANIMATION_PERIOD=50,v.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,v.DEFAULT_GRAPH_MARGIN=15,v.NODE_DIMENSIONS_INCLUDE_LABELS=!1,v.SIMPLE_NODE_SIZE=40,v.SIMPLE_NODE_HALF_SIZE=v.SIMPLE_NODE_SIZE/2,v.EMPTY_COMPOUND_NODE_SIZE=40,v.MIN_EDGE_LENGTH=1,v.WORLD_BOUNDARY=1e6,v.INITIAL_WORLD_BOUNDARY=v.WORLD_BOUNDARY/1e3,v.WORLD_CENTER_X=1200,v.WORLD_CENTER_Y=900,C.exports=v}),(function(C,x,N){var v=N(2),l=N(8),n=N(9);function r(f,e,g){v.call(this,g),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=g,this.bendpoints=[],this.source=f,this.target=e}r.prototype=Object.create(v.prototype);for(var i in v)r[i]=v[i];r.prototype.getSource=function(){return this.source},r.prototype.getTarget=function(){return this.target},r.prototype.isInterGraph=function(){return this.isInterGraph},r.prototype.getLength=function(){return this.length},r.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},r.prototype.getBendpoints=function(){return this.bendpoints},r.prototype.getLca=function(){return this.lca},r.prototype.getSourceInLca=function(){return this.sourceInLca},r.prototype.getTargetInLca=function(){return this.targetInLca},r.prototype.getOtherEnd=function(f){if(this.source===f)return this.target;if(this.target===f)return this.source;throw"Node is not incident with this edge"},r.prototype.getOtherEndInGraph=function(f,e){for(var g=this.getOtherEnd(f),t=e.getGraphManager().getRoot();;){if(g.getOwner()==e)return g;if(g.getOwner()==t)break;g=g.getOwner().getParent()}return null},r.prototype.updateLength=function(){var f=new Array(4);this.isOverlapingSourceAndTarget=l.getIntersection(this.target.getRect(),this.source.getRect(),f),this.isOverlapingSourceAndTarget||(this.lengthX=f[0]-f[2],this.lengthY=f[1]-f[3],Math.abs(this.lengthX)<1&&(this.lengthX=n.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=n.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},r.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=n.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=n.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},C.exports=r}),(function(C,x,N){function v(l){this.vGraphObject=l}C.exports=v}),(function(C,x,N){var v=N(2),l=N(10),n=N(13),r=N(0),i=N(16),f=N(5);function e(t,s,o,c){o==null&&c==null&&(c=s),v.call(this,c),t.graphManager!=null&&(t=t.graphManager),this.estimatedSize=l.MIN_VALUE,this.inclusionTreeDepth=l.MAX_VALUE,this.vGraphObject=c,this.edges=[],this.graphManager=t,o!=null&&s!=null?this.rect=new n(s.x,s.y,o.width,o.height):this.rect=new n}e.prototype=Object.create(v.prototype);for(var g in v)e[g]=v[g];e.prototype.getEdges=function(){return this.edges},e.prototype.getChild=function(){return this.child},e.prototype.getOwner=function(){return this.owner},e.prototype.getWidth=function(){return this.rect.width},e.prototype.setWidth=function(t){this.rect.width=t},e.prototype.getHeight=function(){return this.rect.height},e.prototype.setHeight=function(t){this.rect.height=t},e.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},e.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},e.prototype.getCenter=function(){return new f(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},e.prototype.getLocation=function(){return new f(this.rect.x,this.rect.y)},e.prototype.getRect=function(){return this.rect},e.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},e.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},e.prototype.setRect=function(t,s){this.rect.x=t.x,this.rect.y=t.y,this.rect.width=s.width,this.rect.height=s.height},e.prototype.setCenter=function(t,s){this.rect.x=t-this.rect.width/2,this.rect.y=s-this.rect.height/2},e.prototype.setLocation=function(t,s){this.rect.x=t,this.rect.y=s},e.prototype.moveBy=function(t,s){this.rect.x+=t,this.rect.y+=s},e.prototype.getEdgeListToNode=function(t){var s=[],o=this;return o.edges.forEach(function(c){if(c.target==t){if(c.source!=o)throw"Incorrect edge source!";s.push(c)}}),s},e.prototype.getEdgesBetween=function(t){var s=[],o=this;return o.edges.forEach(function(c){if(!(c.source==o||c.target==o))throw"Incorrect edge source and/or target";(c.target==t||c.source==t)&&s.push(c)}),s},e.prototype.getNeighborsList=function(){var t=new Set,s=this;return s.edges.forEach(function(o){if(o.source==s)t.add(o.target);else{if(o.target!=s)throw"Incorrect incidency!";t.add(o.source)}}),t},e.prototype.withChildren=function(){var t=new Set,s,o;if(t.add(this),this.child!=null)for(var c=this.child.getNodes(),h=0;hs?(this.rect.x-=(this.labelWidth-s)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal=="right"&&this.setWidth(s+this.labelWidth)),this.labelHeight&&(this.labelPosVertical=="top"?(this.rect.y-=this.labelHeight,this.setHeight(o+this.labelHeight)):this.labelPosVertical=="center"&&this.labelHeight>o?(this.rect.y-=(this.labelHeight-o)/2,this.setHeight(this.labelHeight)):this.labelPosVertical=="bottom"&&this.setHeight(o+this.labelHeight))}}},e.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==l.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},e.prototype.transform=function(t){var s=this.rect.x;s>r.WORLD_BOUNDARY?s=r.WORLD_BOUNDARY:s<-r.WORLD_BOUNDARY&&(s=-r.WORLD_BOUNDARY);var o=this.rect.y;o>r.WORLD_BOUNDARY?o=r.WORLD_BOUNDARY:o<-r.WORLD_BOUNDARY&&(o=-r.WORLD_BOUNDARY);var c=new f(s,o),h=t.inverseTransformPoint(c);this.setLocation(h.x,h.y)},e.prototype.getLeft=function(){return this.rect.x},e.prototype.getRight=function(){return this.rect.x+this.rect.width},e.prototype.getTop=function(){return this.rect.y},e.prototype.getBottom=function(){return this.rect.y+this.rect.height},e.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},C.exports=e}),(function(C,x,N){var v=N(0);function l(){}for(var n in v)l[n]=v[n];l.MAX_ITERATIONS=2500,l.DEFAULT_EDGE_LENGTH=50,l.DEFAULT_SPRING_STRENGTH=.45,l.DEFAULT_REPULSION_STRENGTH=4500,l.DEFAULT_GRAVITY_STRENGTH=.4,l.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,l.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,l.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,l.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,l.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,l.COOLING_ADAPTATION_FACTOR=.33,l.ADAPTATION_LOWER_NODE_LIMIT=1e3,l.ADAPTATION_UPPER_NODE_LIMIT=5e3,l.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,l.MAX_NODE_DISPLACEMENT=l.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,l.MIN_REPULSION_DIST=l.DEFAULT_EDGE_LENGTH/10,l.CONVERGENCE_CHECK_PERIOD=100,l.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,l.MIN_EDGE_LENGTH=1,l.GRID_CALCULATION_CHECK_PERIOD=10,C.exports=l}),(function(C,x,N){function v(l,n){l==null&&n==null?(this.x=0,this.y=0):(this.x=l,this.y=n)}v.prototype.getX=function(){return this.x},v.prototype.getY=function(){return this.y},v.prototype.setX=function(l){this.x=l},v.prototype.setY=function(l){this.y=l},v.prototype.getDifference=function(l){return new DimensionD(this.x-l.x,this.y-l.y)},v.prototype.getCopy=function(){return new v(this.x,this.y)},v.prototype.translate=function(l){return this.x+=l.width,this.y+=l.height,this},C.exports=v}),(function(C,x,N){var v=N(2),l=N(10),n=N(0),r=N(7),i=N(3),f=N(1),e=N(13),g=N(12),t=N(11);function s(c,h,T){v.call(this,T),this.estimatedSize=l.MIN_VALUE,this.margin=n.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=c,h!=null&&h instanceof r?this.graphManager=h:h!=null&&h instanceof Layout&&(this.graphManager=h.graphManager)}s.prototype=Object.create(v.prototype);for(var o in v)s[o]=v[o];s.prototype.getNodes=function(){return this.nodes},s.prototype.getEdges=function(){return this.edges},s.prototype.getGraphManager=function(){return this.graphManager},s.prototype.getParent=function(){return this.parent},s.prototype.getLeft=function(){return this.left},s.prototype.getRight=function(){return this.right},s.prototype.getTop=function(){return this.top},s.prototype.getBottom=function(){return this.bottom},s.prototype.isConnected=function(){return this.isConnected},s.prototype.add=function(c,h,T){if(h==null&&T==null){var u=c;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(u)>-1)throw"Node already in graph!";return u.owner=this,this.getNodes().push(u),u}else{var d=c;if(!(this.getNodes().indexOf(h)>-1&&this.getNodes().indexOf(T)>-1))throw"Source or target not in graph!";if(!(h.owner==T.owner&&h.owner==this))throw"Both owners must be this graph!";return h.owner!=T.owner?null:(d.source=h,d.target=T,d.isInterGraph=!1,this.getEdges().push(d),h.edges.push(d),T!=h&&T.edges.push(d),d)}},s.prototype.remove=function(c){var h=c;if(c instanceof i){if(h==null)throw"Node is null!";if(!(h.owner!=null&&h.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var T=h.edges.slice(),u,d=T.length,L=0;L-1&&G>-1))throw"Source and/or target doesn't know this edge!";u.source.edges.splice(w,1),u.target!=u.source&&u.target.edges.splice(G,1);var b=u.source.owner.getEdges().indexOf(u);if(b==-1)throw"Not in owner's edge list!";u.source.owner.getEdges().splice(b,1)}},s.prototype.updateLeftTop=function(){for(var c=l.MAX_VALUE,h=l.MAX_VALUE,T,u,d,L=this.getNodes(),b=L.length,w=0;wT&&(c=T),h>u&&(h=u)}return c==l.MAX_VALUE?null:(L[0].getParent().paddingLeft!=null?d=L[0].getParent().paddingLeft:d=this.margin,this.left=h-d,this.top=c-d,new g(this.left,this.top))},s.prototype.updateBounds=function(c){for(var h=l.MAX_VALUE,T=-l.MAX_VALUE,u=l.MAX_VALUE,d=-l.MAX_VALUE,L,b,w,G,V,Y=this.nodes,B=Y.length,A=0;AL&&(h=L),Tw&&(u=w),dL&&(h=L),Tw&&(u=w),d=this.nodes.length){var B=0;T.forEach(function(A){A.owner==c&&B++}),B==this.nodes.length&&(this.isConnected=!0)}},C.exports=s}),(function(C,x,N){var v,l=N(1);function n(r){v=N(6),this.layout=r,this.graphs=[],this.edges=[]}n.prototype.addRoot=function(){var r=this.layout.newGraph(),i=this.layout.newNode(null),f=this.add(r,i);return this.setRootGraph(f),this.rootGraph},n.prototype.add=function(r,i,f,e,g){if(f==null&&e==null&&g==null){if(r==null)throw"Graph is null!";if(i==null)throw"Parent node is null!";if(this.graphs.indexOf(r)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(r),r.parent!=null)throw"Already has a parent!";if(i.child!=null)throw"Already has a child!";return r.parent=i,i.child=r,r}else{g=f,e=i,f=r;var t=e.getOwner(),s=g.getOwner();if(!(t!=null&&t.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(s!=null&&s.getGraphManager()==this))throw"Target not in this graph mgr!";if(t==s)return f.isInterGraph=!1,t.add(f,e,g);if(f.isInterGraph=!0,f.source=e,f.target=g,this.edges.indexOf(f)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(f),!(f.source!=null&&f.target!=null))throw"Edge source and/or target is null!";if(!(f.source.edges.indexOf(f)==-1&&f.target.edges.indexOf(f)==-1))throw"Edge already in source and/or target incidency list!";return f.source.edges.push(f),f.target.edges.push(f),f}},n.prototype.remove=function(r){if(r instanceof v){var i=r;if(i.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(i==this.rootGraph||i.parent!=null&&i.parent.graphManager==this))throw"Invalid parent node!";var f=[];f=f.concat(i.getEdges());for(var e,g=f.length,t=0;t=r.getRight()?i[0]+=Math.min(r.getX()-n.getX(),n.getRight()-r.getRight()):r.getX()<=n.getX()&&r.getRight()>=n.getRight()&&(i[0]+=Math.min(n.getX()-r.getX(),r.getRight()-n.getRight())),n.getY()<=r.getY()&&n.getBottom()>=r.getBottom()?i[1]+=Math.min(r.getY()-n.getY(),n.getBottom()-r.getBottom()):r.getY()<=n.getY()&&r.getBottom()>=n.getBottom()&&(i[1]+=Math.min(n.getY()-r.getY(),r.getBottom()-n.getBottom()));var g=Math.abs((r.getCenterY()-n.getCenterY())/(r.getCenterX()-n.getCenterX()));r.getCenterY()===n.getCenterY()&&r.getCenterX()===n.getCenterX()&&(g=1);var t=g*i[0],s=i[1]/g;i[0]t)return i[0]=f,i[1]=o,i[2]=g,i[3]=Y,!1;if(eg)return i[0]=s,i[1]=e,i[2]=G,i[3]=t,!1;if(fg?(i[0]=h,i[1]=T,a=!0):(i[0]=c,i[1]=o,a=!0):p===y&&(f>g?(i[0]=s,i[1]=o,a=!0):(i[0]=u,i[1]=T,a=!0)),-m===y?g>f?(i[2]=V,i[3]=Y,E=!0):(i[2]=G,i[3]=w,E=!0):m===y&&(g>f?(i[2]=b,i[3]=w,E=!0):(i[2]=B,i[3]=Y,E=!0)),a&&E)return!1;if(f>g?e>t?(S=this.getCardinalDirection(p,y,4),D=this.getCardinalDirection(m,y,2)):(S=this.getCardinalDirection(-p,y,3),D=this.getCardinalDirection(-m,y,1)):e>t?(S=this.getCardinalDirection(-p,y,1),D=this.getCardinalDirection(-m,y,3)):(S=this.getCardinalDirection(p,y,2),D=this.getCardinalDirection(m,y,4)),!a)switch(S){case 1:W=o,F=f+-L/y,i[0]=F,i[1]=W;break;case 2:F=u,W=e+d*y,i[0]=F,i[1]=W;break;case 3:W=T,F=f+L/y,i[0]=F,i[1]=W;break;case 4:F=h,W=e+-d*y,i[0]=F,i[1]=W;break}if(!E)switch(D){case 1:Q=w,R=g+-j/y,i[2]=R,i[3]=Q;break;case 2:R=B,Q=t+A*y,i[2]=R,i[3]=Q;break;case 3:Q=Y,R=g+j/y,i[2]=R,i[3]=Q;break;case 4:R=V,Q=t+-A*y,i[2]=R,i[3]=Q;break}}return!1},l.getCardinalDirection=function(n,r,i){return n>r?i:1+i%4},l.getIntersection=function(n,r,i,f){if(f==null)return this.getIntersection2(n,r,i);var e=n.x,g=n.y,t=r.x,s=r.y,o=i.x,c=i.y,h=f.x,T=f.y,u=void 0,d=void 0,L=void 0,b=void 0,w=void 0,G=void 0,V=void 0,Y=void 0,B=void 0;return L=s-g,w=e-t,V=t*g-e*s,b=T-c,G=o-h,Y=h*c-o*T,B=L*G-b*w,B===0?null:(u=(w*Y-G*V)/B,d=(b*V-L*Y)/B,new v(u,d))},l.angleOfVector=function(n,r,i,f){var e=void 0;return n!==i?(e=Math.atan((f-r)/(i-n)),i=0){var T=(-o+Math.sqrt(o*o-4*s*c))/(2*s),u=(-o-Math.sqrt(o*o-4*s*c))/(2*s),d=null;return T>=0&&T<=1?[T]:u>=0&&u<=1?[u]:d}else return null},l.HALF_PI=.5*Math.PI,l.ONE_AND_HALF_PI=1.5*Math.PI,l.TWO_PI=2*Math.PI,l.THREE_PI=3*Math.PI,C.exports=l}),(function(C,x,N){function v(){}v.sign=function(l){return l>0?1:l<0?-1:0},v.floor=function(l){return l<0?Math.ceil(l):Math.floor(l)},v.ceil=function(l){return l<0?Math.floor(l):Math.ceil(l)},C.exports=v}),(function(C,x,N){function v(){}v.MAX_VALUE=2147483647,v.MIN_VALUE=-2147483648,C.exports=v}),(function(C,x,N){var v=(function(){function e(g,t){for(var s=0;s"u"?"undefined":v(n);return n==null||r!="object"&&r!="function"},C.exports=l}),(function(C,x,N){function v(o){if(Array.isArray(o)){for(var c=0,h=Array(o.length);c0&&c;){for(L.push(w[0]);L.length>0&&c;){var G=L[0];L.splice(0,1),d.add(G);for(var V=G.getEdges(),u=0;u-1&&w.splice(j,1)}d=new Set,b=new Map}}return o},s.prototype.createDummyNodesForBendpoints=function(o){for(var c=[],h=o.source,T=this.graphManager.calcLowestCommonAncestor(o.source,o.target),u=0;u0){for(var T=this.edgeToDummyNodes.get(h),u=0;u=0&&c.splice(Y,1);var B=b.getNeighborsList();B.forEach(function(a){if(h.indexOf(a)<0){var E=T.get(a),p=E-1;p==1&&G.push(a),T.set(a,p)}})}h=h.concat(G),(c.length==1||c.length==2)&&(u=!0,d=c[0])}return d},s.prototype.setGraphManager=function(o){this.graphManager=o},C.exports=s}),(function(C,x,N){function v(){}v.seed=1,v.x=0,v.nextDouble=function(){return v.x=Math.sin(v.seed++)*1e4,v.x-Math.floor(v.x)},C.exports=v}),(function(C,x,N){var v=N(5);function l(n,r){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}l.prototype.getWorldOrgX=function(){return this.lworldOrgX},l.prototype.setWorldOrgX=function(n){this.lworldOrgX=n},l.prototype.getWorldOrgY=function(){return this.lworldOrgY},l.prototype.setWorldOrgY=function(n){this.lworldOrgY=n},l.prototype.getWorldExtX=function(){return this.lworldExtX},l.prototype.setWorldExtX=function(n){this.lworldExtX=n},l.prototype.getWorldExtY=function(){return this.lworldExtY},l.prototype.setWorldExtY=function(n){this.lworldExtY=n},l.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},l.prototype.setDeviceOrgX=function(n){this.ldeviceOrgX=n},l.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},l.prototype.setDeviceOrgY=function(n){this.ldeviceOrgY=n},l.prototype.getDeviceExtX=function(){return this.ldeviceExtX},l.prototype.setDeviceExtX=function(n){this.ldeviceExtX=n},l.prototype.getDeviceExtY=function(){return this.ldeviceExtY},l.prototype.setDeviceExtY=function(n){this.ldeviceExtY=n},l.prototype.transformX=function(n){var r=0,i=this.lworldExtX;return i!=0&&(r=this.ldeviceOrgX+(n-this.lworldOrgX)*this.ldeviceExtX/i),r},l.prototype.transformY=function(n){var r=0,i=this.lworldExtY;return i!=0&&(r=this.ldeviceOrgY+(n-this.lworldOrgY)*this.ldeviceExtY/i),r},l.prototype.inverseTransformX=function(n){var r=0,i=this.ldeviceExtX;return i!=0&&(r=this.lworldOrgX+(n-this.ldeviceOrgX)*this.lworldExtX/i),r},l.prototype.inverseTransformY=function(n){var r=0,i=this.ldeviceExtY;return i!=0&&(r=this.lworldOrgY+(n-this.ldeviceOrgY)*this.lworldExtY/i),r},l.prototype.inverseTransformPoint=function(n){var r=new v(this.inverseTransformX(n.x),this.inverseTransformY(n.y));return r},C.exports=l}),(function(C,x,N){function v(t){if(Array.isArray(t)){for(var s=0,o=Array(t.length);sn.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*n.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(t-n.ADAPTATION_LOWER_NODE_LIMIT)/(n.ADAPTATION_UPPER_NODE_LIMIT-n.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-n.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=n.MAX_NODE_DISPLACEMENT_INCREMENTAL):(t>n.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(n.COOLING_ADAPTATION_FACTOR,1-(t-n.ADAPTATION_LOWER_NODE_LIMIT)/(n.ADAPTATION_UPPER_NODE_LIMIT-n.ADAPTATION_LOWER_NODE_LIMIT)*(1-n.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=n.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*n.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},e.prototype.calcSpringForces=function(){for(var t=this.getAllEdges(),s,o=0;o0&&arguments[0]!==void 0?arguments[0]:!0,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,o,c,h,T,u=this.getAllNodes(),d;if(this.useFRGridVariant)for(this.totalIterations%n.GRID_CALCULATION_CHECK_PERIOD==1&&t&&this.updateGrid(),d=new Set,o=0;oL||d>L)&&(t.gravitationForceX=-this.gravityConstant*h,t.gravitationForceY=-this.gravityConstant*T)):(L=s.getEstimatedSize()*this.compoundGravityRangeFactor,(u>L||d>L)&&(t.gravitationForceX=-this.gravityConstant*h*this.compoundGravityConstant,t.gravitationForceY=-this.gravityConstant*T*this.compoundGravityConstant))},e.prototype.isConverged=function(){var t,s=!1;return this.totalIterations>this.maxIterations/3&&(s=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),t=this.totalDisplacement=u.length||L>=u[0].length)){for(var b=0;be}}]),i})();C.exports=r}),(function(C,x,N){function v(){}v.svd=function(l){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=l.length,this.n=l[0].length;var n=Math.min(this.m,this.n);this.s=(function(Tt){for(var wt=[];Tt-- >0;)wt.push(0);return wt})(Math.min(this.m+1,this.n)),this.U=(function(Tt){var wt=function $t(bt){if(bt.length==0)return 0;for(var zt=[],St=0;St0;)wt.push(0);return wt})(this.n),i=(function(Tt){for(var wt=[];Tt-- >0;)wt.push(0);return wt})(this.m),f=!0,e=Math.min(this.m-1,this.n),g=Math.max(0,Math.min(this.n-2,this.m)),t=0;t=0;m--)if(this.s[m]!==0){for(var y=m+1;y=0;z--){if((function(Tt,wt){return Tt&&wt})(z0;){var J=void 0,It=void 0;for(J=a-2;J>=-1&&J!==-1;J--)if(Math.abs(r[J])<=ht+tt*(Math.abs(this.s[J])+Math.abs(this.s[J+1]))){r[J]=0;break}if(J===a-2)It=4;else{var Nt=void 0;for(Nt=a-1;Nt>=J&&Nt!==J;Nt--){var vt=(Nt!==a?Math.abs(r[Nt]):0)+(Nt!==J+1?Math.abs(r[Nt-1]):0);if(Math.abs(this.s[Nt])<=ht+tt*vt){this.s[Nt]=0;break}}Nt===J?It=3:Nt===a-1?It=1:(It=2,J=Nt)}switch(J++,It){case 1:{var it=r[a-2];r[a-2]=0;for(var ut=a-2;ut>=J;ut--){var Et=v.hypot(this.s[ut],it),Ct=this.s[ut]/Et,Dt=it/Et;this.s[ut]=Et,ut!==J&&(it=-Dt*r[ut-1],r[ut-1]=Ct*r[ut-1]);for(var mt=0;mt=this.s[J+1]);){var Lt=this.s[J];if(this.s[J]=this.s[J+1],this.s[J+1]=Lt,JMath.abs(n)?(r=n/l,r=Math.abs(l)*Math.sqrt(1+r*r)):n!=0?(r=l/n,r=Math.abs(n)*Math.sqrt(1+r*r)):r=0,r},C.exports=v}),(function(C,x,N){var v=(function(){function r(i,f){for(var e=0;e2&&arguments[2]!==void 0?arguments[2]:1,g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,t=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;l(this,r),this.sequence1=i,this.sequence2=f,this.match_score=e,this.mismatch_penalty=g,this.gap_penalty=t,this.iMax=i.length+1,this.jMax=f.length+1,this.grid=new Array(this.iMax);for(var s=0;s=0;i--){var f=this.listeners[i];f.event===n&&f.callback===r&&this.listeners.splice(i,1)}},l.emit=function(n,r){for(var i=0;i{var x={45:((n,r,i)=>{var f={};f.layoutBase=i(551),f.CoSEConstants=i(806),f.CoSEEdge=i(767),f.CoSEGraph=i(880),f.CoSEGraphManager=i(578),f.CoSELayout=i(765),f.CoSENode=i(991),f.ConstraintHandler=i(902),n.exports=f}),806:((n,r,i)=>{var f=i(551).FDLayoutConstants;function e(){}for(var g in f)e[g]=f[g];e.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,e.DEFAULT_RADIAL_SEPARATION=f.DEFAULT_EDGE_LENGTH,e.DEFAULT_COMPONENT_SEPERATION=60,e.TILE=!0,e.TILING_PADDING_VERTICAL=10,e.TILING_PADDING_HORIZONTAL=10,e.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,e.ENFORCE_CONSTRAINTS=!0,e.APPLY_LAYOUT=!0,e.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,e.TREE_REDUCTION_ON_INCREMENTAL=!0,e.PURE_INCREMENTAL=e.DEFAULT_INCREMENTAL,n.exports=e}),767:((n,r,i)=>{var f=i(551).FDLayoutEdge;function e(t,s,o){f.call(this,t,s,o)}e.prototype=Object.create(f.prototype);for(var g in f)e[g]=f[g];n.exports=e}),880:((n,r,i)=>{var f=i(551).LGraph;function e(t,s,o){f.call(this,t,s,o)}e.prototype=Object.create(f.prototype);for(var g in f)e[g]=f[g];n.exports=e}),578:((n,r,i)=>{var f=i(551).LGraphManager;function e(t){f.call(this,t)}e.prototype=Object.create(f.prototype);for(var g in f)e[g]=f[g];n.exports=e}),765:((n,r,i)=>{var f=i(551).FDLayout,e=i(578),g=i(880),t=i(991),s=i(767),o=i(806),c=i(902),h=i(551).FDLayoutConstants,T=i(551).LayoutConstants,u=i(551).Point,d=i(551).PointD,L=i(551).DimensionD,b=i(551).Layout,w=i(551).Integer,G=i(551).IGeometry,V=i(551).LGraph,Y=i(551).Transform,B=i(551).LinkedList;function A(){f.call(this),this.toBeTiled={},this.constraints={}}A.prototype=Object.create(f.prototype);for(var j in f)A[j]=f[j];A.prototype.newGraphManager=function(){var a=new e(this);return this.graphManager=a,a},A.prototype.newGraph=function(a){return new g(null,this.graphManager,a)},A.prototype.newNode=function(a){return new t(this.graphManager,a)},A.prototype.newEdge=function(a){return new s(null,null,a)},A.prototype.initParameters=function(){f.prototype.initParameters.call(this,arguments),this.isSubLayout||(o.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=o.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=o.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=h.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=h.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=h.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=h.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},A.prototype.initSpringEmbedder=function(){f.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/h.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},A.prototype.layout=function(){var a=T.DEFAULT_CREATE_BENDS_AS_NEEDED;return a&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},A.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental){if(o.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var E=new Set(this.getAllNodes()),p=this.nodesWithGravity.filter(function(S){return E.has(S)});this.graphManager.setAllNodesToApplyGravitation(p)}}else{var a=this.getFlatForest();if(a.length>0)this.positionNodesRadially(a);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var E=new Set(this.getAllNodes()),p=this.nodesWithGravity.filter(function(m){return E.has(m)});this.graphManager.setAllNodesToApplyGravitation(p),this.positionNodesRandomly()}}return Object.keys(this.constraints).length>0&&(c.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),o.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},A.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%h.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var a=new Set(this.getAllNodes()),E=this.nodesWithGravity.filter(function(y){return a.has(y)});this.graphManager.setAllNodesToApplyGravitation(E),this.graphManager.updateBounds(),this.updateGrid(),o.PURE_INCREMENTAL?this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),o.PURE_INCREMENTAL?this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var p=!this.isTreeGrowing&&!this.isGrowthFinished,m=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(p,m),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},A.prototype.getPositionsData=function(){for(var a=this.graphManager.getAllNodes(),E={},p=0;p0&&this.updateDisplacements();for(var p=0;p0&&(m.fixedNodeWeight=S)}}if(this.constraints.relativePlacementConstraint){var D=new Map,F=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(O){a.fixedNodesOnHorizontal.add(O),a.fixedNodesOnVertical.add(O)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var W=this.constraints.alignmentConstraint.vertical,p=0;p=2*O.length/3;tt--)H=Math.floor(Math.random()*(tt+1)),Z=O[tt],O[tt]=O[H],O[H]=Z;return O},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(O){if(O.left){var H=D.has(O.left)?D.get(O.left):O.left,Z=D.has(O.right)?D.get(O.right):O.right;a.nodesInRelativeHorizontal.includes(H)||(a.nodesInRelativeHorizontal.push(H),a.nodeToRelativeConstraintMapHorizontal.set(H,[]),a.dummyToNodeForVerticalAlignment.has(H)?a.nodeToTempPositionMapHorizontal.set(H,a.idToNodeMap.get(a.dummyToNodeForVerticalAlignment.get(H)[0]).getCenterX()):a.nodeToTempPositionMapHorizontal.set(H,a.idToNodeMap.get(H).getCenterX())),a.nodesInRelativeHorizontal.includes(Z)||(a.nodesInRelativeHorizontal.push(Z),a.nodeToRelativeConstraintMapHorizontal.set(Z,[]),a.dummyToNodeForVerticalAlignment.has(Z)?a.nodeToTempPositionMapHorizontal.set(Z,a.idToNodeMap.get(a.dummyToNodeForVerticalAlignment.get(Z)[0]).getCenterX()):a.nodeToTempPositionMapHorizontal.set(Z,a.idToNodeMap.get(Z).getCenterX())),a.nodeToRelativeConstraintMapHorizontal.get(H).push({right:Z,gap:O.gap}),a.nodeToRelativeConstraintMapHorizontal.get(Z).push({left:H,gap:O.gap})}else{var tt=F.has(O.top)?F.get(O.top):O.top,ht=F.has(O.bottom)?F.get(O.bottom):O.bottom;a.nodesInRelativeVertical.includes(tt)||(a.nodesInRelativeVertical.push(tt),a.nodeToRelativeConstraintMapVertical.set(tt,[]),a.dummyToNodeForHorizontalAlignment.has(tt)?a.nodeToTempPositionMapVertical.set(tt,a.idToNodeMap.get(a.dummyToNodeForHorizontalAlignment.get(tt)[0]).getCenterY()):a.nodeToTempPositionMapVertical.set(tt,a.idToNodeMap.get(tt).getCenterY())),a.nodesInRelativeVertical.includes(ht)||(a.nodesInRelativeVertical.push(ht),a.nodeToRelativeConstraintMapVertical.set(ht,[]),a.dummyToNodeForHorizontalAlignment.has(ht)?a.nodeToTempPositionMapVertical.set(ht,a.idToNodeMap.get(a.dummyToNodeForHorizontalAlignment.get(ht)[0]).getCenterY()):a.nodeToTempPositionMapVertical.set(ht,a.idToNodeMap.get(ht).getCenterY())),a.nodeToRelativeConstraintMapVertical.get(tt).push({bottom:ht,gap:O.gap}),a.nodeToRelativeConstraintMapVertical.get(ht).push({top:tt,gap:O.gap})}});else{var Q=new Map,z=new Map;this.constraints.relativePlacementConstraint.forEach(function(O){if(O.left){var H=D.has(O.left)?D.get(O.left):O.left,Z=D.has(O.right)?D.get(O.right):O.right;Q.has(H)?Q.get(H).push(Z):Q.set(H,[Z]),Q.has(Z)?Q.get(Z).push(H):Q.set(Z,[H])}else{var tt=F.has(O.top)?F.get(O.top):O.top,ht=F.has(O.bottom)?F.get(O.bottom):O.bottom;z.has(tt)?z.get(tt).push(ht):z.set(tt,[ht]),z.has(ht)?z.get(ht).push(tt):z.set(ht,[tt])}});var X=function(H,Z){var tt=[],ht=[],J=new B,It=new Set,Nt=0;return H.forEach(function(vt,it){if(!It.has(it)){tt[Nt]=[],ht[Nt]=!1;var ut=it;for(J.push(ut),It.add(ut),tt[Nt].push(ut);J.length!=0;){ut=J.shift(),Z.has(ut)&&(ht[Nt]=!0);var Et=H.get(ut);Et.forEach(function(Ct){It.has(Ct)||(J.push(Ct),It.add(Ct),tt[Nt].push(Ct))})}Nt++}}),{components:tt,isFixed:ht}},rt=X(Q,a.fixedNodesOnHorizontal);this.componentsOnHorizontal=rt.components,this.fixedComponentsOnHorizontal=rt.isFixed;var $=X(z,a.fixedNodesOnVertical);this.componentsOnVertical=$.components,this.fixedComponentsOnVertical=$.isFixed}}},A.prototype.updateDisplacements=function(){var a=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function($){var O=a.idToNodeMap.get($.nodeId);O.displacementX=0,O.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var E=this.constraints.alignmentConstraint.vertical,p=0;p1){var F;for(F=0;Fm&&(m=Math.floor(D.y)),S=Math.floor(D.x+o.DEFAULT_COMPONENT_SEPERATION)}this.transform(new d(T.WORLD_CENTER_X-D.x/2,T.WORLD_CENTER_Y-D.y/2))},A.radialLayout=function(a,E,p){var m=Math.max(this.maxDiagonalInTree(a),o.DEFAULT_RADIAL_SEPARATION);A.branchRadialLayout(E,null,0,359,0,m);var y=V.calculateBounds(a),S=new Y;S.setDeviceOrgX(y.getMinX()),S.setDeviceOrgY(y.getMinY()),S.setWorldOrgX(p.x),S.setWorldOrgY(p.y);for(var D=0;D1;){var Z=H[0];H.splice(0,1);var tt=z.indexOf(Z);tt>=0&&z.splice(tt,1),$--,X--}E!=null?O=(z.indexOf(H[0])+1)%$:O=0;for(var ht=Math.abs(m-p)/X,J=O;rt!=X;J=++J%$){var It=z[J].getOtherEnd(a);if(It!=E){var Nt=(p+rt*ht)%360,vt=(Nt+ht)%360;A.branchRadialLayout(It,a,Nt,vt,y+S,S),rt++}}},A.maxDiagonalInTree=function(a){for(var E=w.MIN_VALUE,p=0;pE&&(E=y)}return E},A.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},A.prototype.groupZeroDegreeMembers=function(){var a=this,E={};this.memberGroups={},this.idToDummyNode={};for(var p=[],m=this.graphManager.getAllNodes(),y=0;y"u"&&(E[F]=[]),E[F]=E[F].concat(S)}Object.keys(E).forEach(function(W){if(E[W].length>1){var R="DummyCompound_"+W;a.memberGroups[R]=E[W];var Q=E[W][0].getParent(),z=new t(a.graphManager);z.id=R,z.paddingLeft=Q.paddingLeft||0,z.paddingRight=Q.paddingRight||0,z.paddingBottom=Q.paddingBottom||0,z.paddingTop=Q.paddingTop||0,a.idToDummyNode[R]=z;var X=a.getGraphManager().add(a.newGraph(),z),rt=Q.getChild();rt.add(z);for(var $=0;$y?(m.rect.x-=(m.labelWidth-y)/2,m.setWidth(m.labelWidth),m.labelMarginLeft=(m.labelWidth-y)/2):m.labelPosHorizontal=="right"&&m.setWidth(y+m.labelWidth)),m.labelHeight&&(m.labelPosVertical=="top"?(m.rect.y-=m.labelHeight,m.setHeight(S+m.labelHeight),m.labelMarginTop=m.labelHeight):m.labelPosVertical=="center"&&m.labelHeight>S?(m.rect.y-=(m.labelHeight-S)/2,m.setHeight(m.labelHeight),m.labelMarginTop=(m.labelHeight-S)/2):m.labelPosVertical=="bottom"&&m.setHeight(S+m.labelHeight))}})},A.prototype.repopulateCompounds=function(){for(var a=this.compoundOrder.length-1;a>=0;a--){var E=this.compoundOrder[a],p=E.id,m=E.paddingLeft,y=E.paddingTop,S=E.labelMarginLeft,D=E.labelMarginTop;this.adjustLocations(this.tiledMemberPack[p],E.rect.x,E.rect.y,m,y,S,D)}},A.prototype.repopulateZeroDegreeMembers=function(){var a=this,E=this.tiledZeroDegreePack;Object.keys(E).forEach(function(p){var m=a.idToDummyNode[p],y=m.paddingLeft,S=m.paddingTop,D=m.labelMarginLeft,F=m.labelMarginTop;a.adjustLocations(E[p],m.rect.x,m.rect.y,y,S,D,F)})},A.prototype.getToBeTiled=function(a){var E=a.id;if(this.toBeTiled[E]!=null)return this.toBeTiled[E];var p=a.getChild();if(p==null)return this.toBeTiled[E]=!1,!1;for(var m=p.getNodes(),y=0;y0)return this.toBeTiled[E]=!1,!1;if(S.getChild()==null){this.toBeTiled[S.id]=!1;continue}if(!this.getToBeTiled(S))return this.toBeTiled[E]=!1,!1}return this.toBeTiled[E]=!0,!0},A.prototype.getNodeDegree=function(a){a.id;for(var E=a.getEdges(),p=0,m=0;mQ&&(Q=X.rect.height)}p+=Q+a.verticalPadding}},A.prototype.tileCompoundMembers=function(a,E){var p=this;this.tiledMemberPack=[],Object.keys(a).forEach(function(m){var y=E[m];if(p.tiledMemberPack[m]=p.tileNodes(a[m],y.paddingLeft+y.paddingRight),y.rect.width=p.tiledMemberPack[m].width,y.rect.height=p.tiledMemberPack[m].height,y.setCenter(p.tiledMemberPack[m].centerX,p.tiledMemberPack[m].centerY),y.labelMarginLeft=0,y.labelMarginTop=0,o.NODE_DIMENSIONS_INCLUDE_LABELS){var S=y.rect.width,D=y.rect.height;y.labelWidth&&(y.labelPosHorizontal=="left"?(y.rect.x-=y.labelWidth,y.setWidth(S+y.labelWidth),y.labelMarginLeft=y.labelWidth):y.labelPosHorizontal=="center"&&y.labelWidth>S?(y.rect.x-=(y.labelWidth-S)/2,y.setWidth(y.labelWidth),y.labelMarginLeft=(y.labelWidth-S)/2):y.labelPosHorizontal=="right"&&y.setWidth(S+y.labelWidth)),y.labelHeight&&(y.labelPosVertical=="top"?(y.rect.y-=y.labelHeight,y.setHeight(D+y.labelHeight),y.labelMarginTop=y.labelHeight):y.labelPosVertical=="center"&&y.labelHeight>D?(y.rect.y-=(y.labelHeight-D)/2,y.setHeight(y.labelHeight),y.labelMarginTop=(y.labelHeight-D)/2):y.labelPosVertical=="bottom"&&y.setHeight(D+y.labelHeight))}})},A.prototype.tileNodes=function(a,E){var p=this.tileNodesByFavoringDim(a,E,!0),m=this.tileNodesByFavoringDim(a,E,!1),y=this.getOrgRatio(p),S=this.getOrgRatio(m),D;return SF&&(F=$.getWidth())});var W=S/y,R=D/y,Q=Math.pow(p-m,2)+4*(W+m)*(R+p)*y,z=(m-p+Math.sqrt(Q))/(2*(W+m)),X;E?(X=Math.ceil(z),X==z&&X++):X=Math.floor(z);var rt=X*(W+m)-m;return F>rt&&(rt=F),rt+=m*2,rt},A.prototype.tileNodesByFavoringDim=function(a,E,p){var m=o.TILING_PADDING_VERTICAL,y=o.TILING_PADDING_HORIZONTAL,S=o.TILING_COMPARE_BY,D={rows:[],rowWidth:[],rowHeight:[],width:0,height:E,verticalPadding:m,horizontalPadding:y,centerX:0,centerY:0};S&&(D.idealRowWidth=this.calcIdealRowWidth(a,p));var F=function(O){return O.rect.width*O.rect.height},W=function(O,H){return F(H)-F(O)};a.sort(function($,O){var H=W;return D.idealRowWidth?(H=S,H($.id,O.id)):H($,O)});for(var R=0,Q=0,z=0;z0&&(D+=a.horizontalPadding),a.rowWidth[p]=D,a.width0&&(F+=a.verticalPadding);var W=0;F>a.rowHeight[p]&&(W=a.rowHeight[p],a.rowHeight[p]=F,W=a.rowHeight[p]-W),a.height+=W,a.rows[p].push(E)},A.prototype.getShortestRowIndex=function(a){for(var E=-1,p=Number.MAX_VALUE,m=0;mp&&(E=m,p=a.rowWidth[m]);return E},A.prototype.canAddHorizontal=function(a,E,p){if(a.idealRowWidth){var m=a.rows.length-1,y=a.rowWidth[m];return y+E+a.horizontalPadding<=a.idealRowWidth}var S=this.getShortestRowIndex(a);if(S<0)return!0;var D=a.rowWidth[S];if(D+a.horizontalPadding+E<=a.width)return!0;var F=0;a.rowHeight[S]0&&(F=p+a.verticalPadding-a.rowHeight[S]);var W;a.width-D>=E+a.horizontalPadding?W=(a.height+F)/(D+E+a.horizontalPadding):W=(a.height+F)/a.width,F=p+a.verticalPadding;var R;return a.widthS&&E!=p){m.splice(-1,1),a.rows[p].push(y),a.rowWidth[E]=a.rowWidth[E]-S,a.rowWidth[p]=a.rowWidth[p]+S,a.width=a.rowWidth[instance.getLongestRowIndex(a)];for(var D=Number.MIN_VALUE,F=0;FD&&(D=m[F].height);E>0&&(D+=a.verticalPadding);var W=a.rowHeight[E]+a.rowHeight[p];a.rowHeight[E]=D,a.rowHeight[p]0)for(var rt=y;rt<=S;rt++)X[0]+=this.grid[rt][D-1].length+this.grid[rt][D].length-1;if(S0)for(var rt=D;rt<=F;rt++)X[3]+=this.grid[y-1][rt].length+this.grid[y][rt].length-1;for(var $=w.MAX_VALUE,O,H,Z=0;Z{var f=i(551).FDLayoutNode,e=i(551).IMath;function g(s,o,c,h){f.call(this,s,o,c,h)}g.prototype=Object.create(f.prototype);for(var t in f)g[t]=f[t];g.prototype.calculateDisplacement=function(){var s=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=s.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=s.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=s.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=s.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>s.coolingFactor*s.maxNodeDisplacement&&(this.displacementX=s.coolingFactor*s.maxNodeDisplacement*e.sign(this.displacementX)),Math.abs(this.displacementY)>s.coolingFactor*s.maxNodeDisplacement&&(this.displacementY=s.coolingFactor*s.maxNodeDisplacement*e.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},g.prototype.propogateDisplacementToChildren=function(s,o){for(var c=this.getChild().getNodes(),h,T=0;T{function f(c){if(Array.isArray(c)){for(var h=0,T=Array(c.length);h0){var Lt=0;ot.forEach(function(st){k=="horizontal"?(et.set(st,u.has(st)?d[u.get(st)]:q.get(st)),Lt+=et.get(st)):(et.set(st,u.has(st)?L[u.get(st)]:q.get(st)),Lt+=et.get(st))}),Lt=Lt/ot.length,lt.forEach(function(st){K.has(st)||et.set(st,Lt)})}else{var ft=0;lt.forEach(function(st){k=="horizontal"?ft+=u.has(st)?d[u.get(st)]:q.get(st):ft+=u.has(st)?L[u.get(st)]:q.get(st)}),ft=ft/lt.length,lt.forEach(function(st){et.set(st,ft)})}});for(var Mt=function(){var ot=dt.shift(),Lt=U.get(ot);Lt.forEach(function(ft){if(et.get(ft.id)st&&(st=Zt),KtXt&&(Xt=Kt)}}catch(ee){wt=!0,$t=ee}finally{try{!Tt&&bt.return&&bt.return()}finally{if(wt)throw $t}}var ce=(Lt+st)/2-(ft+Xt)/2,Qt=!0,jt=!1,_t=void 0;try{for(var Jt=lt[Symbol.iterator](),oe;!(Qt=(oe=Jt.next()).done);Qt=!0){var te=oe.value;et.set(te,et.get(te)+ce)}}catch(ee){jt=!0,_t=ee}finally{try{!Qt&&Jt.return&&Jt.return()}finally{if(jt)throw _t}}})}return et},j=function(U){var k=0,K=0,q=0,at=0;if(U.forEach(function(_){_.left?d[u.get(_.left)]-d[u.get(_.right)]>=0?k++:K++:L[u.get(_.top)]-L[u.get(_.bottom)]>=0?q++:at++}),k>K&&q>at)for(var gt=0;gtK)for(var nt=0;ntat)for(var et=0;et1)h.fixedNodeConstraint.forEach(function(P,U){m[U]=[P.position.x,P.position.y],y[U]=[d[u.get(P.nodeId)],L[u.get(P.nodeId)]]}),S=!0;else if(h.alignmentConstraint)(function(){var P=0;if(h.alignmentConstraint.vertical){for(var U=h.alignmentConstraint.vertical,k=function(et){var _=new Set;U[et].forEach(function(pt){_.add(pt)});var dt=new Set([].concat(f(_)).filter(function(pt){return F.has(pt)})),Mt=void 0;dt.size>0?Mt=d[u.get(dt.values().next().value)]:Mt=B(_).x,U[et].forEach(function(pt){m[P]=[Mt,L[u.get(pt)]],y[P]=[d[u.get(pt)],L[u.get(pt)]],P++})},K=0;K0?Mt=d[u.get(dt.values().next().value)]:Mt=B(_).y,q[et].forEach(function(pt){m[P]=[d[u.get(pt)],Mt],y[P]=[d[u.get(pt)],L[u.get(pt)]],P++})},gt=0;gtz&&(z=Q[rt].length,X=rt);if(z0){var mt={x:0,y:0};h.fixedNodeConstraint.forEach(function(P,U){var k={x:d[u.get(P.nodeId)],y:L[u.get(P.nodeId)]},K=P.position,q=Y(K,k);mt.x+=q.x,mt.y+=q.y}),mt.x/=h.fixedNodeConstraint.length,mt.y/=h.fixedNodeConstraint.length,d.forEach(function(P,U){d[U]+=mt.x}),L.forEach(function(P,U){L[U]+=mt.y}),h.fixedNodeConstraint.forEach(function(P){d[u.get(P.nodeId)]=P.position.x,L[u.get(P.nodeId)]=P.position.y})}if(h.alignmentConstraint){if(h.alignmentConstraint.vertical)for(var Ot=h.alignmentConstraint.vertical,Rt=function(U){var k=new Set;Ot[U].forEach(function(at){k.add(at)});var K=new Set([].concat(f(k)).filter(function(at){return F.has(at)})),q=void 0;K.size>0?q=d[u.get(K.values().next().value)]:q=B(k).x,k.forEach(function(at){F.has(at)||(d[u.get(at)]=q)})},Ht=0;Ht0?q=L[u.get(K.values().next().value)]:q=B(k).y,k.forEach(function(at){F.has(at)||(L[u.get(at)]=q)})},Ft=0;Ft{n.exports=C})},N={};function v(n){var r=N[n];if(r!==void 0)return r.exports;var i=N[n]={exports:{}};return x[n](i,i.exports,v),i.exports}var l=v(45);return l})()})})(le)),le.exports}var mr=he.exports,xe;function Er(){return xe||(xe=1,(function(I,M){(function(x,N){I.exports=N(yr())})(mr,function(C){return(()=>{var x={658:(n=>{n.exports=Object.assign!=null?Object.assign.bind(Object):function(r){for(var i=arguments.length,f=Array(i>1?i-1:0),e=1;e{var f=(function(){function t(s,o){var c=[],h=!0,T=!1,u=void 0;try{for(var d=s[Symbol.iterator](),L;!(h=(L=d.next()).done)&&(c.push(L.value),!(o&&c.length===o));h=!0);}catch(b){T=!0,u=b}finally{try{!h&&d.return&&d.return()}finally{if(T)throw u}}return c}return function(s,o){if(Array.isArray(s))return s;if(Symbol.iterator in Object(s))return t(s,o);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),e=i(140).layoutBase.LinkedList,g={};g.getTopMostNodes=function(t){for(var s={},o=0;o0&&S.merge(R)});for(var D=0;D1){L=u[0],b=L.connectedEdges().length,u.forEach(function(y){y.connectedEdges().length0&&c.set("dummy"+(c.size+1),V),Y},g.relocateComponent=function(t,s,o){if(!o.fixedNodeConstraint){var c=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY,T=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;if(o.quality=="draft"){var d=!0,L=!1,b=void 0;try{for(var w=s.nodeIndexes[Symbol.iterator](),G;!(d=(G=w.next()).done);d=!0){var V=G.value,Y=f(V,2),B=Y[0],A=Y[1],j=o.cy.getElementById(B);if(j){var a=j.boundingBox(),E=s.xCoords[A]-a.w/2,p=s.xCoords[A]+a.w/2,m=s.yCoords[A]-a.h/2,y=s.yCoords[A]+a.h/2;Eh&&(h=p),mu&&(u=y)}}}catch(R){L=!0,b=R}finally{try{!d&&w.return&&w.return()}finally{if(L)throw b}}var S=t.x-(h+c)/2,D=t.y-(u+T)/2;s.xCoords=s.xCoords.map(function(R){return R+S}),s.yCoords=s.yCoords.map(function(R){return R+D})}else{Object.keys(s).forEach(function(R){var Q=s[R],z=Q.getRect().x,X=Q.getRect().x+Q.getRect().width,rt=Q.getRect().y,$=Q.getRect().y+Q.getRect().height;zh&&(h=X),rtu&&(u=$)});var F=t.x-(h+c)/2,W=t.y-(u+T)/2;Object.keys(s).forEach(function(R){var Q=s[R];Q.setCenter(Q.getCenterX()+F,Q.getCenterY()+W)})}}},g.calcBoundingBox=function(t,s,o,c){for(var h=Number.MAX_SAFE_INTEGER,T=Number.MIN_SAFE_INTEGER,u=Number.MAX_SAFE_INTEGER,d=Number.MIN_SAFE_INTEGER,L=void 0,b=void 0,w=void 0,G=void 0,V=t.descendants().not(":parent"),Y=V.length,B=0;BL&&(h=L),Tw&&(u=w),d{var f=i(548),e=i(140).CoSELayout,g=i(140).CoSENode,t=i(140).layoutBase.PointD,s=i(140).layoutBase.DimensionD,o=i(140).layoutBase.LayoutConstants,c=i(140).layoutBase.FDLayoutConstants,h=i(140).CoSEConstants,T=function(d,L){var b=d.cy,w=d.eles,G=w.nodes(),V=w.edges(),Y=void 0,B=void 0,A=void 0,j={};d.randomize&&(Y=L.nodeIndexes,B=L.xCoords,A=L.yCoords);var a=function(R){return typeof R=="function"},E=function(R,Q){return a(R)?R(Q):R},p=f.calcParentsWithoutChildren(b,w),m=function W(R,Q,z,X){for(var rt=Q.length,$=0;$0){var J=void 0;J=z.getGraphManager().add(z.newGraph(),Z),W(J,H,z,X)}}},y=function(R,Q,z){for(var X=0,rt=0,$=0;$0?h.DEFAULT_EDGE_LENGTH=c.DEFAULT_EDGE_LENGTH=X/rt:a(d.idealEdgeLength)?h.DEFAULT_EDGE_LENGTH=c.DEFAULT_EDGE_LENGTH=50:h.DEFAULT_EDGE_LENGTH=c.DEFAULT_EDGE_LENGTH=d.idealEdgeLength,h.MIN_REPULSION_DIST=c.MIN_REPULSION_DIST=c.DEFAULT_EDGE_LENGTH/10,h.DEFAULT_RADIAL_SEPARATION=c.DEFAULT_EDGE_LENGTH)},S=function(R,Q){Q.fixedNodeConstraint&&(R.constraints.fixedNodeConstraint=Q.fixedNodeConstraint),Q.alignmentConstraint&&(R.constraints.alignmentConstraint=Q.alignmentConstraint),Q.relativePlacementConstraint&&(R.constraints.relativePlacementConstraint=Q.relativePlacementConstraint)};d.nestingFactor!=null&&(h.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=c.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=d.nestingFactor),d.gravity!=null&&(h.DEFAULT_GRAVITY_STRENGTH=c.DEFAULT_GRAVITY_STRENGTH=d.gravity),d.numIter!=null&&(h.MAX_ITERATIONS=c.MAX_ITERATIONS=d.numIter),d.gravityRange!=null&&(h.DEFAULT_GRAVITY_RANGE_FACTOR=c.DEFAULT_GRAVITY_RANGE_FACTOR=d.gravityRange),d.gravityCompound!=null&&(h.DEFAULT_COMPOUND_GRAVITY_STRENGTH=c.DEFAULT_COMPOUND_GRAVITY_STRENGTH=d.gravityCompound),d.gravityRangeCompound!=null&&(h.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=c.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=d.gravityRangeCompound),d.initialEnergyOnIncremental!=null&&(h.DEFAULT_COOLING_FACTOR_INCREMENTAL=c.DEFAULT_COOLING_FACTOR_INCREMENTAL=d.initialEnergyOnIncremental),d.tilingCompareBy!=null&&(h.TILING_COMPARE_BY=d.tilingCompareBy),d.quality=="proof"?o.QUALITY=2:o.QUALITY=0,h.NODE_DIMENSIONS_INCLUDE_LABELS=c.NODE_DIMENSIONS_INCLUDE_LABELS=o.NODE_DIMENSIONS_INCLUDE_LABELS=d.nodeDimensionsIncludeLabels,h.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=o.DEFAULT_INCREMENTAL=!d.randomize,h.ANIMATE=c.ANIMATE=o.ANIMATE=d.animate,h.TILE=d.tile,h.TILING_PADDING_VERTICAL=typeof d.tilingPaddingVertical=="function"?d.tilingPaddingVertical.call():d.tilingPaddingVertical,h.TILING_PADDING_HORIZONTAL=typeof d.tilingPaddingHorizontal=="function"?d.tilingPaddingHorizontal.call():d.tilingPaddingHorizontal,h.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=o.DEFAULT_INCREMENTAL=!0,h.PURE_INCREMENTAL=!d.randomize,o.DEFAULT_UNIFORM_LEAF_NODE_SIZES=d.uniformNodeDimensions,d.step=="transformed"&&(h.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,h.ENFORCE_CONSTRAINTS=!1,h.APPLY_LAYOUT=!1),d.step=="enforced"&&(h.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,h.ENFORCE_CONSTRAINTS=!0,h.APPLY_LAYOUT=!1),d.step=="cose"&&(h.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,h.ENFORCE_CONSTRAINTS=!1,h.APPLY_LAYOUT=!0),d.step=="all"&&(d.randomize?h.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:h.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,h.ENFORCE_CONSTRAINTS=!0,h.APPLY_LAYOUT=!0),d.fixedNodeConstraint||d.alignmentConstraint||d.relativePlacementConstraint?h.TREE_REDUCTION_ON_INCREMENTAL=!1:h.TREE_REDUCTION_ON_INCREMENTAL=!0;var D=new e,F=D.newGraphManager();return m(F.addRoot(),f.getTopMostNodes(G),D,d),y(D,F,V),S(D,d),D.runLayout(),j};n.exports={coseLayout:T}}),212:((n,r,i)=>{var f=(function(){function d(L,b){for(var w=0;w0)if(p){var S=t.getTopMostNodes(w.eles.nodes());if(A=t.connectComponents(G,w.eles,S),A.forEach(function(vt){var it=vt.boundingBox();j.push({x:it.x1+it.w/2,y:it.y1+it.h/2})}),w.randomize&&A.forEach(function(vt){w.eles=vt,Y.push(o(w))}),w.quality=="default"||w.quality=="proof"){var D=G.collection();if(w.tile){var F=new Map,W=[],R=[],Q=0,z={nodeIndexes:F,xCoords:W,yCoords:R},X=[];if(A.forEach(function(vt,it){vt.edges().length==0&&(vt.nodes().forEach(function(ut,Et){D.merge(vt.nodes()[Et]),ut.isParent()||(z.nodeIndexes.set(vt.nodes()[Et].id(),Q++),z.xCoords.push(vt.nodes()[0].position().x),z.yCoords.push(vt.nodes()[0].position().y))}),X.push(it))}),D.length>1){var rt=D.boundingBox();j.push({x:rt.x1+rt.w/2,y:rt.y1+rt.h/2}),A.push(D),Y.push(z);for(var $=X.length-1;$>=0;$--)A.splice(X[$],1),Y.splice(X[$],1),j.splice(X[$],1)}}A.forEach(function(vt,it){w.eles=vt,B.push(h(w,Y[it])),t.relocateComponent(j[it],B[it],w)})}else A.forEach(function(vt,it){t.relocateComponent(j[it],Y[it],w)});var O=new Set;if(A.length>1){var H=[],Z=V.filter(function(vt){return vt.css("display")=="none"});A.forEach(function(vt,it){var ut=void 0;if(w.quality=="draft"&&(ut=Y[it].nodeIndexes),vt.nodes().not(Z).length>0){var Et={};Et.edges=[],Et.nodes=[];var Ct=void 0;vt.nodes().not(Z).forEach(function(Dt){if(w.quality=="draft")if(!Dt.isParent())Ct=ut.get(Dt.id()),Et.nodes.push({x:Y[it].xCoords[Ct]-Dt.boundingbox().w/2,y:Y[it].yCoords[Ct]-Dt.boundingbox().h/2,width:Dt.boundingbox().w,height:Dt.boundingbox().h});else{var mt=t.calcBoundingBox(Dt,Y[it].xCoords,Y[it].yCoords,ut);Et.nodes.push({x:mt.topLeftX,y:mt.topLeftY,width:mt.width,height:mt.height})}else B[it][Dt.id()]&&Et.nodes.push({x:B[it][Dt.id()].getLeft(),y:B[it][Dt.id()].getTop(),width:B[it][Dt.id()].getWidth(),height:B[it][Dt.id()].getHeight()})}),vt.edges().forEach(function(Dt){var mt=Dt.source(),Ot=Dt.target();if(mt.css("display")!="none"&&Ot.css("display")!="none")if(w.quality=="draft"){var Rt=ut.get(mt.id()),Ht=ut.get(Ot.id()),Ut=[],Pt=[];if(mt.isParent()){var Ft=t.calcBoundingBox(mt,Y[it].xCoords,Y[it].yCoords,ut);Ut.push(Ft.topLeftX+Ft.width/2),Ut.push(Ft.topLeftY+Ft.height/2)}else Ut.push(Y[it].xCoords[Rt]),Ut.push(Y[it].yCoords[Rt]);if(Ot.isParent()){var Yt=t.calcBoundingBox(Ot,Y[it].xCoords,Y[it].yCoords,ut);Pt.push(Yt.topLeftX+Yt.width/2),Pt.push(Yt.topLeftY+Yt.height/2)}else Pt.push(Y[it].xCoords[Ht]),Pt.push(Y[it].yCoords[Ht]);Et.edges.push({startX:Ut[0],startY:Ut[1],endX:Pt[0],endY:Pt[1]})}else B[it][mt.id()]&&B[it][Ot.id()]&&Et.edges.push({startX:B[it][mt.id()].getCenterX(),startY:B[it][mt.id()].getCenterY(),endX:B[it][Ot.id()].getCenterX(),endY:B[it][Ot.id()].getCenterY()})}),Et.nodes.length>0&&(H.push(Et),O.add(it))}});var tt=E.packComponents(H,w.randomize).shifts;if(w.quality=="draft")Y.forEach(function(vt,it){var ut=vt.xCoords.map(function(Ct){return Ct+tt[it].dx}),Et=vt.yCoords.map(function(Ct){return Ct+tt[it].dy});vt.xCoords=ut,vt.yCoords=Et});else{var ht=0;O.forEach(function(vt){Object.keys(B[vt]).forEach(function(it){var ut=B[vt][it];ut.setCenter(ut.getCenterX()+tt[ht].dx,ut.getCenterY()+tt[ht].dy)}),ht++})}}}else{var m=w.eles.boundingBox();if(j.push({x:m.x1+m.w/2,y:m.y1+m.h/2}),w.randomize){var y=o(w);Y.push(y)}w.quality=="default"||w.quality=="proof"?(B.push(h(w,Y[0])),t.relocateComponent(j[0],B[0],w)):t.relocateComponent(j[0],Y[0],w)}var J=function(it,ut){if(w.quality=="default"||w.quality=="proof"){typeof it=="number"&&(it=ut);var Et=void 0,Ct=void 0,Dt=it.data("id");return B.forEach(function(Ot){Dt in Ot&&(Et={x:Ot[Dt].getRect().getCenterX(),y:Ot[Dt].getRect().getCenterY()},Ct=Ot[Dt])}),w.nodeDimensionsIncludeLabels&&(Ct.labelWidth&&(Ct.labelPosHorizontal=="left"?Et.x+=Ct.labelWidth/2:Ct.labelPosHorizontal=="right"&&(Et.x-=Ct.labelWidth/2)),Ct.labelHeight&&(Ct.labelPosVertical=="top"?Et.y+=Ct.labelHeight/2:Ct.labelPosVertical=="bottom"&&(Et.y-=Ct.labelHeight/2))),Et==null&&(Et={x:it.position("x"),y:it.position("y")}),{x:Et.x,y:Et.y}}else{var mt=void 0;return Y.forEach(function(Ot){var Rt=Ot.nodeIndexes.get(it.id());Rt!=null&&(mt={x:Ot.xCoords[Rt],y:Ot.yCoords[Rt]})}),mt==null&&(mt={x:it.position("x"),y:it.position("y")}),{x:mt.x,y:mt.y}}};if(w.quality=="default"||w.quality=="proof"||w.randomize){var It=t.calcParentsWithoutChildren(G,V),Nt=V.filter(function(vt){return vt.css("display")=="none"});w.eles=V.not(Nt),V.nodes().not(":parent").not(Nt).layoutPositions(b,w,J),It.length>0&&It.forEach(function(vt){vt.position(J(vt))})}else console.log("If randomize option is set to false, then quality option must be 'default' or 'proof'.")}}]),d})();n.exports=u}),657:((n,r,i)=>{var f=i(548),e=i(140).layoutBase.Matrix,g=i(140).layoutBase.SVD,t=function(o){var c=o.cy,h=o.eles,T=h.nodes(),u=h.nodes(":parent"),d=new Map,L=new Map,b=new Map,w=[],G=[],V=[],Y=[],B=[],A=[],j=[],a=[],E=void 0,p=1e8,m=1e-9,y=o.piTol,S=o.samplingType,D=o.nodeSeparation,F=void 0,W=function(){for(var U=0,k=0,K=!1;k=at;){nt=q[at++];for(var xt=w[nt],lt=0;ltdt&&(dt=B[Lt],Mt=Lt)}return Mt},Q=function(U){var k=void 0;if(U){k=Math.floor(Math.random()*E);for(var q=0;q=1)break;_=et}for(var pt=0;pt=1)break;_=et}for(var lt=0;lt0&&(k.isParent()?w[U].push(b.get(k.id())):w[U].push(k.id()))})});var Nt=function(U){var k=L.get(U),K=void 0;d.get(U).forEach(function(q){c.getElementById(q).isParent()?K=b.get(q):K=q,w[k].push(K),w[L.get(K)].push(U)})},vt=!0,it=!1,ut=void 0;try{for(var Et=d.keys()[Symbol.iterator](),Ct;!(vt=(Ct=Et.next()).done);vt=!0){var Dt=Ct.value;Nt(Dt)}}catch(P){it=!0,ut=P}finally{try{!vt&&Et.return&&Et.return()}finally{if(it)throw ut}}E=L.size;var mt=void 0;if(E>2){F=E{var f=i(212),e=function(t){t&&t("layout","fcose",f)};typeof cytoscape<"u"&&e(cytoscape),n.exports=e}),140:(n=>{n.exports=C})},N={};function v(n){var r=N[n];if(r!==void 0)return r.exports;var i=N[n]={exports:{}};return x[n](i,i.exports,v),i.exports}var l=v(579);return l})()})})(he)),he.exports}var Tr=Er();const Nr=gr(Tr);var Ie={L:"left",R:"right",T:"top",B:"bottom"},Re={L:ct(I=>`${I},${I/2} 0,${I} 0,0`,"L"),R:ct(I=>`0,${I/2} ${I},0 ${I},${I}`,"R"),T:ct(I=>`0,0 ${I},0 ${I/2},${I}`,"T"),B:ct(I=>`${I/2},0 ${I},${I} 0,${I}`,"B")},se={L:ct((I,M)=>I-M+2,"L"),R:ct((I,M)=>I-2,"R"),T:ct((I,M)=>I-M+2,"T"),B:ct((I,M)=>I-2,"B")},Lr=ct(function(I){return Wt(I)?I==="L"?"R":"L":I==="T"?"B":"T"},"getOppositeArchitectureDirection"),Se=ct(function(I){const M=I;return M==="L"||M==="R"||M==="T"||M==="B"},"isArchitectureDirection"),Wt=ct(function(I){const M=I;return M==="L"||M==="R"},"isArchitectureDirectionX"),qt=ct(function(I){const M=I;return M==="T"||M==="B"},"isArchitectureDirectionY"),Ne=ct(function(I,M){const C=Wt(I)&&qt(M),x=qt(I)&&Wt(M);return C||x},"isArchitectureDirectionXY"),wr=ct(function(I){const M=I[0],C=I[1],x=Wt(M)&&qt(C),N=qt(M)&&Wt(C);return x||N},"isArchitecturePairXY"),Cr=ct(function(I){return I!=="LL"&&I!=="RR"&&I!=="TT"&&I!=="BB"},"isValidArchitectureDirectionPair"),ye=ct(function(I,M){const C=`${I}${M}`;return Cr(C)?C:void 0},"getArchitectureDirectionPair"),Mr=ct(function([I,M],C){const x=C[0],N=C[1];return Wt(x)?qt(N)?[I+(x==="L"?-1:1),M+(N==="T"?1:-1)]:[I+(x==="L"?-1:1),M]:Wt(N)?[I+(N==="L"?1:-1),M+(x==="T"?1:-1)]:[I,M+(x==="T"?1:-1)]},"shiftPositionByArchitectureDirectionPair"),Ar=ct(function(I){return I==="LT"||I==="TL"?[1,1]:I==="BL"||I==="LB"?[1,-1]:I==="BR"||I==="RB"?[-1,-1]:[-1,1]},"getArchitectureDirectionXYFactors"),Dr=ct(function(I,M){return Ne(I,M)?"bend":Wt(I)?"horizontal":"vertical"},"getArchitectureDirectionAlignment"),Or=ct(function(I){return I.type==="service"},"isArchitectureService"),xr=ct(function(I){return I.type==="junction"},"isArchitectureJunction"),Pe=ct((I,M)=>{const[C,x]=[I,M].sort();return`${JSON.stringify(C)}-${JSON.stringify(x)}`},"architectureGroupAlignmentKey"),Ge=ct(I=>I.data(),"edgeData"),ie=ct(I=>I.data(),"nodeData"),Ir=or.architecture,ae,Ue=(ae=class{constructor(){this.nodes=new Map,this.groups=new Map,this.edges=[],this.layoutHints=[],this.registeredIds=new Map,this.elements=new Map,this.diagramId="",this.setAccTitle=Ke,this.getAccTitle=je,this.setDiagramTitle=_e,this.getDiagramTitle=tr,this.getAccDescription=er,this.setAccDescription=rr,this.clear()}setDiagramId(M){this.diagramId=M}getDiagramId(){return this.diagramId}clear(){this.nodes=new Map,this.groups=new Map,this.edges=[],this.layoutHints=[],this.registeredIds=new Map,this.dataStructures=void 0,this.elements=new Map,this.diagramId="",ir()}addService({id:M,icon:C,in:x,title:N,iconText:v}){if(this.registeredIds.has(M))throw new Error(`The service id [${M}] is already in use by another ${this.registeredIds.get(M)}`);if(x!==void 0){if(M===x)throw new Error(`The service [${M}] cannot be placed within itself`);if(!this.registeredIds.has(x))throw new Error(`The service [${M}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds.get(x)==="node")throw new Error(`The service [${M}]'s parent is not a group`)}this.registeredIds.set(M,"node"),this.nodes.set(M,{id:M,type:"service",icon:C,iconText:v,title:N,edges:[],in:x})}getServices(){return[...this.nodes.values()].filter(Or)}addJunction({id:M,in:C}){if(this.registeredIds.has(M))throw new Error(`The junction id [${M}] is already in use by another ${this.registeredIds.get(M)}`);if(C!==void 0){if(M===C)throw new Error(`The junction [${M}] cannot be placed within itself`);if(!this.registeredIds.has(C))throw new Error(`The junction [${M}]'s parent does not exist. Please make sure the parent is created before this junction`);if(this.registeredIds.get(C)==="node")throw new Error(`The junction [${M}]'s parent is not a group`)}this.registeredIds.set(M,"node"),this.nodes.set(M,{id:M,type:"junction",edges:[],in:C})}getJunctions(){return[...this.nodes.values()].filter(xr)}getNodes(){return[...this.nodes.values()]}getNode(M){return this.nodes.get(M)??null}addGroup({id:M,icon:C,in:x,title:N}){if(this.registeredIds.has(M))throw new Error(`The group id [${M}] is already in use by another ${this.registeredIds.get(M)}`);if(x!==void 0){if(M===x)throw new Error(`The group [${M}] cannot be placed within itself`);if(!this.registeredIds.has(x))throw new Error(`The group [${M}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds.get(x)==="node")throw new Error(`The group [${M}]'s parent is not a group`)}this.registeredIds.set(M,"group"),this.groups.set(M,{id:M,icon:C,title:N,in:x})}getGroups(){return[...this.groups.values()]}addEdge({lhsId:M,rhsId:C,lhsDir:x,rhsDir:N,lhsInto:v,rhsInto:l,lhsGroup:n,rhsGroup:r,title:i}){if(!Se(x))throw new Error(`Invalid direction given for left hand side of edge ${M}--${C}. Expected (L,R,T,B) got ${String(x)}`);if(!Se(N))throw new Error(`Invalid direction given for right hand side of edge ${M}--${C}. Expected (L,R,T,B) got ${String(N)}`);if(!this.nodes.has(M)&&!this.groups.has(M))throw new Error(`The left-hand id [${M}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(!this.nodes.has(C)&&!this.groups.has(C))throw new Error(`The right-hand id [${C}] does not yet exist. Please create the service/group before declaring an edge to it.`);const f=this.nodes.get(M).in,e=this.nodes.get(C).in;if(n&&f&&e&&f==e)throw new Error(`The left-hand id [${M}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(r&&f&&e&&f==e)throw new Error(`The right-hand id [${C}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);const g={lhsId:M,lhsDir:x,lhsInto:v,lhsGroup:n,rhsId:C,rhsDir:N,rhsInto:l,rhsGroup:r,title:i};this.edges.push(g);const t=this.nodes.get(M),s=this.nodes.get(C);t&&s&&(t.edges.push(this.edges[this.edges.length-1]),s.edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}addLayoutHint(M){if(M.members.length<2)throw new Error(`An align directive requires at least two members; got ${M.members.length}`);const C=new Set;M.members.forEach(x=>{if(this.registeredIds.get(x)!=="node")throw new Error(`align ${M.direction} references [${x}], which is not a service or junction`);if(C.has(x))throw new Error(`align ${M.direction} lists [${x}] more than once`);C.add(x)}),this.layoutHints.push(M)}getLayoutHints(){return this.layoutHints}getDataStructures(){var M,C;if(this.dataStructures===void 0){const x=new Map,N=new Map;for(const[i,f]of this.nodes.entries()){const e=new Map;for(const g of f.edges){const t=(M=this.getNode(g.lhsId))==null?void 0:M.in,s=(C=this.getNode(g.rhsId))==null?void 0:C.in;if(t&&s&&t!==s){const o=Dr(g.lhsDir,g.rhsDir);o!=="bend"&&x.set(Pe(t,s),o)}if(g.lhsId===i){const o=ye(g.lhsDir,g.rhsDir);o&&e.set(o,g.rhsId)}else{const o=ye(g.rhsDir,g.lhsDir);o&&e.set(o,g.lhsId)}}N.set(i,e)}const v=new Set,l=new Set(N.keys()),n=ct(i=>{const f=new Map([[i,[0,0]]]),e=[i];for(;e.length>0;){const g=e.shift();if(g){v.add(g),l.delete(g);const t=N.get(g);if(!t)throw new Error(`BFS error: adjacency list for id ${g} not found. Please report this as a bug.`);const s=f.get(g);if(!s)throw new Error(`BFS error: position for id ${g} not found in spatial map. Please report this as a bug.`);const[o,c]=s;t.forEach((h,T)=>{v.has(h)||(f.set(h,Mr([o,c],T)),e.push(h))})}}return f},"BFS"),r=[];for(;l.size>0;){const i=l.values().next().value;r.push(n(i))}this.dataStructures={adjList:N,spatialMaps:r,groupAlignments:x}}return this.dataStructures}setElementForId(M,C){this.elements.set(M,C)}getElementById(M){return this.elements.get(M)}getConfig(){return ar({...Ir,...nr().architecture})}getConfigField(M){return this.getConfig()[M]}},ct(ae,"ArchitectureDB"),ae),Rr=ct((I,M)=>{var C;qe(I,M),I.groups.map(x=>M.addGroup(x)),I.services.map(x=>M.addService({...x,type:"service"})),I.junctions.map(x=>M.addJunction({...x,type:"junction"})),I.edges.map(x=>M.addEdge(x)),(C=I.alignments)==null||C.map(x=>M.addLayoutHint({direction:x.direction,members:[...x.members]}))},"populateDb"),Ye={parser:{yy:void 0},parse:ct(async I=>{var x;const M=await cr("architecture",I);Fe.debug(M);const C=(x=Ye.parser)==null?void 0:x.yy;if(!(C instanceof Ue))throw new Error("parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");Rr(M,C)},"parse")},Sr=ct(I=>` +import{p as qe}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{_ as ct,C as Qe,Y as Je,l as Fe,b as Ke,a as je,m as _e,n as tr,g as er,s as rr,o as ir,z as ar,x as nr,A as or,c as Ee,ap as Te,a4 as pe,i as sr,p as hr,a5 as lr,aq as fr}from"./mermaid.core-BRmiRRt4.js";import{p as cr}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import{c as be}from"./cytoscape.esm-Bch-eiPH.js";import{g as gr}from"./vendor-utils-_6D5wMFs.js";import{s as ur}from"./vendor-flow-bDma3vSM.js";import"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";var he={exports:{}},le={exports:{}},fe={exports:{}},dr=fe.exports,De;function vr(){return De||(De=1,(function(I,M){(function(x,N){I.exports=N()})(dr,function(){return(function(C){var x={};function N(v){if(x[v])return x[v].exports;var l=x[v]={i:v,l:!1,exports:{}};return C[v].call(l.exports,l,l.exports,N),l.l=!0,l.exports}return N.m=C,N.c=x,N.i=function(v){return v},N.d=function(v,l,n){N.o(v,l)||Object.defineProperty(v,l,{configurable:!1,enumerable:!0,get:n})},N.n=function(v){var l=v&&v.__esModule?function(){return v.default}:function(){return v};return N.d(l,"a",l),l},N.o=function(v,l){return Object.prototype.hasOwnProperty.call(v,l)},N.p="",N(N.s=28)})([(function(C,x,N){function v(){}v.QUALITY=1,v.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,v.DEFAULT_INCREMENTAL=!1,v.DEFAULT_ANIMATION_ON_LAYOUT=!0,v.DEFAULT_ANIMATION_DURING_LAYOUT=!1,v.DEFAULT_ANIMATION_PERIOD=50,v.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,v.DEFAULT_GRAPH_MARGIN=15,v.NODE_DIMENSIONS_INCLUDE_LABELS=!1,v.SIMPLE_NODE_SIZE=40,v.SIMPLE_NODE_HALF_SIZE=v.SIMPLE_NODE_SIZE/2,v.EMPTY_COMPOUND_NODE_SIZE=40,v.MIN_EDGE_LENGTH=1,v.WORLD_BOUNDARY=1e6,v.INITIAL_WORLD_BOUNDARY=v.WORLD_BOUNDARY/1e3,v.WORLD_CENTER_X=1200,v.WORLD_CENTER_Y=900,C.exports=v}),(function(C,x,N){var v=N(2),l=N(8),n=N(9);function r(f,e,g){v.call(this,g),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=g,this.bendpoints=[],this.source=f,this.target=e}r.prototype=Object.create(v.prototype);for(var i in v)r[i]=v[i];r.prototype.getSource=function(){return this.source},r.prototype.getTarget=function(){return this.target},r.prototype.isInterGraph=function(){return this.isInterGraph},r.prototype.getLength=function(){return this.length},r.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},r.prototype.getBendpoints=function(){return this.bendpoints},r.prototype.getLca=function(){return this.lca},r.prototype.getSourceInLca=function(){return this.sourceInLca},r.prototype.getTargetInLca=function(){return this.targetInLca},r.prototype.getOtherEnd=function(f){if(this.source===f)return this.target;if(this.target===f)return this.source;throw"Node is not incident with this edge"},r.prototype.getOtherEndInGraph=function(f,e){for(var g=this.getOtherEnd(f),t=e.getGraphManager().getRoot();;){if(g.getOwner()==e)return g;if(g.getOwner()==t)break;g=g.getOwner().getParent()}return null},r.prototype.updateLength=function(){var f=new Array(4);this.isOverlapingSourceAndTarget=l.getIntersection(this.target.getRect(),this.source.getRect(),f),this.isOverlapingSourceAndTarget||(this.lengthX=f[0]-f[2],this.lengthY=f[1]-f[3],Math.abs(this.lengthX)<1&&(this.lengthX=n.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=n.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},r.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=n.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=n.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},C.exports=r}),(function(C,x,N){function v(l){this.vGraphObject=l}C.exports=v}),(function(C,x,N){var v=N(2),l=N(10),n=N(13),r=N(0),i=N(16),f=N(5);function e(t,s,o,c){o==null&&c==null&&(c=s),v.call(this,c),t.graphManager!=null&&(t=t.graphManager),this.estimatedSize=l.MIN_VALUE,this.inclusionTreeDepth=l.MAX_VALUE,this.vGraphObject=c,this.edges=[],this.graphManager=t,o!=null&&s!=null?this.rect=new n(s.x,s.y,o.width,o.height):this.rect=new n}e.prototype=Object.create(v.prototype);for(var g in v)e[g]=v[g];e.prototype.getEdges=function(){return this.edges},e.prototype.getChild=function(){return this.child},e.prototype.getOwner=function(){return this.owner},e.prototype.getWidth=function(){return this.rect.width},e.prototype.setWidth=function(t){this.rect.width=t},e.prototype.getHeight=function(){return this.rect.height},e.prototype.setHeight=function(t){this.rect.height=t},e.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},e.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},e.prototype.getCenter=function(){return new f(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},e.prototype.getLocation=function(){return new f(this.rect.x,this.rect.y)},e.prototype.getRect=function(){return this.rect},e.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},e.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},e.prototype.setRect=function(t,s){this.rect.x=t.x,this.rect.y=t.y,this.rect.width=s.width,this.rect.height=s.height},e.prototype.setCenter=function(t,s){this.rect.x=t-this.rect.width/2,this.rect.y=s-this.rect.height/2},e.prototype.setLocation=function(t,s){this.rect.x=t,this.rect.y=s},e.prototype.moveBy=function(t,s){this.rect.x+=t,this.rect.y+=s},e.prototype.getEdgeListToNode=function(t){var s=[],o=this;return o.edges.forEach(function(c){if(c.target==t){if(c.source!=o)throw"Incorrect edge source!";s.push(c)}}),s},e.prototype.getEdgesBetween=function(t){var s=[],o=this;return o.edges.forEach(function(c){if(!(c.source==o||c.target==o))throw"Incorrect edge source and/or target";(c.target==t||c.source==t)&&s.push(c)}),s},e.prototype.getNeighborsList=function(){var t=new Set,s=this;return s.edges.forEach(function(o){if(o.source==s)t.add(o.target);else{if(o.target!=s)throw"Incorrect incidency!";t.add(o.source)}}),t},e.prototype.withChildren=function(){var t=new Set,s,o;if(t.add(this),this.child!=null)for(var c=this.child.getNodes(),h=0;hs?(this.rect.x-=(this.labelWidth-s)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal=="right"&&this.setWidth(s+this.labelWidth)),this.labelHeight&&(this.labelPosVertical=="top"?(this.rect.y-=this.labelHeight,this.setHeight(o+this.labelHeight)):this.labelPosVertical=="center"&&this.labelHeight>o?(this.rect.y-=(this.labelHeight-o)/2,this.setHeight(this.labelHeight)):this.labelPosVertical=="bottom"&&this.setHeight(o+this.labelHeight))}}},e.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==l.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},e.prototype.transform=function(t){var s=this.rect.x;s>r.WORLD_BOUNDARY?s=r.WORLD_BOUNDARY:s<-r.WORLD_BOUNDARY&&(s=-r.WORLD_BOUNDARY);var o=this.rect.y;o>r.WORLD_BOUNDARY?o=r.WORLD_BOUNDARY:o<-r.WORLD_BOUNDARY&&(o=-r.WORLD_BOUNDARY);var c=new f(s,o),h=t.inverseTransformPoint(c);this.setLocation(h.x,h.y)},e.prototype.getLeft=function(){return this.rect.x},e.prototype.getRight=function(){return this.rect.x+this.rect.width},e.prototype.getTop=function(){return this.rect.y},e.prototype.getBottom=function(){return this.rect.y+this.rect.height},e.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},C.exports=e}),(function(C,x,N){var v=N(0);function l(){}for(var n in v)l[n]=v[n];l.MAX_ITERATIONS=2500,l.DEFAULT_EDGE_LENGTH=50,l.DEFAULT_SPRING_STRENGTH=.45,l.DEFAULT_REPULSION_STRENGTH=4500,l.DEFAULT_GRAVITY_STRENGTH=.4,l.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,l.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,l.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,l.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,l.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,l.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,l.COOLING_ADAPTATION_FACTOR=.33,l.ADAPTATION_LOWER_NODE_LIMIT=1e3,l.ADAPTATION_UPPER_NODE_LIMIT=5e3,l.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,l.MAX_NODE_DISPLACEMENT=l.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,l.MIN_REPULSION_DIST=l.DEFAULT_EDGE_LENGTH/10,l.CONVERGENCE_CHECK_PERIOD=100,l.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,l.MIN_EDGE_LENGTH=1,l.GRID_CALCULATION_CHECK_PERIOD=10,C.exports=l}),(function(C,x,N){function v(l,n){l==null&&n==null?(this.x=0,this.y=0):(this.x=l,this.y=n)}v.prototype.getX=function(){return this.x},v.prototype.getY=function(){return this.y},v.prototype.setX=function(l){this.x=l},v.prototype.setY=function(l){this.y=l},v.prototype.getDifference=function(l){return new DimensionD(this.x-l.x,this.y-l.y)},v.prototype.getCopy=function(){return new v(this.x,this.y)},v.prototype.translate=function(l){return this.x+=l.width,this.y+=l.height,this},C.exports=v}),(function(C,x,N){var v=N(2),l=N(10),n=N(0),r=N(7),i=N(3),f=N(1),e=N(13),g=N(12),t=N(11);function s(c,h,T){v.call(this,T),this.estimatedSize=l.MIN_VALUE,this.margin=n.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=c,h!=null&&h instanceof r?this.graphManager=h:h!=null&&h instanceof Layout&&(this.graphManager=h.graphManager)}s.prototype=Object.create(v.prototype);for(var o in v)s[o]=v[o];s.prototype.getNodes=function(){return this.nodes},s.prototype.getEdges=function(){return this.edges},s.prototype.getGraphManager=function(){return this.graphManager},s.prototype.getParent=function(){return this.parent},s.prototype.getLeft=function(){return this.left},s.prototype.getRight=function(){return this.right},s.prototype.getTop=function(){return this.top},s.prototype.getBottom=function(){return this.bottom},s.prototype.isConnected=function(){return this.isConnected},s.prototype.add=function(c,h,T){if(h==null&&T==null){var u=c;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(u)>-1)throw"Node already in graph!";return u.owner=this,this.getNodes().push(u),u}else{var d=c;if(!(this.getNodes().indexOf(h)>-1&&this.getNodes().indexOf(T)>-1))throw"Source or target not in graph!";if(!(h.owner==T.owner&&h.owner==this))throw"Both owners must be this graph!";return h.owner!=T.owner?null:(d.source=h,d.target=T,d.isInterGraph=!1,this.getEdges().push(d),h.edges.push(d),T!=h&&T.edges.push(d),d)}},s.prototype.remove=function(c){var h=c;if(c instanceof i){if(h==null)throw"Node is null!";if(!(h.owner!=null&&h.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var T=h.edges.slice(),u,d=T.length,L=0;L-1&&G>-1))throw"Source and/or target doesn't know this edge!";u.source.edges.splice(w,1),u.target!=u.source&&u.target.edges.splice(G,1);var b=u.source.owner.getEdges().indexOf(u);if(b==-1)throw"Not in owner's edge list!";u.source.owner.getEdges().splice(b,1)}},s.prototype.updateLeftTop=function(){for(var c=l.MAX_VALUE,h=l.MAX_VALUE,T,u,d,L=this.getNodes(),b=L.length,w=0;wT&&(c=T),h>u&&(h=u)}return c==l.MAX_VALUE?null:(L[0].getParent().paddingLeft!=null?d=L[0].getParent().paddingLeft:d=this.margin,this.left=h-d,this.top=c-d,new g(this.left,this.top))},s.prototype.updateBounds=function(c){for(var h=l.MAX_VALUE,T=-l.MAX_VALUE,u=l.MAX_VALUE,d=-l.MAX_VALUE,L,b,w,G,V,Y=this.nodes,B=Y.length,A=0;AL&&(h=L),Tw&&(u=w),dL&&(h=L),Tw&&(u=w),d=this.nodes.length){var B=0;T.forEach(function(A){A.owner==c&&B++}),B==this.nodes.length&&(this.isConnected=!0)}},C.exports=s}),(function(C,x,N){var v,l=N(1);function n(r){v=N(6),this.layout=r,this.graphs=[],this.edges=[]}n.prototype.addRoot=function(){var r=this.layout.newGraph(),i=this.layout.newNode(null),f=this.add(r,i);return this.setRootGraph(f),this.rootGraph},n.prototype.add=function(r,i,f,e,g){if(f==null&&e==null&&g==null){if(r==null)throw"Graph is null!";if(i==null)throw"Parent node is null!";if(this.graphs.indexOf(r)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(r),r.parent!=null)throw"Already has a parent!";if(i.child!=null)throw"Already has a child!";return r.parent=i,i.child=r,r}else{g=f,e=i,f=r;var t=e.getOwner(),s=g.getOwner();if(!(t!=null&&t.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(s!=null&&s.getGraphManager()==this))throw"Target not in this graph mgr!";if(t==s)return f.isInterGraph=!1,t.add(f,e,g);if(f.isInterGraph=!0,f.source=e,f.target=g,this.edges.indexOf(f)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(f),!(f.source!=null&&f.target!=null))throw"Edge source and/or target is null!";if(!(f.source.edges.indexOf(f)==-1&&f.target.edges.indexOf(f)==-1))throw"Edge already in source and/or target incidency list!";return f.source.edges.push(f),f.target.edges.push(f),f}},n.prototype.remove=function(r){if(r instanceof v){var i=r;if(i.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(i==this.rootGraph||i.parent!=null&&i.parent.graphManager==this))throw"Invalid parent node!";var f=[];f=f.concat(i.getEdges());for(var e,g=f.length,t=0;t=r.getRight()?i[0]+=Math.min(r.getX()-n.getX(),n.getRight()-r.getRight()):r.getX()<=n.getX()&&r.getRight()>=n.getRight()&&(i[0]+=Math.min(n.getX()-r.getX(),r.getRight()-n.getRight())),n.getY()<=r.getY()&&n.getBottom()>=r.getBottom()?i[1]+=Math.min(r.getY()-n.getY(),n.getBottom()-r.getBottom()):r.getY()<=n.getY()&&r.getBottom()>=n.getBottom()&&(i[1]+=Math.min(n.getY()-r.getY(),r.getBottom()-n.getBottom()));var g=Math.abs((r.getCenterY()-n.getCenterY())/(r.getCenterX()-n.getCenterX()));r.getCenterY()===n.getCenterY()&&r.getCenterX()===n.getCenterX()&&(g=1);var t=g*i[0],s=i[1]/g;i[0]t)return i[0]=f,i[1]=o,i[2]=g,i[3]=Y,!1;if(eg)return i[0]=s,i[1]=e,i[2]=G,i[3]=t,!1;if(fg?(i[0]=h,i[1]=T,a=!0):(i[0]=c,i[1]=o,a=!0):p===y&&(f>g?(i[0]=s,i[1]=o,a=!0):(i[0]=u,i[1]=T,a=!0)),-m===y?g>f?(i[2]=V,i[3]=Y,E=!0):(i[2]=G,i[3]=w,E=!0):m===y&&(g>f?(i[2]=b,i[3]=w,E=!0):(i[2]=B,i[3]=Y,E=!0)),a&&E)return!1;if(f>g?e>t?(S=this.getCardinalDirection(p,y,4),D=this.getCardinalDirection(m,y,2)):(S=this.getCardinalDirection(-p,y,3),D=this.getCardinalDirection(-m,y,1)):e>t?(S=this.getCardinalDirection(-p,y,1),D=this.getCardinalDirection(-m,y,3)):(S=this.getCardinalDirection(p,y,2),D=this.getCardinalDirection(m,y,4)),!a)switch(S){case 1:W=o,F=f+-L/y,i[0]=F,i[1]=W;break;case 2:F=u,W=e+d*y,i[0]=F,i[1]=W;break;case 3:W=T,F=f+L/y,i[0]=F,i[1]=W;break;case 4:F=h,W=e+-d*y,i[0]=F,i[1]=W;break}if(!E)switch(D){case 1:Q=w,R=g+-j/y,i[2]=R,i[3]=Q;break;case 2:R=B,Q=t+A*y,i[2]=R,i[3]=Q;break;case 3:Q=Y,R=g+j/y,i[2]=R,i[3]=Q;break;case 4:R=V,Q=t+-A*y,i[2]=R,i[3]=Q;break}}return!1},l.getCardinalDirection=function(n,r,i){return n>r?i:1+i%4},l.getIntersection=function(n,r,i,f){if(f==null)return this.getIntersection2(n,r,i);var e=n.x,g=n.y,t=r.x,s=r.y,o=i.x,c=i.y,h=f.x,T=f.y,u=void 0,d=void 0,L=void 0,b=void 0,w=void 0,G=void 0,V=void 0,Y=void 0,B=void 0;return L=s-g,w=e-t,V=t*g-e*s,b=T-c,G=o-h,Y=h*c-o*T,B=L*G-b*w,B===0?null:(u=(w*Y-G*V)/B,d=(b*V-L*Y)/B,new v(u,d))},l.angleOfVector=function(n,r,i,f){var e=void 0;return n!==i?(e=Math.atan((f-r)/(i-n)),i=0){var T=(-o+Math.sqrt(o*o-4*s*c))/(2*s),u=(-o-Math.sqrt(o*o-4*s*c))/(2*s),d=null;return T>=0&&T<=1?[T]:u>=0&&u<=1?[u]:d}else return null},l.HALF_PI=.5*Math.PI,l.ONE_AND_HALF_PI=1.5*Math.PI,l.TWO_PI=2*Math.PI,l.THREE_PI=3*Math.PI,C.exports=l}),(function(C,x,N){function v(){}v.sign=function(l){return l>0?1:l<0?-1:0},v.floor=function(l){return l<0?Math.ceil(l):Math.floor(l)},v.ceil=function(l){return l<0?Math.floor(l):Math.ceil(l)},C.exports=v}),(function(C,x,N){function v(){}v.MAX_VALUE=2147483647,v.MIN_VALUE=-2147483648,C.exports=v}),(function(C,x,N){var v=(function(){function e(g,t){for(var s=0;s"u"?"undefined":v(n);return n==null||r!="object"&&r!="function"},C.exports=l}),(function(C,x,N){function v(o){if(Array.isArray(o)){for(var c=0,h=Array(o.length);c0&&c;){for(L.push(w[0]);L.length>0&&c;){var G=L[0];L.splice(0,1),d.add(G);for(var V=G.getEdges(),u=0;u-1&&w.splice(j,1)}d=new Set,b=new Map}}return o},s.prototype.createDummyNodesForBendpoints=function(o){for(var c=[],h=o.source,T=this.graphManager.calcLowestCommonAncestor(o.source,o.target),u=0;u0){for(var T=this.edgeToDummyNodes.get(h),u=0;u=0&&c.splice(Y,1);var B=b.getNeighborsList();B.forEach(function(a){if(h.indexOf(a)<0){var E=T.get(a),p=E-1;p==1&&G.push(a),T.set(a,p)}})}h=h.concat(G),(c.length==1||c.length==2)&&(u=!0,d=c[0])}return d},s.prototype.setGraphManager=function(o){this.graphManager=o},C.exports=s}),(function(C,x,N){function v(){}v.seed=1,v.x=0,v.nextDouble=function(){return v.x=Math.sin(v.seed++)*1e4,v.x-Math.floor(v.x)},C.exports=v}),(function(C,x,N){var v=N(5);function l(n,r){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}l.prototype.getWorldOrgX=function(){return this.lworldOrgX},l.prototype.setWorldOrgX=function(n){this.lworldOrgX=n},l.prototype.getWorldOrgY=function(){return this.lworldOrgY},l.prototype.setWorldOrgY=function(n){this.lworldOrgY=n},l.prototype.getWorldExtX=function(){return this.lworldExtX},l.prototype.setWorldExtX=function(n){this.lworldExtX=n},l.prototype.getWorldExtY=function(){return this.lworldExtY},l.prototype.setWorldExtY=function(n){this.lworldExtY=n},l.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},l.prototype.setDeviceOrgX=function(n){this.ldeviceOrgX=n},l.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},l.prototype.setDeviceOrgY=function(n){this.ldeviceOrgY=n},l.prototype.getDeviceExtX=function(){return this.ldeviceExtX},l.prototype.setDeviceExtX=function(n){this.ldeviceExtX=n},l.prototype.getDeviceExtY=function(){return this.ldeviceExtY},l.prototype.setDeviceExtY=function(n){this.ldeviceExtY=n},l.prototype.transformX=function(n){var r=0,i=this.lworldExtX;return i!=0&&(r=this.ldeviceOrgX+(n-this.lworldOrgX)*this.ldeviceExtX/i),r},l.prototype.transformY=function(n){var r=0,i=this.lworldExtY;return i!=0&&(r=this.ldeviceOrgY+(n-this.lworldOrgY)*this.ldeviceExtY/i),r},l.prototype.inverseTransformX=function(n){var r=0,i=this.ldeviceExtX;return i!=0&&(r=this.lworldOrgX+(n-this.ldeviceOrgX)*this.lworldExtX/i),r},l.prototype.inverseTransformY=function(n){var r=0,i=this.ldeviceExtY;return i!=0&&(r=this.lworldOrgY+(n-this.ldeviceOrgY)*this.lworldExtY/i),r},l.prototype.inverseTransformPoint=function(n){var r=new v(this.inverseTransformX(n.x),this.inverseTransformY(n.y));return r},C.exports=l}),(function(C,x,N){function v(t){if(Array.isArray(t)){for(var s=0,o=Array(t.length);sn.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*n.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(t-n.ADAPTATION_LOWER_NODE_LIMIT)/(n.ADAPTATION_UPPER_NODE_LIMIT-n.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-n.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=n.MAX_NODE_DISPLACEMENT_INCREMENTAL):(t>n.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(n.COOLING_ADAPTATION_FACTOR,1-(t-n.ADAPTATION_LOWER_NODE_LIMIT)/(n.ADAPTATION_UPPER_NODE_LIMIT-n.ADAPTATION_LOWER_NODE_LIMIT)*(1-n.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=n.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*n.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},e.prototype.calcSpringForces=function(){for(var t=this.getAllEdges(),s,o=0;o0&&arguments[0]!==void 0?arguments[0]:!0,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,o,c,h,T,u=this.getAllNodes(),d;if(this.useFRGridVariant)for(this.totalIterations%n.GRID_CALCULATION_CHECK_PERIOD==1&&t&&this.updateGrid(),d=new Set,o=0;oL||d>L)&&(t.gravitationForceX=-this.gravityConstant*h,t.gravitationForceY=-this.gravityConstant*T)):(L=s.getEstimatedSize()*this.compoundGravityRangeFactor,(u>L||d>L)&&(t.gravitationForceX=-this.gravityConstant*h*this.compoundGravityConstant,t.gravitationForceY=-this.gravityConstant*T*this.compoundGravityConstant))},e.prototype.isConverged=function(){var t,s=!1;return this.totalIterations>this.maxIterations/3&&(s=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),t=this.totalDisplacement=u.length||L>=u[0].length)){for(var b=0;be}}]),i})();C.exports=r}),(function(C,x,N){function v(){}v.svd=function(l){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=l.length,this.n=l[0].length;var n=Math.min(this.m,this.n);this.s=(function(Tt){for(var wt=[];Tt-- >0;)wt.push(0);return wt})(Math.min(this.m+1,this.n)),this.U=(function(Tt){var wt=function $t(bt){if(bt.length==0)return 0;for(var zt=[],St=0;St0;)wt.push(0);return wt})(this.n),i=(function(Tt){for(var wt=[];Tt-- >0;)wt.push(0);return wt})(this.m),f=!0,e=Math.min(this.m-1,this.n),g=Math.max(0,Math.min(this.n-2,this.m)),t=0;t=0;m--)if(this.s[m]!==0){for(var y=m+1;y=0;z--){if((function(Tt,wt){return Tt&&wt})(z0;){var J=void 0,It=void 0;for(J=a-2;J>=-1&&J!==-1;J--)if(Math.abs(r[J])<=ht+tt*(Math.abs(this.s[J])+Math.abs(this.s[J+1]))){r[J]=0;break}if(J===a-2)It=4;else{var Nt=void 0;for(Nt=a-1;Nt>=J&&Nt!==J;Nt--){var vt=(Nt!==a?Math.abs(r[Nt]):0)+(Nt!==J+1?Math.abs(r[Nt-1]):0);if(Math.abs(this.s[Nt])<=ht+tt*vt){this.s[Nt]=0;break}}Nt===J?It=3:Nt===a-1?It=1:(It=2,J=Nt)}switch(J++,It){case 1:{var it=r[a-2];r[a-2]=0;for(var ut=a-2;ut>=J;ut--){var Et=v.hypot(this.s[ut],it),Ct=this.s[ut]/Et,Dt=it/Et;this.s[ut]=Et,ut!==J&&(it=-Dt*r[ut-1],r[ut-1]=Ct*r[ut-1]);for(var mt=0;mt=this.s[J+1]);){var Lt=this.s[J];if(this.s[J]=this.s[J+1],this.s[J+1]=Lt,JMath.abs(n)?(r=n/l,r=Math.abs(l)*Math.sqrt(1+r*r)):n!=0?(r=l/n,r=Math.abs(n)*Math.sqrt(1+r*r)):r=0,r},C.exports=v}),(function(C,x,N){var v=(function(){function r(i,f){for(var e=0;e2&&arguments[2]!==void 0?arguments[2]:1,g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,t=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;l(this,r),this.sequence1=i,this.sequence2=f,this.match_score=e,this.mismatch_penalty=g,this.gap_penalty=t,this.iMax=i.length+1,this.jMax=f.length+1,this.grid=new Array(this.iMax);for(var s=0;s=0;i--){var f=this.listeners[i];f.event===n&&f.callback===r&&this.listeners.splice(i,1)}},l.emit=function(n,r){for(var i=0;i{var x={45:((n,r,i)=>{var f={};f.layoutBase=i(551),f.CoSEConstants=i(806),f.CoSEEdge=i(767),f.CoSEGraph=i(880),f.CoSEGraphManager=i(578),f.CoSELayout=i(765),f.CoSENode=i(991),f.ConstraintHandler=i(902),n.exports=f}),806:((n,r,i)=>{var f=i(551).FDLayoutConstants;function e(){}for(var g in f)e[g]=f[g];e.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,e.DEFAULT_RADIAL_SEPARATION=f.DEFAULT_EDGE_LENGTH,e.DEFAULT_COMPONENT_SEPERATION=60,e.TILE=!0,e.TILING_PADDING_VERTICAL=10,e.TILING_PADDING_HORIZONTAL=10,e.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,e.ENFORCE_CONSTRAINTS=!0,e.APPLY_LAYOUT=!0,e.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,e.TREE_REDUCTION_ON_INCREMENTAL=!0,e.PURE_INCREMENTAL=e.DEFAULT_INCREMENTAL,n.exports=e}),767:((n,r,i)=>{var f=i(551).FDLayoutEdge;function e(t,s,o){f.call(this,t,s,o)}e.prototype=Object.create(f.prototype);for(var g in f)e[g]=f[g];n.exports=e}),880:((n,r,i)=>{var f=i(551).LGraph;function e(t,s,o){f.call(this,t,s,o)}e.prototype=Object.create(f.prototype);for(var g in f)e[g]=f[g];n.exports=e}),578:((n,r,i)=>{var f=i(551).LGraphManager;function e(t){f.call(this,t)}e.prototype=Object.create(f.prototype);for(var g in f)e[g]=f[g];n.exports=e}),765:((n,r,i)=>{var f=i(551).FDLayout,e=i(578),g=i(880),t=i(991),s=i(767),o=i(806),c=i(902),h=i(551).FDLayoutConstants,T=i(551).LayoutConstants,u=i(551).Point,d=i(551).PointD,L=i(551).DimensionD,b=i(551).Layout,w=i(551).Integer,G=i(551).IGeometry,V=i(551).LGraph,Y=i(551).Transform,B=i(551).LinkedList;function A(){f.call(this),this.toBeTiled={},this.constraints={}}A.prototype=Object.create(f.prototype);for(var j in f)A[j]=f[j];A.prototype.newGraphManager=function(){var a=new e(this);return this.graphManager=a,a},A.prototype.newGraph=function(a){return new g(null,this.graphManager,a)},A.prototype.newNode=function(a){return new t(this.graphManager,a)},A.prototype.newEdge=function(a){return new s(null,null,a)},A.prototype.initParameters=function(){f.prototype.initParameters.call(this,arguments),this.isSubLayout||(o.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=o.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=o.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=h.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=h.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=h.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=h.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},A.prototype.initSpringEmbedder=function(){f.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/h.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},A.prototype.layout=function(){var a=T.DEFAULT_CREATE_BENDS_AS_NEEDED;return a&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},A.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental){if(o.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var E=new Set(this.getAllNodes()),p=this.nodesWithGravity.filter(function(S){return E.has(S)});this.graphManager.setAllNodesToApplyGravitation(p)}}else{var a=this.getFlatForest();if(a.length>0)this.positionNodesRadially(a);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var E=new Set(this.getAllNodes()),p=this.nodesWithGravity.filter(function(m){return E.has(m)});this.graphManager.setAllNodesToApplyGravitation(p),this.positionNodesRandomly()}}return Object.keys(this.constraints).length>0&&(c.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),o.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},A.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%h.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var a=new Set(this.getAllNodes()),E=this.nodesWithGravity.filter(function(y){return a.has(y)});this.graphManager.setAllNodesToApplyGravitation(E),this.graphManager.updateBounds(),this.updateGrid(),o.PURE_INCREMENTAL?this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),o.PURE_INCREMENTAL?this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=h.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var p=!this.isTreeGrowing&&!this.isGrowthFinished,m=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(p,m),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},A.prototype.getPositionsData=function(){for(var a=this.graphManager.getAllNodes(),E={},p=0;p0&&this.updateDisplacements();for(var p=0;p0&&(m.fixedNodeWeight=S)}}if(this.constraints.relativePlacementConstraint){var D=new Map,F=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(O){a.fixedNodesOnHorizontal.add(O),a.fixedNodesOnVertical.add(O)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var W=this.constraints.alignmentConstraint.vertical,p=0;p=2*O.length/3;tt--)H=Math.floor(Math.random()*(tt+1)),Z=O[tt],O[tt]=O[H],O[H]=Z;return O},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(O){if(O.left){var H=D.has(O.left)?D.get(O.left):O.left,Z=D.has(O.right)?D.get(O.right):O.right;a.nodesInRelativeHorizontal.includes(H)||(a.nodesInRelativeHorizontal.push(H),a.nodeToRelativeConstraintMapHorizontal.set(H,[]),a.dummyToNodeForVerticalAlignment.has(H)?a.nodeToTempPositionMapHorizontal.set(H,a.idToNodeMap.get(a.dummyToNodeForVerticalAlignment.get(H)[0]).getCenterX()):a.nodeToTempPositionMapHorizontal.set(H,a.idToNodeMap.get(H).getCenterX())),a.nodesInRelativeHorizontal.includes(Z)||(a.nodesInRelativeHorizontal.push(Z),a.nodeToRelativeConstraintMapHorizontal.set(Z,[]),a.dummyToNodeForVerticalAlignment.has(Z)?a.nodeToTempPositionMapHorizontal.set(Z,a.idToNodeMap.get(a.dummyToNodeForVerticalAlignment.get(Z)[0]).getCenterX()):a.nodeToTempPositionMapHorizontal.set(Z,a.idToNodeMap.get(Z).getCenterX())),a.nodeToRelativeConstraintMapHorizontal.get(H).push({right:Z,gap:O.gap}),a.nodeToRelativeConstraintMapHorizontal.get(Z).push({left:H,gap:O.gap})}else{var tt=F.has(O.top)?F.get(O.top):O.top,ht=F.has(O.bottom)?F.get(O.bottom):O.bottom;a.nodesInRelativeVertical.includes(tt)||(a.nodesInRelativeVertical.push(tt),a.nodeToRelativeConstraintMapVertical.set(tt,[]),a.dummyToNodeForHorizontalAlignment.has(tt)?a.nodeToTempPositionMapVertical.set(tt,a.idToNodeMap.get(a.dummyToNodeForHorizontalAlignment.get(tt)[0]).getCenterY()):a.nodeToTempPositionMapVertical.set(tt,a.idToNodeMap.get(tt).getCenterY())),a.nodesInRelativeVertical.includes(ht)||(a.nodesInRelativeVertical.push(ht),a.nodeToRelativeConstraintMapVertical.set(ht,[]),a.dummyToNodeForHorizontalAlignment.has(ht)?a.nodeToTempPositionMapVertical.set(ht,a.idToNodeMap.get(a.dummyToNodeForHorizontalAlignment.get(ht)[0]).getCenterY()):a.nodeToTempPositionMapVertical.set(ht,a.idToNodeMap.get(ht).getCenterY())),a.nodeToRelativeConstraintMapVertical.get(tt).push({bottom:ht,gap:O.gap}),a.nodeToRelativeConstraintMapVertical.get(ht).push({top:tt,gap:O.gap})}});else{var Q=new Map,z=new Map;this.constraints.relativePlacementConstraint.forEach(function(O){if(O.left){var H=D.has(O.left)?D.get(O.left):O.left,Z=D.has(O.right)?D.get(O.right):O.right;Q.has(H)?Q.get(H).push(Z):Q.set(H,[Z]),Q.has(Z)?Q.get(Z).push(H):Q.set(Z,[H])}else{var tt=F.has(O.top)?F.get(O.top):O.top,ht=F.has(O.bottom)?F.get(O.bottom):O.bottom;z.has(tt)?z.get(tt).push(ht):z.set(tt,[ht]),z.has(ht)?z.get(ht).push(tt):z.set(ht,[tt])}});var X=function(H,Z){var tt=[],ht=[],J=new B,It=new Set,Nt=0;return H.forEach(function(vt,it){if(!It.has(it)){tt[Nt]=[],ht[Nt]=!1;var ut=it;for(J.push(ut),It.add(ut),tt[Nt].push(ut);J.length!=0;){ut=J.shift(),Z.has(ut)&&(ht[Nt]=!0);var Et=H.get(ut);Et.forEach(function(Ct){It.has(Ct)||(J.push(Ct),It.add(Ct),tt[Nt].push(Ct))})}Nt++}}),{components:tt,isFixed:ht}},rt=X(Q,a.fixedNodesOnHorizontal);this.componentsOnHorizontal=rt.components,this.fixedComponentsOnHorizontal=rt.isFixed;var $=X(z,a.fixedNodesOnVertical);this.componentsOnVertical=$.components,this.fixedComponentsOnVertical=$.isFixed}}},A.prototype.updateDisplacements=function(){var a=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function($){var O=a.idToNodeMap.get($.nodeId);O.displacementX=0,O.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var E=this.constraints.alignmentConstraint.vertical,p=0;p1){var F;for(F=0;Fm&&(m=Math.floor(D.y)),S=Math.floor(D.x+o.DEFAULT_COMPONENT_SEPERATION)}this.transform(new d(T.WORLD_CENTER_X-D.x/2,T.WORLD_CENTER_Y-D.y/2))},A.radialLayout=function(a,E,p){var m=Math.max(this.maxDiagonalInTree(a),o.DEFAULT_RADIAL_SEPARATION);A.branchRadialLayout(E,null,0,359,0,m);var y=V.calculateBounds(a),S=new Y;S.setDeviceOrgX(y.getMinX()),S.setDeviceOrgY(y.getMinY()),S.setWorldOrgX(p.x),S.setWorldOrgY(p.y);for(var D=0;D1;){var Z=H[0];H.splice(0,1);var tt=z.indexOf(Z);tt>=0&&z.splice(tt,1),$--,X--}E!=null?O=(z.indexOf(H[0])+1)%$:O=0;for(var ht=Math.abs(m-p)/X,J=O;rt!=X;J=++J%$){var It=z[J].getOtherEnd(a);if(It!=E){var Nt=(p+rt*ht)%360,vt=(Nt+ht)%360;A.branchRadialLayout(It,a,Nt,vt,y+S,S),rt++}}},A.maxDiagonalInTree=function(a){for(var E=w.MIN_VALUE,p=0;pE&&(E=y)}return E},A.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},A.prototype.groupZeroDegreeMembers=function(){var a=this,E={};this.memberGroups={},this.idToDummyNode={};for(var p=[],m=this.graphManager.getAllNodes(),y=0;y"u"&&(E[F]=[]),E[F]=E[F].concat(S)}Object.keys(E).forEach(function(W){if(E[W].length>1){var R="DummyCompound_"+W;a.memberGroups[R]=E[W];var Q=E[W][0].getParent(),z=new t(a.graphManager);z.id=R,z.paddingLeft=Q.paddingLeft||0,z.paddingRight=Q.paddingRight||0,z.paddingBottom=Q.paddingBottom||0,z.paddingTop=Q.paddingTop||0,a.idToDummyNode[R]=z;var X=a.getGraphManager().add(a.newGraph(),z),rt=Q.getChild();rt.add(z);for(var $=0;$y?(m.rect.x-=(m.labelWidth-y)/2,m.setWidth(m.labelWidth),m.labelMarginLeft=(m.labelWidth-y)/2):m.labelPosHorizontal=="right"&&m.setWidth(y+m.labelWidth)),m.labelHeight&&(m.labelPosVertical=="top"?(m.rect.y-=m.labelHeight,m.setHeight(S+m.labelHeight),m.labelMarginTop=m.labelHeight):m.labelPosVertical=="center"&&m.labelHeight>S?(m.rect.y-=(m.labelHeight-S)/2,m.setHeight(m.labelHeight),m.labelMarginTop=(m.labelHeight-S)/2):m.labelPosVertical=="bottom"&&m.setHeight(S+m.labelHeight))}})},A.prototype.repopulateCompounds=function(){for(var a=this.compoundOrder.length-1;a>=0;a--){var E=this.compoundOrder[a],p=E.id,m=E.paddingLeft,y=E.paddingTop,S=E.labelMarginLeft,D=E.labelMarginTop;this.adjustLocations(this.tiledMemberPack[p],E.rect.x,E.rect.y,m,y,S,D)}},A.prototype.repopulateZeroDegreeMembers=function(){var a=this,E=this.tiledZeroDegreePack;Object.keys(E).forEach(function(p){var m=a.idToDummyNode[p],y=m.paddingLeft,S=m.paddingTop,D=m.labelMarginLeft,F=m.labelMarginTop;a.adjustLocations(E[p],m.rect.x,m.rect.y,y,S,D,F)})},A.prototype.getToBeTiled=function(a){var E=a.id;if(this.toBeTiled[E]!=null)return this.toBeTiled[E];var p=a.getChild();if(p==null)return this.toBeTiled[E]=!1,!1;for(var m=p.getNodes(),y=0;y0)return this.toBeTiled[E]=!1,!1;if(S.getChild()==null){this.toBeTiled[S.id]=!1;continue}if(!this.getToBeTiled(S))return this.toBeTiled[E]=!1,!1}return this.toBeTiled[E]=!0,!0},A.prototype.getNodeDegree=function(a){a.id;for(var E=a.getEdges(),p=0,m=0;mQ&&(Q=X.rect.height)}p+=Q+a.verticalPadding}},A.prototype.tileCompoundMembers=function(a,E){var p=this;this.tiledMemberPack=[],Object.keys(a).forEach(function(m){var y=E[m];if(p.tiledMemberPack[m]=p.tileNodes(a[m],y.paddingLeft+y.paddingRight),y.rect.width=p.tiledMemberPack[m].width,y.rect.height=p.tiledMemberPack[m].height,y.setCenter(p.tiledMemberPack[m].centerX,p.tiledMemberPack[m].centerY),y.labelMarginLeft=0,y.labelMarginTop=0,o.NODE_DIMENSIONS_INCLUDE_LABELS){var S=y.rect.width,D=y.rect.height;y.labelWidth&&(y.labelPosHorizontal=="left"?(y.rect.x-=y.labelWidth,y.setWidth(S+y.labelWidth),y.labelMarginLeft=y.labelWidth):y.labelPosHorizontal=="center"&&y.labelWidth>S?(y.rect.x-=(y.labelWidth-S)/2,y.setWidth(y.labelWidth),y.labelMarginLeft=(y.labelWidth-S)/2):y.labelPosHorizontal=="right"&&y.setWidth(S+y.labelWidth)),y.labelHeight&&(y.labelPosVertical=="top"?(y.rect.y-=y.labelHeight,y.setHeight(D+y.labelHeight),y.labelMarginTop=y.labelHeight):y.labelPosVertical=="center"&&y.labelHeight>D?(y.rect.y-=(y.labelHeight-D)/2,y.setHeight(y.labelHeight),y.labelMarginTop=(y.labelHeight-D)/2):y.labelPosVertical=="bottom"&&y.setHeight(D+y.labelHeight))}})},A.prototype.tileNodes=function(a,E){var p=this.tileNodesByFavoringDim(a,E,!0),m=this.tileNodesByFavoringDim(a,E,!1),y=this.getOrgRatio(p),S=this.getOrgRatio(m),D;return SF&&(F=$.getWidth())});var W=S/y,R=D/y,Q=Math.pow(p-m,2)+4*(W+m)*(R+p)*y,z=(m-p+Math.sqrt(Q))/(2*(W+m)),X;E?(X=Math.ceil(z),X==z&&X++):X=Math.floor(z);var rt=X*(W+m)-m;return F>rt&&(rt=F),rt+=m*2,rt},A.prototype.tileNodesByFavoringDim=function(a,E,p){var m=o.TILING_PADDING_VERTICAL,y=o.TILING_PADDING_HORIZONTAL,S=o.TILING_COMPARE_BY,D={rows:[],rowWidth:[],rowHeight:[],width:0,height:E,verticalPadding:m,horizontalPadding:y,centerX:0,centerY:0};S&&(D.idealRowWidth=this.calcIdealRowWidth(a,p));var F=function(O){return O.rect.width*O.rect.height},W=function(O,H){return F(H)-F(O)};a.sort(function($,O){var H=W;return D.idealRowWidth?(H=S,H($.id,O.id)):H($,O)});for(var R=0,Q=0,z=0;z0&&(D+=a.horizontalPadding),a.rowWidth[p]=D,a.width0&&(F+=a.verticalPadding);var W=0;F>a.rowHeight[p]&&(W=a.rowHeight[p],a.rowHeight[p]=F,W=a.rowHeight[p]-W),a.height+=W,a.rows[p].push(E)},A.prototype.getShortestRowIndex=function(a){for(var E=-1,p=Number.MAX_VALUE,m=0;mp&&(E=m,p=a.rowWidth[m]);return E},A.prototype.canAddHorizontal=function(a,E,p){if(a.idealRowWidth){var m=a.rows.length-1,y=a.rowWidth[m];return y+E+a.horizontalPadding<=a.idealRowWidth}var S=this.getShortestRowIndex(a);if(S<0)return!0;var D=a.rowWidth[S];if(D+a.horizontalPadding+E<=a.width)return!0;var F=0;a.rowHeight[S]0&&(F=p+a.verticalPadding-a.rowHeight[S]);var W;a.width-D>=E+a.horizontalPadding?W=(a.height+F)/(D+E+a.horizontalPadding):W=(a.height+F)/a.width,F=p+a.verticalPadding;var R;return a.widthS&&E!=p){m.splice(-1,1),a.rows[p].push(y),a.rowWidth[E]=a.rowWidth[E]-S,a.rowWidth[p]=a.rowWidth[p]+S,a.width=a.rowWidth[instance.getLongestRowIndex(a)];for(var D=Number.MIN_VALUE,F=0;FD&&(D=m[F].height);E>0&&(D+=a.verticalPadding);var W=a.rowHeight[E]+a.rowHeight[p];a.rowHeight[E]=D,a.rowHeight[p]0)for(var rt=y;rt<=S;rt++)X[0]+=this.grid[rt][D-1].length+this.grid[rt][D].length-1;if(S0)for(var rt=D;rt<=F;rt++)X[3]+=this.grid[y-1][rt].length+this.grid[y][rt].length-1;for(var $=w.MAX_VALUE,O,H,Z=0;Z{var f=i(551).FDLayoutNode,e=i(551).IMath;function g(s,o,c,h){f.call(this,s,o,c,h)}g.prototype=Object.create(f.prototype);for(var t in f)g[t]=f[t];g.prototype.calculateDisplacement=function(){var s=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=s.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=s.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=s.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=s.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>s.coolingFactor*s.maxNodeDisplacement&&(this.displacementX=s.coolingFactor*s.maxNodeDisplacement*e.sign(this.displacementX)),Math.abs(this.displacementY)>s.coolingFactor*s.maxNodeDisplacement&&(this.displacementY=s.coolingFactor*s.maxNodeDisplacement*e.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},g.prototype.propogateDisplacementToChildren=function(s,o){for(var c=this.getChild().getNodes(),h,T=0;T{function f(c){if(Array.isArray(c)){for(var h=0,T=Array(c.length);h0){var Lt=0;ot.forEach(function(st){k=="horizontal"?(et.set(st,u.has(st)?d[u.get(st)]:q.get(st)),Lt+=et.get(st)):(et.set(st,u.has(st)?L[u.get(st)]:q.get(st)),Lt+=et.get(st))}),Lt=Lt/ot.length,lt.forEach(function(st){K.has(st)||et.set(st,Lt)})}else{var ft=0;lt.forEach(function(st){k=="horizontal"?ft+=u.has(st)?d[u.get(st)]:q.get(st):ft+=u.has(st)?L[u.get(st)]:q.get(st)}),ft=ft/lt.length,lt.forEach(function(st){et.set(st,ft)})}});for(var Mt=function(){var ot=dt.shift(),Lt=U.get(ot);Lt.forEach(function(ft){if(et.get(ft.id)st&&(st=Zt),KtXt&&(Xt=Kt)}}catch(ee){wt=!0,$t=ee}finally{try{!Tt&&bt.return&&bt.return()}finally{if(wt)throw $t}}var ce=(Lt+st)/2-(ft+Xt)/2,Qt=!0,jt=!1,_t=void 0;try{for(var Jt=lt[Symbol.iterator](),oe;!(Qt=(oe=Jt.next()).done);Qt=!0){var te=oe.value;et.set(te,et.get(te)+ce)}}catch(ee){jt=!0,_t=ee}finally{try{!Qt&&Jt.return&&Jt.return()}finally{if(jt)throw _t}}})}return et},j=function(U){var k=0,K=0,q=0,at=0;if(U.forEach(function(_){_.left?d[u.get(_.left)]-d[u.get(_.right)]>=0?k++:K++:L[u.get(_.top)]-L[u.get(_.bottom)]>=0?q++:at++}),k>K&&q>at)for(var gt=0;gtK)for(var nt=0;ntat)for(var et=0;et1)h.fixedNodeConstraint.forEach(function(P,U){m[U]=[P.position.x,P.position.y],y[U]=[d[u.get(P.nodeId)],L[u.get(P.nodeId)]]}),S=!0;else if(h.alignmentConstraint)(function(){var P=0;if(h.alignmentConstraint.vertical){for(var U=h.alignmentConstraint.vertical,k=function(et){var _=new Set;U[et].forEach(function(pt){_.add(pt)});var dt=new Set([].concat(f(_)).filter(function(pt){return F.has(pt)})),Mt=void 0;dt.size>0?Mt=d[u.get(dt.values().next().value)]:Mt=B(_).x,U[et].forEach(function(pt){m[P]=[Mt,L[u.get(pt)]],y[P]=[d[u.get(pt)],L[u.get(pt)]],P++})},K=0;K0?Mt=d[u.get(dt.values().next().value)]:Mt=B(_).y,q[et].forEach(function(pt){m[P]=[d[u.get(pt)],Mt],y[P]=[d[u.get(pt)],L[u.get(pt)]],P++})},gt=0;gtz&&(z=Q[rt].length,X=rt);if(z0){var mt={x:0,y:0};h.fixedNodeConstraint.forEach(function(P,U){var k={x:d[u.get(P.nodeId)],y:L[u.get(P.nodeId)]},K=P.position,q=Y(K,k);mt.x+=q.x,mt.y+=q.y}),mt.x/=h.fixedNodeConstraint.length,mt.y/=h.fixedNodeConstraint.length,d.forEach(function(P,U){d[U]+=mt.x}),L.forEach(function(P,U){L[U]+=mt.y}),h.fixedNodeConstraint.forEach(function(P){d[u.get(P.nodeId)]=P.position.x,L[u.get(P.nodeId)]=P.position.y})}if(h.alignmentConstraint){if(h.alignmentConstraint.vertical)for(var Ot=h.alignmentConstraint.vertical,Rt=function(U){var k=new Set;Ot[U].forEach(function(at){k.add(at)});var K=new Set([].concat(f(k)).filter(function(at){return F.has(at)})),q=void 0;K.size>0?q=d[u.get(K.values().next().value)]:q=B(k).x,k.forEach(function(at){F.has(at)||(d[u.get(at)]=q)})},Ht=0;Ht0?q=L[u.get(K.values().next().value)]:q=B(k).y,k.forEach(function(at){F.has(at)||(L[u.get(at)]=q)})},Ft=0;Ft{n.exports=C})},N={};function v(n){var r=N[n];if(r!==void 0)return r.exports;var i=N[n]={exports:{}};return x[n](i,i.exports,v),i.exports}var l=v(45);return l})()})})(le)),le.exports}var mr=he.exports,xe;function Er(){return xe||(xe=1,(function(I,M){(function(x,N){I.exports=N(yr())})(mr,function(C){return(()=>{var x={658:(n=>{n.exports=Object.assign!=null?Object.assign.bind(Object):function(r){for(var i=arguments.length,f=Array(i>1?i-1:0),e=1;e{var f=(function(){function t(s,o){var c=[],h=!0,T=!1,u=void 0;try{for(var d=s[Symbol.iterator](),L;!(h=(L=d.next()).done)&&(c.push(L.value),!(o&&c.length===o));h=!0);}catch(b){T=!0,u=b}finally{try{!h&&d.return&&d.return()}finally{if(T)throw u}}return c}return function(s,o){if(Array.isArray(s))return s;if(Symbol.iterator in Object(s))return t(s,o);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),e=i(140).layoutBase.LinkedList,g={};g.getTopMostNodes=function(t){for(var s={},o=0;o0&&S.merge(R)});for(var D=0;D1){L=u[0],b=L.connectedEdges().length,u.forEach(function(y){y.connectedEdges().length0&&c.set("dummy"+(c.size+1),V),Y},g.relocateComponent=function(t,s,o){if(!o.fixedNodeConstraint){var c=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY,T=Number.POSITIVE_INFINITY,u=Number.NEGATIVE_INFINITY;if(o.quality=="draft"){var d=!0,L=!1,b=void 0;try{for(var w=s.nodeIndexes[Symbol.iterator](),G;!(d=(G=w.next()).done);d=!0){var V=G.value,Y=f(V,2),B=Y[0],A=Y[1],j=o.cy.getElementById(B);if(j){var a=j.boundingBox(),E=s.xCoords[A]-a.w/2,p=s.xCoords[A]+a.w/2,m=s.yCoords[A]-a.h/2,y=s.yCoords[A]+a.h/2;Eh&&(h=p),mu&&(u=y)}}}catch(R){L=!0,b=R}finally{try{!d&&w.return&&w.return()}finally{if(L)throw b}}var S=t.x-(h+c)/2,D=t.y-(u+T)/2;s.xCoords=s.xCoords.map(function(R){return R+S}),s.yCoords=s.yCoords.map(function(R){return R+D})}else{Object.keys(s).forEach(function(R){var Q=s[R],z=Q.getRect().x,X=Q.getRect().x+Q.getRect().width,rt=Q.getRect().y,$=Q.getRect().y+Q.getRect().height;zh&&(h=X),rtu&&(u=$)});var F=t.x-(h+c)/2,W=t.y-(u+T)/2;Object.keys(s).forEach(function(R){var Q=s[R];Q.setCenter(Q.getCenterX()+F,Q.getCenterY()+W)})}}},g.calcBoundingBox=function(t,s,o,c){for(var h=Number.MAX_SAFE_INTEGER,T=Number.MIN_SAFE_INTEGER,u=Number.MAX_SAFE_INTEGER,d=Number.MIN_SAFE_INTEGER,L=void 0,b=void 0,w=void 0,G=void 0,V=t.descendants().not(":parent"),Y=V.length,B=0;BL&&(h=L),Tw&&(u=w),d{var f=i(548),e=i(140).CoSELayout,g=i(140).CoSENode,t=i(140).layoutBase.PointD,s=i(140).layoutBase.DimensionD,o=i(140).layoutBase.LayoutConstants,c=i(140).layoutBase.FDLayoutConstants,h=i(140).CoSEConstants,T=function(d,L){var b=d.cy,w=d.eles,G=w.nodes(),V=w.edges(),Y=void 0,B=void 0,A=void 0,j={};d.randomize&&(Y=L.nodeIndexes,B=L.xCoords,A=L.yCoords);var a=function(R){return typeof R=="function"},E=function(R,Q){return a(R)?R(Q):R},p=f.calcParentsWithoutChildren(b,w),m=function W(R,Q,z,X){for(var rt=Q.length,$=0;$0){var J=void 0;J=z.getGraphManager().add(z.newGraph(),Z),W(J,H,z,X)}}},y=function(R,Q,z){for(var X=0,rt=0,$=0;$0?h.DEFAULT_EDGE_LENGTH=c.DEFAULT_EDGE_LENGTH=X/rt:a(d.idealEdgeLength)?h.DEFAULT_EDGE_LENGTH=c.DEFAULT_EDGE_LENGTH=50:h.DEFAULT_EDGE_LENGTH=c.DEFAULT_EDGE_LENGTH=d.idealEdgeLength,h.MIN_REPULSION_DIST=c.MIN_REPULSION_DIST=c.DEFAULT_EDGE_LENGTH/10,h.DEFAULT_RADIAL_SEPARATION=c.DEFAULT_EDGE_LENGTH)},S=function(R,Q){Q.fixedNodeConstraint&&(R.constraints.fixedNodeConstraint=Q.fixedNodeConstraint),Q.alignmentConstraint&&(R.constraints.alignmentConstraint=Q.alignmentConstraint),Q.relativePlacementConstraint&&(R.constraints.relativePlacementConstraint=Q.relativePlacementConstraint)};d.nestingFactor!=null&&(h.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=c.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=d.nestingFactor),d.gravity!=null&&(h.DEFAULT_GRAVITY_STRENGTH=c.DEFAULT_GRAVITY_STRENGTH=d.gravity),d.numIter!=null&&(h.MAX_ITERATIONS=c.MAX_ITERATIONS=d.numIter),d.gravityRange!=null&&(h.DEFAULT_GRAVITY_RANGE_FACTOR=c.DEFAULT_GRAVITY_RANGE_FACTOR=d.gravityRange),d.gravityCompound!=null&&(h.DEFAULT_COMPOUND_GRAVITY_STRENGTH=c.DEFAULT_COMPOUND_GRAVITY_STRENGTH=d.gravityCompound),d.gravityRangeCompound!=null&&(h.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=c.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=d.gravityRangeCompound),d.initialEnergyOnIncremental!=null&&(h.DEFAULT_COOLING_FACTOR_INCREMENTAL=c.DEFAULT_COOLING_FACTOR_INCREMENTAL=d.initialEnergyOnIncremental),d.tilingCompareBy!=null&&(h.TILING_COMPARE_BY=d.tilingCompareBy),d.quality=="proof"?o.QUALITY=2:o.QUALITY=0,h.NODE_DIMENSIONS_INCLUDE_LABELS=c.NODE_DIMENSIONS_INCLUDE_LABELS=o.NODE_DIMENSIONS_INCLUDE_LABELS=d.nodeDimensionsIncludeLabels,h.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=o.DEFAULT_INCREMENTAL=!d.randomize,h.ANIMATE=c.ANIMATE=o.ANIMATE=d.animate,h.TILE=d.tile,h.TILING_PADDING_VERTICAL=typeof d.tilingPaddingVertical=="function"?d.tilingPaddingVertical.call():d.tilingPaddingVertical,h.TILING_PADDING_HORIZONTAL=typeof d.tilingPaddingHorizontal=="function"?d.tilingPaddingHorizontal.call():d.tilingPaddingHorizontal,h.DEFAULT_INCREMENTAL=c.DEFAULT_INCREMENTAL=o.DEFAULT_INCREMENTAL=!0,h.PURE_INCREMENTAL=!d.randomize,o.DEFAULT_UNIFORM_LEAF_NODE_SIZES=d.uniformNodeDimensions,d.step=="transformed"&&(h.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,h.ENFORCE_CONSTRAINTS=!1,h.APPLY_LAYOUT=!1),d.step=="enforced"&&(h.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,h.ENFORCE_CONSTRAINTS=!0,h.APPLY_LAYOUT=!1),d.step=="cose"&&(h.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,h.ENFORCE_CONSTRAINTS=!1,h.APPLY_LAYOUT=!0),d.step=="all"&&(d.randomize?h.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:h.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,h.ENFORCE_CONSTRAINTS=!0,h.APPLY_LAYOUT=!0),d.fixedNodeConstraint||d.alignmentConstraint||d.relativePlacementConstraint?h.TREE_REDUCTION_ON_INCREMENTAL=!1:h.TREE_REDUCTION_ON_INCREMENTAL=!0;var D=new e,F=D.newGraphManager();return m(F.addRoot(),f.getTopMostNodes(G),D,d),y(D,F,V),S(D,d),D.runLayout(),j};n.exports={coseLayout:T}}),212:((n,r,i)=>{var f=(function(){function d(L,b){for(var w=0;w0)if(p){var S=t.getTopMostNodes(w.eles.nodes());if(A=t.connectComponents(G,w.eles,S),A.forEach(function(vt){var it=vt.boundingBox();j.push({x:it.x1+it.w/2,y:it.y1+it.h/2})}),w.randomize&&A.forEach(function(vt){w.eles=vt,Y.push(o(w))}),w.quality=="default"||w.quality=="proof"){var D=G.collection();if(w.tile){var F=new Map,W=[],R=[],Q=0,z={nodeIndexes:F,xCoords:W,yCoords:R},X=[];if(A.forEach(function(vt,it){vt.edges().length==0&&(vt.nodes().forEach(function(ut,Et){D.merge(vt.nodes()[Et]),ut.isParent()||(z.nodeIndexes.set(vt.nodes()[Et].id(),Q++),z.xCoords.push(vt.nodes()[0].position().x),z.yCoords.push(vt.nodes()[0].position().y))}),X.push(it))}),D.length>1){var rt=D.boundingBox();j.push({x:rt.x1+rt.w/2,y:rt.y1+rt.h/2}),A.push(D),Y.push(z);for(var $=X.length-1;$>=0;$--)A.splice(X[$],1),Y.splice(X[$],1),j.splice(X[$],1)}}A.forEach(function(vt,it){w.eles=vt,B.push(h(w,Y[it])),t.relocateComponent(j[it],B[it],w)})}else A.forEach(function(vt,it){t.relocateComponent(j[it],Y[it],w)});var O=new Set;if(A.length>1){var H=[],Z=V.filter(function(vt){return vt.css("display")=="none"});A.forEach(function(vt,it){var ut=void 0;if(w.quality=="draft"&&(ut=Y[it].nodeIndexes),vt.nodes().not(Z).length>0){var Et={};Et.edges=[],Et.nodes=[];var Ct=void 0;vt.nodes().not(Z).forEach(function(Dt){if(w.quality=="draft")if(!Dt.isParent())Ct=ut.get(Dt.id()),Et.nodes.push({x:Y[it].xCoords[Ct]-Dt.boundingbox().w/2,y:Y[it].yCoords[Ct]-Dt.boundingbox().h/2,width:Dt.boundingbox().w,height:Dt.boundingbox().h});else{var mt=t.calcBoundingBox(Dt,Y[it].xCoords,Y[it].yCoords,ut);Et.nodes.push({x:mt.topLeftX,y:mt.topLeftY,width:mt.width,height:mt.height})}else B[it][Dt.id()]&&Et.nodes.push({x:B[it][Dt.id()].getLeft(),y:B[it][Dt.id()].getTop(),width:B[it][Dt.id()].getWidth(),height:B[it][Dt.id()].getHeight()})}),vt.edges().forEach(function(Dt){var mt=Dt.source(),Ot=Dt.target();if(mt.css("display")!="none"&&Ot.css("display")!="none")if(w.quality=="draft"){var Rt=ut.get(mt.id()),Ht=ut.get(Ot.id()),Ut=[],Pt=[];if(mt.isParent()){var Ft=t.calcBoundingBox(mt,Y[it].xCoords,Y[it].yCoords,ut);Ut.push(Ft.topLeftX+Ft.width/2),Ut.push(Ft.topLeftY+Ft.height/2)}else Ut.push(Y[it].xCoords[Rt]),Ut.push(Y[it].yCoords[Rt]);if(Ot.isParent()){var Yt=t.calcBoundingBox(Ot,Y[it].xCoords,Y[it].yCoords,ut);Pt.push(Yt.topLeftX+Yt.width/2),Pt.push(Yt.topLeftY+Yt.height/2)}else Pt.push(Y[it].xCoords[Ht]),Pt.push(Y[it].yCoords[Ht]);Et.edges.push({startX:Ut[0],startY:Ut[1],endX:Pt[0],endY:Pt[1]})}else B[it][mt.id()]&&B[it][Ot.id()]&&Et.edges.push({startX:B[it][mt.id()].getCenterX(),startY:B[it][mt.id()].getCenterY(),endX:B[it][Ot.id()].getCenterX(),endY:B[it][Ot.id()].getCenterY()})}),Et.nodes.length>0&&(H.push(Et),O.add(it))}});var tt=E.packComponents(H,w.randomize).shifts;if(w.quality=="draft")Y.forEach(function(vt,it){var ut=vt.xCoords.map(function(Ct){return Ct+tt[it].dx}),Et=vt.yCoords.map(function(Ct){return Ct+tt[it].dy});vt.xCoords=ut,vt.yCoords=Et});else{var ht=0;O.forEach(function(vt){Object.keys(B[vt]).forEach(function(it){var ut=B[vt][it];ut.setCenter(ut.getCenterX()+tt[ht].dx,ut.getCenterY()+tt[ht].dy)}),ht++})}}}else{var m=w.eles.boundingBox();if(j.push({x:m.x1+m.w/2,y:m.y1+m.h/2}),w.randomize){var y=o(w);Y.push(y)}w.quality=="default"||w.quality=="proof"?(B.push(h(w,Y[0])),t.relocateComponent(j[0],B[0],w)):t.relocateComponent(j[0],Y[0],w)}var J=function(it,ut){if(w.quality=="default"||w.quality=="proof"){typeof it=="number"&&(it=ut);var Et=void 0,Ct=void 0,Dt=it.data("id");return B.forEach(function(Ot){Dt in Ot&&(Et={x:Ot[Dt].getRect().getCenterX(),y:Ot[Dt].getRect().getCenterY()},Ct=Ot[Dt])}),w.nodeDimensionsIncludeLabels&&(Ct.labelWidth&&(Ct.labelPosHorizontal=="left"?Et.x+=Ct.labelWidth/2:Ct.labelPosHorizontal=="right"&&(Et.x-=Ct.labelWidth/2)),Ct.labelHeight&&(Ct.labelPosVertical=="top"?Et.y+=Ct.labelHeight/2:Ct.labelPosVertical=="bottom"&&(Et.y-=Ct.labelHeight/2))),Et==null&&(Et={x:it.position("x"),y:it.position("y")}),{x:Et.x,y:Et.y}}else{var mt=void 0;return Y.forEach(function(Ot){var Rt=Ot.nodeIndexes.get(it.id());Rt!=null&&(mt={x:Ot.xCoords[Rt],y:Ot.yCoords[Rt]})}),mt==null&&(mt={x:it.position("x"),y:it.position("y")}),{x:mt.x,y:mt.y}}};if(w.quality=="default"||w.quality=="proof"||w.randomize){var It=t.calcParentsWithoutChildren(G,V),Nt=V.filter(function(vt){return vt.css("display")=="none"});w.eles=V.not(Nt),V.nodes().not(":parent").not(Nt).layoutPositions(b,w,J),It.length>0&&It.forEach(function(vt){vt.position(J(vt))})}else console.log("If randomize option is set to false, then quality option must be 'default' or 'proof'.")}}]),d})();n.exports=u}),657:((n,r,i)=>{var f=i(548),e=i(140).layoutBase.Matrix,g=i(140).layoutBase.SVD,t=function(o){var c=o.cy,h=o.eles,T=h.nodes(),u=h.nodes(":parent"),d=new Map,L=new Map,b=new Map,w=[],G=[],V=[],Y=[],B=[],A=[],j=[],a=[],E=void 0,p=1e8,m=1e-9,y=o.piTol,S=o.samplingType,D=o.nodeSeparation,F=void 0,W=function(){for(var U=0,k=0,K=!1;k=at;){nt=q[at++];for(var xt=w[nt],lt=0;ltdt&&(dt=B[Lt],Mt=Lt)}return Mt},Q=function(U){var k=void 0;if(U){k=Math.floor(Math.random()*E);for(var q=0;q=1)break;_=et}for(var pt=0;pt=1)break;_=et}for(var lt=0;lt0&&(k.isParent()?w[U].push(b.get(k.id())):w[U].push(k.id()))})});var Nt=function(U){var k=L.get(U),K=void 0;d.get(U).forEach(function(q){c.getElementById(q).isParent()?K=b.get(q):K=q,w[k].push(K),w[L.get(K)].push(U)})},vt=!0,it=!1,ut=void 0;try{for(var Et=d.keys()[Symbol.iterator](),Ct;!(vt=(Ct=Et.next()).done);vt=!0){var Dt=Ct.value;Nt(Dt)}}catch(P){it=!0,ut=P}finally{try{!vt&&Et.return&&Et.return()}finally{if(it)throw ut}}E=L.size;var mt=void 0;if(E>2){F=E{var f=i(212),e=function(t){t&&t("layout","fcose",f)};typeof cytoscape<"u"&&e(cytoscape),n.exports=e}),140:(n=>{n.exports=C})},N={};function v(n){var r=N[n];if(r!==void 0)return r.exports;var i=N[n]={exports:{}};return x[n](i,i.exports,v),i.exports}var l=v(579);return l})()})})(he)),he.exports}var Tr=Er();const Nr=gr(Tr);var Ie={L:"left",R:"right",T:"top",B:"bottom"},Re={L:ct(I=>`${I},${I/2} 0,${I} 0,0`,"L"),R:ct(I=>`0,${I/2} ${I},0 ${I},${I}`,"R"),T:ct(I=>`0,0 ${I},0 ${I/2},${I}`,"T"),B:ct(I=>`${I/2},0 ${I},${I} 0,${I}`,"B")},se={L:ct((I,M)=>I-M+2,"L"),R:ct((I,M)=>I-2,"R"),T:ct((I,M)=>I-M+2,"T"),B:ct((I,M)=>I-2,"B")},Lr=ct(function(I){return Wt(I)?I==="L"?"R":"L":I==="T"?"B":"T"},"getOppositeArchitectureDirection"),Se=ct(function(I){const M=I;return M==="L"||M==="R"||M==="T"||M==="B"},"isArchitectureDirection"),Wt=ct(function(I){const M=I;return M==="L"||M==="R"},"isArchitectureDirectionX"),qt=ct(function(I){const M=I;return M==="T"||M==="B"},"isArchitectureDirectionY"),Ne=ct(function(I,M){const C=Wt(I)&&qt(M),x=qt(I)&&Wt(M);return C||x},"isArchitectureDirectionXY"),wr=ct(function(I){const M=I[0],C=I[1],x=Wt(M)&&qt(C),N=qt(M)&&Wt(C);return x||N},"isArchitecturePairXY"),Cr=ct(function(I){return I!=="LL"&&I!=="RR"&&I!=="TT"&&I!=="BB"},"isValidArchitectureDirectionPair"),ye=ct(function(I,M){const C=`${I}${M}`;return Cr(C)?C:void 0},"getArchitectureDirectionPair"),Mr=ct(function([I,M],C){const x=C[0],N=C[1];return Wt(x)?qt(N)?[I+(x==="L"?-1:1),M+(N==="T"?1:-1)]:[I+(x==="L"?-1:1),M]:Wt(N)?[I+(N==="L"?1:-1),M+(x==="T"?1:-1)]:[I,M+(x==="T"?1:-1)]},"shiftPositionByArchitectureDirectionPair"),Ar=ct(function(I){return I==="LT"||I==="TL"?[1,1]:I==="BL"||I==="LB"?[1,-1]:I==="BR"||I==="RB"?[-1,-1]:[-1,1]},"getArchitectureDirectionXYFactors"),Dr=ct(function(I,M){return Ne(I,M)?"bend":Wt(I)?"horizontal":"vertical"},"getArchitectureDirectionAlignment"),Or=ct(function(I){return I.type==="service"},"isArchitectureService"),xr=ct(function(I){return I.type==="junction"},"isArchitectureJunction"),Pe=ct((I,M)=>{const[C,x]=[I,M].sort();return`${JSON.stringify(C)}-${JSON.stringify(x)}`},"architectureGroupAlignmentKey"),Ge=ct(I=>I.data(),"edgeData"),ie=ct(I=>I.data(),"nodeData"),Ir=or.architecture,ae,Ue=(ae=class{constructor(){this.nodes=new Map,this.groups=new Map,this.edges=[],this.layoutHints=[],this.registeredIds=new Map,this.elements=new Map,this.diagramId="",this.setAccTitle=Ke,this.getAccTitle=je,this.setDiagramTitle=_e,this.getDiagramTitle=tr,this.getAccDescription=er,this.setAccDescription=rr,this.clear()}setDiagramId(M){this.diagramId=M}getDiagramId(){return this.diagramId}clear(){this.nodes=new Map,this.groups=new Map,this.edges=[],this.layoutHints=[],this.registeredIds=new Map,this.dataStructures=void 0,this.elements=new Map,this.diagramId="",ir()}addService({id:M,icon:C,in:x,title:N,iconText:v}){if(this.registeredIds.has(M))throw new Error(`The service id [${M}] is already in use by another ${this.registeredIds.get(M)}`);if(x!==void 0){if(M===x)throw new Error(`The service [${M}] cannot be placed within itself`);if(!this.registeredIds.has(x))throw new Error(`The service [${M}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds.get(x)==="node")throw new Error(`The service [${M}]'s parent is not a group`)}this.registeredIds.set(M,"node"),this.nodes.set(M,{id:M,type:"service",icon:C,iconText:v,title:N,edges:[],in:x})}getServices(){return[...this.nodes.values()].filter(Or)}addJunction({id:M,in:C}){if(this.registeredIds.has(M))throw new Error(`The junction id [${M}] is already in use by another ${this.registeredIds.get(M)}`);if(C!==void 0){if(M===C)throw new Error(`The junction [${M}] cannot be placed within itself`);if(!this.registeredIds.has(C))throw new Error(`The junction [${M}]'s parent does not exist. Please make sure the parent is created before this junction`);if(this.registeredIds.get(C)==="node")throw new Error(`The junction [${M}]'s parent is not a group`)}this.registeredIds.set(M,"node"),this.nodes.set(M,{id:M,type:"junction",edges:[],in:C})}getJunctions(){return[...this.nodes.values()].filter(xr)}getNodes(){return[...this.nodes.values()]}getNode(M){return this.nodes.get(M)??null}addGroup({id:M,icon:C,in:x,title:N}){if(this.registeredIds.has(M))throw new Error(`The group id [${M}] is already in use by another ${this.registeredIds.get(M)}`);if(x!==void 0){if(M===x)throw new Error(`The group [${M}] cannot be placed within itself`);if(!this.registeredIds.has(x))throw new Error(`The group [${M}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds.get(x)==="node")throw new Error(`The group [${M}]'s parent is not a group`)}this.registeredIds.set(M,"group"),this.groups.set(M,{id:M,icon:C,title:N,in:x})}getGroups(){return[...this.groups.values()]}addEdge({lhsId:M,rhsId:C,lhsDir:x,rhsDir:N,lhsInto:v,rhsInto:l,lhsGroup:n,rhsGroup:r,title:i}){if(!Se(x))throw new Error(`Invalid direction given for left hand side of edge ${M}--${C}. Expected (L,R,T,B) got ${String(x)}`);if(!Se(N))throw new Error(`Invalid direction given for right hand side of edge ${M}--${C}. Expected (L,R,T,B) got ${String(N)}`);if(!this.nodes.has(M)&&!this.groups.has(M))throw new Error(`The left-hand id [${M}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(!this.nodes.has(C)&&!this.groups.has(C))throw new Error(`The right-hand id [${C}] does not yet exist. Please create the service/group before declaring an edge to it.`);const f=this.nodes.get(M).in,e=this.nodes.get(C).in;if(n&&f&&e&&f==e)throw new Error(`The left-hand id [${M}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(r&&f&&e&&f==e)throw new Error(`The right-hand id [${C}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);const g={lhsId:M,lhsDir:x,lhsInto:v,lhsGroup:n,rhsId:C,rhsDir:N,rhsInto:l,rhsGroup:r,title:i};this.edges.push(g);const t=this.nodes.get(M),s=this.nodes.get(C);t&&s&&(t.edges.push(this.edges[this.edges.length-1]),s.edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}addLayoutHint(M){if(M.members.length<2)throw new Error(`An align directive requires at least two members; got ${M.members.length}`);const C=new Set;M.members.forEach(x=>{if(this.registeredIds.get(x)!=="node")throw new Error(`align ${M.direction} references [${x}], which is not a service or junction`);if(C.has(x))throw new Error(`align ${M.direction} lists [${x}] more than once`);C.add(x)}),this.layoutHints.push(M)}getLayoutHints(){return this.layoutHints}getDataStructures(){var M,C;if(this.dataStructures===void 0){const x=new Map,N=new Map;for(const[i,f]of this.nodes.entries()){const e=new Map;for(const g of f.edges){const t=(M=this.getNode(g.lhsId))==null?void 0:M.in,s=(C=this.getNode(g.rhsId))==null?void 0:C.in;if(t&&s&&t!==s){const o=Dr(g.lhsDir,g.rhsDir);o!=="bend"&&x.set(Pe(t,s),o)}if(g.lhsId===i){const o=ye(g.lhsDir,g.rhsDir);o&&e.set(o,g.rhsId)}else{const o=ye(g.rhsDir,g.lhsDir);o&&e.set(o,g.lhsId)}}N.set(i,e)}const v=new Set,l=new Set(N.keys()),n=ct(i=>{const f=new Map([[i,[0,0]]]),e=[i];for(;e.length>0;){const g=e.shift();if(g){v.add(g),l.delete(g);const t=N.get(g);if(!t)throw new Error(`BFS error: adjacency list for id ${g} not found. Please report this as a bug.`);const s=f.get(g);if(!s)throw new Error(`BFS error: position for id ${g} not found in spatial map. Please report this as a bug.`);const[o,c]=s;t.forEach((h,T)=>{v.has(h)||(f.set(h,Mr([o,c],T)),e.push(h))})}}return f},"BFS"),r=[];for(;l.size>0;){const i=l.values().next().value;r.push(n(i))}this.dataStructures={adjList:N,spatialMaps:r,groupAlignments:x}}return this.dataStructures}setElementForId(M,C){this.elements.set(M,C)}getElementById(M){return this.elements.get(M)}getConfig(){return ar({...Ir,...nr().architecture})}getConfigField(M){return this.getConfig()[M]}},ct(ae,"ArchitectureDB"),ae),Rr=ct((I,M)=>{var C;qe(I,M),I.groups.map(x=>M.addGroup(x)),I.services.map(x=>M.addService({...x,type:"service"})),I.junctions.map(x=>M.addJunction({...x,type:"junction"})),I.edges.map(x=>M.addEdge(x)),(C=I.alignments)==null||C.map(x=>M.addLayoutHint({direction:x.direction,members:[...x.members]}))},"populateDb"),Ye={parser:{yy:void 0},parse:ct(async I=>{var x;const M=await cr("architecture",I);Fe.debug(M);const C=(x=Ye.parser)==null?void 0:x.yy;if(!(C instanceof Ue))throw new Error("parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");Rr(M,C)},"parse")},Sr=ct(I=>` .edge { stroke-width: ${I.archEdgeWidth}; stroke: ${I.archEdgeColor}; diff --git a/static/ml_canvas/assets/blockDiagram-I7D4REHJ-C2vNrp8X.js b/static/ml_canvas/assets/blockDiagram-I7D4REHJ-Dwrazez5.js similarity index 99% rename from static/ml_canvas/assets/blockDiagram-I7D4REHJ-C2vNrp8X.js rename to static/ml_canvas/assets/blockDiagram-I7D4REHJ-Dwrazez5.js index 99b9c60af..2a28d59b0 100644 --- a/static/ml_canvas/assets/blockDiagram-I7D4REHJ-C2vNrp8X.js +++ b/static/ml_canvas/assets/blockDiagram-I7D4REHJ-Dwrazez5.js @@ -1,4 +1,4 @@ -import{g as Pe}from"./chunk-5VM5RSS4-W4WNe2RE.js";import{_ as g,x as X,am as Fe,d as Me,l as y,o as Ke,r as Ye,c as me,S as We,aj as Ve,ai as Ue,ak as He,j as je,an as Xe,a2 as ye,a3 as Ge}from"./mermaid.core-BCO0YdKy.js";import{s as qe,t as be,v as Je,w as Ze,x as Qe,y as $e,z as et,A as tt,D as st,E as rt,F as it,G as nt,H as at,I as ot,J as ct,K as lt,L as ut,M as gt,N as ht,O as dt,P as pt,Q as ft,S as St,U as xt,V as Lt,W as mt}from"./vendor-charts-CwfdE1jD.js";import{s as J}from"./vendor-flow-bDma3vSM.js";import{c as yt}from"./channel-Dp8JVrfa.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";function bt(e){if(qe(e))return e;const a=be(e);if(!wt(e))return{};if(Je(e)){const s=Array.from(e);return e.length>0&&typeof e[0]=="string"&&Object.hasOwn(e,"index")&&(s.index=e.index,s.input=e.input),s}if(Ze(e)){const s=e,c=s.constructor;return new c(s.buffer,s.byteOffset,s.length)}if(a==="[object ArrayBuffer]")return new ArrayBuffer(e.byteLength);if(a==="[object DataView]"){const s=e,c=s.buffer,p=s.byteOffset,r=s.byteLength,d=new ArrayBuffer(r),x=new Uint8Array(c,p,r);return new Uint8Array(d).set(x),new DataView(d)}if(a==="[object Boolean]"||a==="[object Number]"||a==="[object String]"){const s=e.constructor,c=new s(e.valueOf());return a==="[object String]"?_t(c,e):re(c,e),c}if(a==="[object Date]")return new Date(Number(e));if(a==="[object RegExp]"){const s=e,c=new RegExp(s.source,s.flags);return c.lastIndex=s.lastIndex,c}if(a==="[object Symbol]")return Object(Symbol.prototype.valueOf.call(e));if(a==="[object Map]"){const s=e,c=new Map;return s.forEach((p,r)=>{c.set(r,p)}),c}if(a==="[object Set]"){const s=e,c=new Set;return s.forEach(p=>{c.add(p)}),c}if(a==="[object Arguments]"){const s=e,c={};return re(c,s),c.length=s.length,c[Symbol.iterator]=s[Symbol.iterator],c}const l={};return Dt(l,e),re(l,e),Et(l,e),l}function wt(e){switch(be(e)){case mt:case Lt:case xt:case St:case ft:case pt:case dt:case ht:case gt:case ut:case lt:case ct:case ot:case at:case nt:case it:case rt:case st:case tt:case et:case $e:case Qe:return!0;default:return!1}}function re(e,a){for(const l in a)Object.hasOwn(a,l)&&(e[l]=a[l])}function Et(e,a){const l=Object.getOwnPropertySymbols(a);for(let s=0;s=l)&&(e[s]=a[s])}function Dt(e,a){const l=Object.getPrototypeOf(a);l!==null&&typeof a.constructor=="function"&&Object.setPrototypeOf(e,l)}var ne=(function(){var e=g(function(T,h,i,o){for(i=i||{},o=T.length;o--;i[T[o]]=h);return i},"o"),a=[1,15],l=[1,7],s=[1,13],c=[1,14],p=[1,19],r=[1,16],d=[1,17],x=[1,18],m=[8,30],S=[8,10,21,28,29,30,31,39,43,46],E=[1,23],z=[1,24],A=[8,10,15,16,21,28,29,30,31,39,43,46],_=[8,10,15,16,21,27,28,29,30,31,39,43,46],N=[1,49],I={trace:g(function(){},"trace"),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:"error",4:"SPACELINE",5:"NL",7:"SPACE",8:"EOF",10:"BLOCK_DIAGRAM_KEY",15:"LINK",16:"START_LINK",17:"LINK_LABEL",18:"STR",21:"SPACE_BLOCK",27:"SIZE",28:"COLUMNS",29:"id-block",30:"end",31:"NODE_ID",34:"DIR",35:"NODE_DSTART",36:"NODE_DEND",37:"BLOCK_ARROW_START",38:"BLOCK_ARROW_END",39:"classDef",40:"CLASSDEF_ID",41:"CLASSDEF_STYLEOPTS",42:"DEFAULT",43:"class",44:"CLASSENTITY_IDS",45:"STYLECLASS",46:"style",47:"STYLE_ENTITY_IDS",48:"STYLE_DEFINITION_DATA"},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:g(function(h,i,o,u,L,t,O){var n=t.length-1;switch(L){case 4:u.getLogger().debug("Rule: separator (NL) ");break;case 5:u.getLogger().debug("Rule: separator (Space) ");break;case 6:u.getLogger().debug("Rule: separator (EOF) ");break;case 7:u.getLogger().debug("Rule: hierarchy: ",t[n-1]),u.setHierarchy(t[n-1]);break;case 8:u.getLogger().debug("Stop NL ");break;case 9:u.getLogger().debug("Stop EOF ");break;case 10:u.getLogger().debug("Stop NL2 ");break;case 11:u.getLogger().debug("Stop EOF2 ");break;case 12:u.getLogger().debug("Rule: statement: ",t[n]),typeof t[n].length=="number"?this.$=t[n]:this.$=[t[n]];break;case 13:u.getLogger().debug("Rule: statement #2: ",t[n-1]),this.$=[t[n-1]].concat(t[n]);break;case 14:u.getLogger().debug("Rule: link: ",t[n],h),this.$={edgeTypeStr:t[n],label:""};break;case 15:u.getLogger().debug("Rule: LABEL link: ",t[n-3],t[n-1],t[n]),this.$={edgeTypeStr:t[n],label:t[n-1]};break;case 18:const f=parseInt(t[n]),w=u.generateId();this.$={id:w,type:"space",label:"",width:f,children:[]};break;case 23:u.getLogger().debug("Rule: (nodeStatement link node) ",t[n-2],t[n-1],t[n]," typestr: ",t[n-1].edgeTypeStr);const C=u.edgeStrToEdgeData(t[n-1].edgeTypeStr),M=u.edgeStrToEdgeStartData(t[n-1].edgeTypeStr),K=u.edgeStrToThickness(t[n-1].edgeTypeStr),b=u.edgeStrToPattern(t[n-1].edgeTypeStr);this.$=[{id:t[n-2].id,label:t[n-2].label,type:t[n-2].type,directions:t[n-2].directions},{id:t[n-2].id+"-"+t[n].id,start:t[n-2].id,end:t[n].id,label:t[n-1].label,type:"edge",thickness:K,pattern:b,directions:t[n].directions,arrowTypeEnd:C,arrowTypeStart:M},{id:t[n].id,label:t[n].label,type:u.typeStr2Type(t[n].typeStr),directions:t[n].directions}];break;case 24:u.getLogger().debug("Rule: nodeStatement (abc88 node size) ",t[n-1],t[n]),this.$={id:t[n-1].id,label:t[n-1].label,type:u.typeStr2Type(t[n-1].typeStr),directions:t[n-1].directions,widthInColumns:parseInt(t[n],10)};break;case 25:u.getLogger().debug("Rule: nodeStatement (node) ",t[n]),this.$={id:t[n].id,label:t[n].label,type:u.typeStr2Type(t[n].typeStr),directions:t[n].directions,widthInColumns:1};break;case 26:u.getLogger().debug("APA123",this?this:"na"),u.getLogger().debug("COLUMNS: ",t[n]),this.$={type:"column-setting",columns:t[n]==="auto"?-1:parseInt(t[n])};break;case 27:u.getLogger().debug("Rule: id-block statement : ",t[n-2],t[n-1]),u.generateId(),this.$={...t[n-2],type:"composite",children:t[n-1]};break;case 28:u.getLogger().debug("Rule: blockStatement : ",t[n-2],t[n-1],t[n]);const R=u.generateId();this.$={id:R,type:"composite",label:"",children:t[n-1]};break;case 29:u.getLogger().debug("Rule: node (NODE_ID separator): ",t[n]),this.$={id:t[n]};break;case 30:u.getLogger().debug("Rule: node (NODE_ID nodeShapeNLabel separator): ",t[n-1],t[n]),this.$={id:t[n-1],label:t[n].label,typeStr:t[n].typeStr,directions:t[n].directions};break;case 31:u.getLogger().debug("Rule: dirList: ",t[n]),this.$=[t[n]];break;case 32:u.getLogger().debug("Rule: dirList: ",t[n-1],t[n]),this.$=[t[n-1]].concat(t[n]);break;case 33:u.getLogger().debug("Rule: nodeShapeNLabel: ",t[n-2],t[n-1],t[n]),this.$={typeStr:t[n-2]+t[n],label:t[n-1]};break;case 34:u.getLogger().debug("Rule: BLOCK_ARROW nodeShapeNLabel: ",t[n-3],t[n-2]," #3:",t[n-1],t[n]),this.$={typeStr:t[n-3]+t[n],label:t[n-2],directions:t[n-1]};break;case 35:case 36:this.$={type:"classDef",id:t[n-1].trim(),css:t[n].trim()};break;case 37:this.$={type:"applyClass",id:t[n-1].trim(),styleClass:t[n].trim()};break;case 38:this.$={type:"applyStyles",id:t[n-1].trim(),stylesStr:t[n].trim()};break}},"anonymous"),table:[{9:1,10:[1,2]},{1:[3]},{10:a,11:3,13:4,19:5,20:6,21:l,22:8,23:9,24:10,25:11,26:12,28:s,29:c,31:p,39:r,43:d,46:x},{8:[1,20]},e(m,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:a,21:l,28:s,29:c,31:p,39:r,43:d,46:x}),e(S,[2,16],{14:22,15:E,16:z}),e(S,[2,17]),e(S,[2,18]),e(S,[2,19]),e(S,[2,20]),e(S,[2,21]),e(S,[2,22]),e(A,[2,25],{27:[1,25]}),e(S,[2,26]),{19:26,26:12,31:p},{10:a,11:27,13:4,19:5,20:6,21:l,22:8,23:9,24:10,25:11,26:12,28:s,29:c,31:p,39:r,43:d,46:x},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},e(_,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},e(m,[2,13]),{26:35,31:p},{31:[2,14]},{17:[1,36]},e(A,[2,24]),{10:a,11:37,13:4,14:22,15:E,16:z,19:5,20:6,21:l,22:8,23:9,24:10,25:11,26:12,28:s,29:c,31:p,39:r,43:d,46:x},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},e(_,[2,30]),{18:[1,43]},{18:[1,44]},e(A,[2,23]),{18:[1,45]},{30:[1,46]},e(S,[2,28]),e(S,[2,35]),e(S,[2,36]),e(S,[2,37]),e(S,[2,38]),{36:[1,47]},{33:48,34:N},{15:[1,50]},e(S,[2,27]),e(_,[2,33]),{38:[1,51]},{33:52,34:N,38:[2,31]},{31:[2,15]},e(_,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:g(function(h,i){if(i.recoverable)this.trace(h);else{var o=new Error(h);throw o.hash=i,o}},"parseError"),parse:g(function(h){var i=this,o=[0],u=[],L=[null],t=[],O=this.table,n="",f=0,w=0,C=2,M=1,K=t.slice.call(arguments,1),b=Object.create(this.lexer),R={yy:{}};for(var Y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Y)&&(R.yy[Y]=this.yy[Y]);b.setInput(h,R.yy),R.yy.lexer=b,R.yy.parser=this,typeof b.yylloc>"u"&&(b.yylloc={});var H=b.yylloc;t.push(H);var ee=b.options&&b.options.ranges;typeof R.yy.parseError=="function"?this.parseError=R.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function ke(k){o.length=o.length-2*k,L.length=L.length-k,t.length=t.length-k}g(ke,"popStack");function pe(){var k;return k=u.pop()||b.lex()||M,typeof k!="number"&&(k instanceof Array&&(u=k,k=u.pop()),k=i.symbols_[k]||k),k}g(pe,"lex");for(var B,V,P,te,U={},G,W,fe,q;;){if(V=o[o.length-1],this.defaultActions[V]?P=this.defaultActions[V]:((B===null||typeof B>"u")&&(B=pe()),P=O[V]&&O[V][B]),typeof P>"u"||!P.length||!P[0]){var se="";q=[];for(G in O[V])this.terminals_[G]&&G>C&&q.push("'"+this.terminals_[G]+"'");b.showPosition?se="Parse error on line "+(f+1)+`: +import{g as Pe}from"./chunk-5VM5RSS4-CKRC1CIZ.js";import{_ as g,x as X,am as Fe,d as Me,l as y,o as Ke,r as Ye,c as me,S as We,aj as Ve,ai as Ue,ak as He,j as je,an as Xe,a2 as ye,a3 as Ge}from"./mermaid.core-BRmiRRt4.js";import{s as qe,t as be,v as Je,w as Ze,x as Qe,y as $e,z as et,A as tt,D as st,E as rt,F as it,G as nt,H as at,I as ot,J as ct,K as lt,L as ut,M as gt,N as ht,O as dt,P as pt,Q as ft,S as St,U as xt,V as Lt,W as mt}from"./vendor-charts-CwfdE1jD.js";import{s as J}from"./vendor-flow-bDma3vSM.js";import{c as yt}from"./channel-CtKHr9fF.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";function bt(e){if(qe(e))return e;const a=be(e);if(!wt(e))return{};if(Je(e)){const s=Array.from(e);return e.length>0&&typeof e[0]=="string"&&Object.hasOwn(e,"index")&&(s.index=e.index,s.input=e.input),s}if(Ze(e)){const s=e,c=s.constructor;return new c(s.buffer,s.byteOffset,s.length)}if(a==="[object ArrayBuffer]")return new ArrayBuffer(e.byteLength);if(a==="[object DataView]"){const s=e,c=s.buffer,p=s.byteOffset,r=s.byteLength,d=new ArrayBuffer(r),x=new Uint8Array(c,p,r);return new Uint8Array(d).set(x),new DataView(d)}if(a==="[object Boolean]"||a==="[object Number]"||a==="[object String]"){const s=e.constructor,c=new s(e.valueOf());return a==="[object String]"?_t(c,e):re(c,e),c}if(a==="[object Date]")return new Date(Number(e));if(a==="[object RegExp]"){const s=e,c=new RegExp(s.source,s.flags);return c.lastIndex=s.lastIndex,c}if(a==="[object Symbol]")return Object(Symbol.prototype.valueOf.call(e));if(a==="[object Map]"){const s=e,c=new Map;return s.forEach((p,r)=>{c.set(r,p)}),c}if(a==="[object Set]"){const s=e,c=new Set;return s.forEach(p=>{c.add(p)}),c}if(a==="[object Arguments]"){const s=e,c={};return re(c,s),c.length=s.length,c[Symbol.iterator]=s[Symbol.iterator],c}const l={};return Dt(l,e),re(l,e),Et(l,e),l}function wt(e){switch(be(e)){case mt:case Lt:case xt:case St:case ft:case pt:case dt:case ht:case gt:case ut:case lt:case ct:case ot:case at:case nt:case it:case rt:case st:case tt:case et:case $e:case Qe:return!0;default:return!1}}function re(e,a){for(const l in a)Object.hasOwn(a,l)&&(e[l]=a[l])}function Et(e,a){const l=Object.getOwnPropertySymbols(a);for(let s=0;s=l)&&(e[s]=a[s])}function Dt(e,a){const l=Object.getPrototypeOf(a);l!==null&&typeof a.constructor=="function"&&Object.setPrototypeOf(e,l)}var ne=(function(){var e=g(function(T,h,i,o){for(i=i||{},o=T.length;o--;i[T[o]]=h);return i},"o"),a=[1,15],l=[1,7],s=[1,13],c=[1,14],p=[1,19],r=[1,16],d=[1,17],x=[1,18],m=[8,30],S=[8,10,21,28,29,30,31,39,43,46],E=[1,23],z=[1,24],A=[8,10,15,16,21,28,29,30,31,39,43,46],_=[8,10,15,16,21,27,28,29,30,31,39,43,46],N=[1,49],I={trace:g(function(){},"trace"),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:"error",4:"SPACELINE",5:"NL",7:"SPACE",8:"EOF",10:"BLOCK_DIAGRAM_KEY",15:"LINK",16:"START_LINK",17:"LINK_LABEL",18:"STR",21:"SPACE_BLOCK",27:"SIZE",28:"COLUMNS",29:"id-block",30:"end",31:"NODE_ID",34:"DIR",35:"NODE_DSTART",36:"NODE_DEND",37:"BLOCK_ARROW_START",38:"BLOCK_ARROW_END",39:"classDef",40:"CLASSDEF_ID",41:"CLASSDEF_STYLEOPTS",42:"DEFAULT",43:"class",44:"CLASSENTITY_IDS",45:"STYLECLASS",46:"style",47:"STYLE_ENTITY_IDS",48:"STYLE_DEFINITION_DATA"},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:g(function(h,i,o,u,L,t,O){var n=t.length-1;switch(L){case 4:u.getLogger().debug("Rule: separator (NL) ");break;case 5:u.getLogger().debug("Rule: separator (Space) ");break;case 6:u.getLogger().debug("Rule: separator (EOF) ");break;case 7:u.getLogger().debug("Rule: hierarchy: ",t[n-1]),u.setHierarchy(t[n-1]);break;case 8:u.getLogger().debug("Stop NL ");break;case 9:u.getLogger().debug("Stop EOF ");break;case 10:u.getLogger().debug("Stop NL2 ");break;case 11:u.getLogger().debug("Stop EOF2 ");break;case 12:u.getLogger().debug("Rule: statement: ",t[n]),typeof t[n].length=="number"?this.$=t[n]:this.$=[t[n]];break;case 13:u.getLogger().debug("Rule: statement #2: ",t[n-1]),this.$=[t[n-1]].concat(t[n]);break;case 14:u.getLogger().debug("Rule: link: ",t[n],h),this.$={edgeTypeStr:t[n],label:""};break;case 15:u.getLogger().debug("Rule: LABEL link: ",t[n-3],t[n-1],t[n]),this.$={edgeTypeStr:t[n],label:t[n-1]};break;case 18:const f=parseInt(t[n]),w=u.generateId();this.$={id:w,type:"space",label:"",width:f,children:[]};break;case 23:u.getLogger().debug("Rule: (nodeStatement link node) ",t[n-2],t[n-1],t[n]," typestr: ",t[n-1].edgeTypeStr);const C=u.edgeStrToEdgeData(t[n-1].edgeTypeStr),M=u.edgeStrToEdgeStartData(t[n-1].edgeTypeStr),K=u.edgeStrToThickness(t[n-1].edgeTypeStr),b=u.edgeStrToPattern(t[n-1].edgeTypeStr);this.$=[{id:t[n-2].id,label:t[n-2].label,type:t[n-2].type,directions:t[n-2].directions},{id:t[n-2].id+"-"+t[n].id,start:t[n-2].id,end:t[n].id,label:t[n-1].label,type:"edge",thickness:K,pattern:b,directions:t[n].directions,arrowTypeEnd:C,arrowTypeStart:M},{id:t[n].id,label:t[n].label,type:u.typeStr2Type(t[n].typeStr),directions:t[n].directions}];break;case 24:u.getLogger().debug("Rule: nodeStatement (abc88 node size) ",t[n-1],t[n]),this.$={id:t[n-1].id,label:t[n-1].label,type:u.typeStr2Type(t[n-1].typeStr),directions:t[n-1].directions,widthInColumns:parseInt(t[n],10)};break;case 25:u.getLogger().debug("Rule: nodeStatement (node) ",t[n]),this.$={id:t[n].id,label:t[n].label,type:u.typeStr2Type(t[n].typeStr),directions:t[n].directions,widthInColumns:1};break;case 26:u.getLogger().debug("APA123",this?this:"na"),u.getLogger().debug("COLUMNS: ",t[n]),this.$={type:"column-setting",columns:t[n]==="auto"?-1:parseInt(t[n])};break;case 27:u.getLogger().debug("Rule: id-block statement : ",t[n-2],t[n-1]),u.generateId(),this.$={...t[n-2],type:"composite",children:t[n-1]};break;case 28:u.getLogger().debug("Rule: blockStatement : ",t[n-2],t[n-1],t[n]);const R=u.generateId();this.$={id:R,type:"composite",label:"",children:t[n-1]};break;case 29:u.getLogger().debug("Rule: node (NODE_ID separator): ",t[n]),this.$={id:t[n]};break;case 30:u.getLogger().debug("Rule: node (NODE_ID nodeShapeNLabel separator): ",t[n-1],t[n]),this.$={id:t[n-1],label:t[n].label,typeStr:t[n].typeStr,directions:t[n].directions};break;case 31:u.getLogger().debug("Rule: dirList: ",t[n]),this.$=[t[n]];break;case 32:u.getLogger().debug("Rule: dirList: ",t[n-1],t[n]),this.$=[t[n-1]].concat(t[n]);break;case 33:u.getLogger().debug("Rule: nodeShapeNLabel: ",t[n-2],t[n-1],t[n]),this.$={typeStr:t[n-2]+t[n],label:t[n-1]};break;case 34:u.getLogger().debug("Rule: BLOCK_ARROW nodeShapeNLabel: ",t[n-3],t[n-2]," #3:",t[n-1],t[n]),this.$={typeStr:t[n-3]+t[n],label:t[n-2],directions:t[n-1]};break;case 35:case 36:this.$={type:"classDef",id:t[n-1].trim(),css:t[n].trim()};break;case 37:this.$={type:"applyClass",id:t[n-1].trim(),styleClass:t[n].trim()};break;case 38:this.$={type:"applyStyles",id:t[n-1].trim(),stylesStr:t[n].trim()};break}},"anonymous"),table:[{9:1,10:[1,2]},{1:[3]},{10:a,11:3,13:4,19:5,20:6,21:l,22:8,23:9,24:10,25:11,26:12,28:s,29:c,31:p,39:r,43:d,46:x},{8:[1,20]},e(m,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:a,21:l,28:s,29:c,31:p,39:r,43:d,46:x}),e(S,[2,16],{14:22,15:E,16:z}),e(S,[2,17]),e(S,[2,18]),e(S,[2,19]),e(S,[2,20]),e(S,[2,21]),e(S,[2,22]),e(A,[2,25],{27:[1,25]}),e(S,[2,26]),{19:26,26:12,31:p},{10:a,11:27,13:4,19:5,20:6,21:l,22:8,23:9,24:10,25:11,26:12,28:s,29:c,31:p,39:r,43:d,46:x},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},e(_,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},e(m,[2,13]),{26:35,31:p},{31:[2,14]},{17:[1,36]},e(A,[2,24]),{10:a,11:37,13:4,14:22,15:E,16:z,19:5,20:6,21:l,22:8,23:9,24:10,25:11,26:12,28:s,29:c,31:p,39:r,43:d,46:x},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},e(_,[2,30]),{18:[1,43]},{18:[1,44]},e(A,[2,23]),{18:[1,45]},{30:[1,46]},e(S,[2,28]),e(S,[2,35]),e(S,[2,36]),e(S,[2,37]),e(S,[2,38]),{36:[1,47]},{33:48,34:N},{15:[1,50]},e(S,[2,27]),e(_,[2,33]),{38:[1,51]},{33:52,34:N,38:[2,31]},{31:[2,15]},e(_,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:g(function(h,i){if(i.recoverable)this.trace(h);else{var o=new Error(h);throw o.hash=i,o}},"parseError"),parse:g(function(h){var i=this,o=[0],u=[],L=[null],t=[],O=this.table,n="",f=0,w=0,C=2,M=1,K=t.slice.call(arguments,1),b=Object.create(this.lexer),R={yy:{}};for(var Y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Y)&&(R.yy[Y]=this.yy[Y]);b.setInput(h,R.yy),R.yy.lexer=b,R.yy.parser=this,typeof b.yylloc>"u"&&(b.yylloc={});var H=b.yylloc;t.push(H);var ee=b.options&&b.options.ranges;typeof R.yy.parseError=="function"?this.parseError=R.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function ke(k){o.length=o.length-2*k,L.length=L.length-k,t.length=t.length-k}g(ke,"popStack");function pe(){var k;return k=u.pop()||b.lex()||M,typeof k!="number"&&(k instanceof Array&&(u=k,k=u.pop()),k=i.symbols_[k]||k),k}g(pe,"lex");for(var B,V,P,te,U={},G,W,fe,q;;){if(V=o[o.length-1],this.defaultActions[V]?P=this.defaultActions[V]:((B===null||typeof B>"u")&&(B=pe()),P=O[V]&&O[V][B]),typeof P>"u"||!P.length||!P[0]){var se="";q=[];for(G in O[V])this.terminals_[G]&&G>C&&q.push("'"+this.terminals_[G]+"'");b.showPosition?se="Parse error on line "+(f+1)+`: `+b.showPosition()+` Expecting `+q.join(", ")+", got '"+(this.terminals_[B]||B)+"'":se="Parse error on line "+(f+1)+": Unexpected "+(B==M?"end of input":"'"+(this.terminals_[B]||B)+"'"),this.parseError(se,{text:b.match,token:this.terminals_[B]||B,line:b.yylineno,loc:H,expected:q})}if(P[0]instanceof Array&&P.length>1)throw new Error("Parse Error: multiple actions possible at state: "+V+", token: "+B);switch(P[0]){case 1:o.push(B),L.push(b.yytext),t.push(b.yylloc),o.push(P[1]),B=null,w=b.yyleng,n=b.yytext,f=b.yylineno,H=b.yylloc;break;case 2:if(W=this.productions_[P[1]][1],U.$=L[L.length-W],U._$={first_line:t[t.length-(W||1)].first_line,last_line:t[t.length-1].last_line,first_column:t[t.length-(W||1)].first_column,last_column:t[t.length-1].last_column},ee&&(U._$.range=[t[t.length-(W||1)].range[0],t[t.length-1].range[1]]),te=this.performAction.apply(U,[n,w,f,R.yy,P[1],L,t].concat(K)),typeof te<"u")return te;W&&(o=o.slice(0,-1*W*2),L=L.slice(0,-1*W),t=t.slice(0,-1*W)),o.push(this.productions_[P[1]][0]),L.push(U.$),t.push(U._$),fe=O[o[o.length-2]][o[o.length-1]],o.push(fe);break;case 3:return!0}}return!0},"parse")},D=(function(){var T={EOF:1,parseError:g(function(i,o){if(this.yy.parser)this.yy.parser.parseError(i,o);else throw new Error(i)},"parseError"),setInput:g(function(h,i){return this.yy=i||this.yy||{},this._input=h,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:g(function(){var h=this._input[0];this.yytext+=h,this.yyleng++,this.offset++,this.match+=h,this.matched+=h;var i=h.match(/(?:\r\n?|\n).*/g);return i?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),h},"input"),unput:g(function(h){var i=h.length,o=h.split(/(?:\r\n?|\n)/g);this._input=h+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-i),this.offset-=i;var u=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),o.length-1&&(this.yylineno-=o.length-1);var L=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:o?(o.length===u.length?this.yylloc.first_column:0)+u[u.length-o.length].length-o[0].length:this.yylloc.first_column-i},this.options.ranges&&(this.yylloc.range=[L[0],L[0]+this.yyleng-i]),this.yyleng=this.yytext.length,this},"unput"),more:g(function(){return this._more=!0,this},"more"),reject:g(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:g(function(h){this.unput(this.match.slice(h))},"less"),pastInput:g(function(){var h=this.matched.substr(0,this.matched.length-this.match.length);return(h.length>20?"...":"")+h.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:g(function(){var h=this.match;return h.length<20&&(h+=this._input.substr(0,20-h.length)),(h.substr(0,20)+(h.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:g(function(){var h=this.pastInput(),i=new Array(h.length+1).join("-");return h+this.upcomingInput()+` diff --git a/static/ml_canvas/assets/c4Diagram-7LVT6UL2-F8JSoWFY.js b/static/ml_canvas/assets/c4Diagram-7LVT6UL2-Dp-1gW55.js similarity index 99% rename from static/ml_canvas/assets/c4Diagram-7LVT6UL2-F8JSoWFY.js rename to static/ml_canvas/assets/c4Diagram-7LVT6UL2-Dp-1gW55.js index 7783d0c05..f3f460bb8 100644 --- a/static/ml_canvas/assets/c4Diagram-7LVT6UL2-F8JSoWFY.js +++ b/static/ml_canvas/assets/c4Diagram-7LVT6UL2-Dp-1gW55.js @@ -1,4 +1,4 @@ -import{d as Le}from"./chunk-F27PBJKO-Dm2Us476.js";import{s as Ie,g as Me,a as Be,b as Ve,_ as d,c as wt,l as he,d as Ye,e as Fe,f as Dt,h as Ue,i as me,w as je,j as $t,k as de}from"./mermaid.core-BCO0YdKy.js";import{s as Jt}from"./vendor-flow-bDma3vSM.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var Ut=(function(){var t=d(function(yt,b,x,E){for(x=x||{},E=yt.length;E--;x[yt[E]]=b);return x},"o"),e=[1,24],s=[1,25],o=[1,26],l=[1,27],a=[1,28],n=[1,63],u=[1,64],r=[1,65],h=[1,66],y=[1,67],f=[1,68],m=[1,69],v=[1,29],w=[1,30],N=[1,31],O=[1,32],P=[1,33],I=[1,34],W=[1,35],X=[1,36],q=[1,37],H=[1,38],Q=[1,39],K=[1,40],G=[1,41],J=[1,42],Z=[1,43],$=[1,44],tt=[1,45],et=[1,46],nt=[1,47],st=[1,48],rt=[1,50],at=[1,51],it=[1,52],ot=[1,53],lt=[1,54],ct=[1,55],ut=[1,56],ht=[1,57],dt=[1,58],pt=[1,59],ft=[1,60],kt=[14,42],Wt=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],Ot=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],S=[1,82],k=[1,83],T=[1,84],C=[1,85],R=[12,14,42],ie=[12,14,33,42],Mt=[12,14,33,42,76,77,79,80],gt=[12,33],Xt=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],qt={trace:d(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:"error",6:"direction_tb",7:"direction_bt",8:"direction_rl",9:"direction_lr",11:"C4_CONTEXT",12:"NEWLINE",14:"EOF",15:"C4_CONTAINER",16:"C4_COMPONENT",17:"C4_DYNAMIC",18:"C4_DEPLOYMENT",22:"title",23:"accDescription",24:"acc_title",25:"acc_title_value",26:"acc_descr",27:"acc_descr_value",28:"acc_descr_multiline_value",33:"LBRACE",34:"ENTERPRISE_BOUNDARY",36:"SYSTEM_BOUNDARY",37:"BOUNDARY",38:"CONTAINER_BOUNDARY",39:"NODE",40:"NODE_L",41:"NODE_R",42:"RBRACE",44:"PERSON",45:"PERSON_EXT",46:"SYSTEM",47:"SYSTEM_DB",48:"SYSTEM_QUEUE",49:"SYSTEM_EXT",50:"SYSTEM_EXT_DB",51:"SYSTEM_EXT_QUEUE",52:"CONTAINER",53:"CONTAINER_DB",54:"CONTAINER_QUEUE",55:"CONTAINER_EXT",56:"CONTAINER_EXT_DB",57:"CONTAINER_EXT_QUEUE",58:"COMPONENT",59:"COMPONENT_DB",60:"COMPONENT_QUEUE",61:"COMPONENT_EXT",62:"COMPONENT_EXT_DB",63:"COMPONENT_EXT_QUEUE",64:"REL",65:"BIREL",66:"REL_U",67:"REL_D",68:"REL_L",69:"REL_R",70:"REL_B",71:"REL_INDEX",72:"UPDATE_EL_STYLE",73:"UPDATE_REL_STYLE",74:"UPDATE_LAYOUT_CONFIG",76:"STR",77:"STR_KEY",78:"STR_VALUE",79:"ATTRIBUTE",80:"ATTRIBUTE_EMPTY"},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:d(function(b,x,E,_,D,i,Pt){var p=i.length-1;switch(D){case 3:_.setDirection("TB");break;case 4:_.setDirection("BT");break;case 5:_.setDirection("RL");break;case 6:_.setDirection("LR");break;case 8:case 9:case 10:case 11:case 12:_.setC4Type(i[p-3]);break;case 19:_.setTitle(i[p].substring(6)),this.$=i[p].substring(6);break;case 20:_.setAccDescription(i[p].substring(15)),this.$=i[p].substring(15);break;case 21:this.$=i[p].trim(),_.setTitle(this.$);break;case 22:case 23:this.$=i[p].trim(),_.setAccDescription(this.$);break;case 28:i[p].splice(2,0,"ENTERPRISE"),_.addPersonOrSystemBoundary(...i[p]),this.$=i[p];break;case 29:i[p].splice(2,0,"SYSTEM"),_.addPersonOrSystemBoundary(...i[p]),this.$=i[p];break;case 30:_.addPersonOrSystemBoundary(...i[p]),this.$=i[p];break;case 31:i[p].splice(2,0,"CONTAINER"),_.addContainerBoundary(...i[p]),this.$=i[p];break;case 32:_.addDeploymentNode("node",...i[p]),this.$=i[p];break;case 33:_.addDeploymentNode("nodeL",...i[p]),this.$=i[p];break;case 34:_.addDeploymentNode("nodeR",...i[p]),this.$=i[p];break;case 35:_.popBoundaryParseStack();break;case 39:_.addPersonOrSystem("person",...i[p]),this.$=i[p];break;case 40:_.addPersonOrSystem("external_person",...i[p]),this.$=i[p];break;case 41:_.addPersonOrSystem("system",...i[p]),this.$=i[p];break;case 42:_.addPersonOrSystem("system_db",...i[p]),this.$=i[p];break;case 43:_.addPersonOrSystem("system_queue",...i[p]),this.$=i[p];break;case 44:_.addPersonOrSystem("external_system",...i[p]),this.$=i[p];break;case 45:_.addPersonOrSystem("external_system_db",...i[p]),this.$=i[p];break;case 46:_.addPersonOrSystem("external_system_queue",...i[p]),this.$=i[p];break;case 47:_.addContainer("container",...i[p]),this.$=i[p];break;case 48:_.addContainer("container_db",...i[p]),this.$=i[p];break;case 49:_.addContainer("container_queue",...i[p]),this.$=i[p];break;case 50:_.addContainer("external_container",...i[p]),this.$=i[p];break;case 51:_.addContainer("external_container_db",...i[p]),this.$=i[p];break;case 52:_.addContainer("external_container_queue",...i[p]),this.$=i[p];break;case 53:_.addComponent("component",...i[p]),this.$=i[p];break;case 54:_.addComponent("component_db",...i[p]),this.$=i[p];break;case 55:_.addComponent("component_queue",...i[p]),this.$=i[p];break;case 56:_.addComponent("external_component",...i[p]),this.$=i[p];break;case 57:_.addComponent("external_component_db",...i[p]),this.$=i[p];break;case 58:_.addComponent("external_component_queue",...i[p]),this.$=i[p];break;case 60:_.addRel("rel",...i[p]),this.$=i[p];break;case 61:_.addRel("birel",...i[p]),this.$=i[p];break;case 62:_.addRel("rel_u",...i[p]),this.$=i[p];break;case 63:_.addRel("rel_d",...i[p]),this.$=i[p];break;case 64:_.addRel("rel_l",...i[p]),this.$=i[p];break;case 65:_.addRel("rel_r",...i[p]),this.$=i[p];break;case 66:_.addRel("rel_b",...i[p]),this.$=i[p];break;case 67:i[p].splice(0,1),_.addRel("rel",...i[p]),this.$=i[p];break;case 68:_.updateElStyle("update_el_style",...i[p]),this.$=i[p];break;case 69:_.updateRelStyle("update_rel_style",...i[p]),this.$=i[p];break;case 70:_.updateLayoutConfig("update_layout_config",...i[p]),this.$=i[p];break;case 71:this.$=[i[p]];break;case 72:i[p].unshift(i[p-1]),this.$=i[p];break;case 73:case 75:this.$=i[p].trim();break;case 74:let xt={};xt[i[p-1].trim()]=i[p].trim(),this.$=xt;break;case 76:this.$="";break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:70,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:71,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:72,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:73,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{14:[1,74]},t(kt,[2,13],{43:23,29:49,30:61,32:62,20:75,34:n,36:u,37:r,38:h,39:y,40:f,41:m,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft}),t(kt,[2,14]),t(Wt,[2,16],{12:[1,76]}),t(kt,[2,36],{12:[1,77]}),t(Ot,[2,19]),t(Ot,[2,20]),{25:[1,78]},{27:[1,79]},t(Ot,[2,23]),{35:80,75:81,76:S,77:k,79:T,80:C},{35:86,75:81,76:S,77:k,79:T,80:C},{35:87,75:81,76:S,77:k,79:T,80:C},{35:88,75:81,76:S,77:k,79:T,80:C},{35:89,75:81,76:S,77:k,79:T,80:C},{35:90,75:81,76:S,77:k,79:T,80:C},{35:91,75:81,76:S,77:k,79:T,80:C},{35:92,75:81,76:S,77:k,79:T,80:C},{35:93,75:81,76:S,77:k,79:T,80:C},{35:94,75:81,76:S,77:k,79:T,80:C},{35:95,75:81,76:S,77:k,79:T,80:C},{35:96,75:81,76:S,77:k,79:T,80:C},{35:97,75:81,76:S,77:k,79:T,80:C},{35:98,75:81,76:S,77:k,79:T,80:C},{35:99,75:81,76:S,77:k,79:T,80:C},{35:100,75:81,76:S,77:k,79:T,80:C},{35:101,75:81,76:S,77:k,79:T,80:C},{35:102,75:81,76:S,77:k,79:T,80:C},{35:103,75:81,76:S,77:k,79:T,80:C},{35:104,75:81,76:S,77:k,79:T,80:C},t(R,[2,59]),{35:105,75:81,76:S,77:k,79:T,80:C},{35:106,75:81,76:S,77:k,79:T,80:C},{35:107,75:81,76:S,77:k,79:T,80:C},{35:108,75:81,76:S,77:k,79:T,80:C},{35:109,75:81,76:S,77:k,79:T,80:C},{35:110,75:81,76:S,77:k,79:T,80:C},{35:111,75:81,76:S,77:k,79:T,80:C},{35:112,75:81,76:S,77:k,79:T,80:C},{35:113,75:81,76:S,77:k,79:T,80:C},{35:114,75:81,76:S,77:k,79:T,80:C},{35:115,75:81,76:S,77:k,79:T,80:C},{20:116,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{12:[1,118],33:[1,117]},{35:119,75:81,76:S,77:k,79:T,80:C},{35:120,75:81,76:S,77:k,79:T,80:C},{35:121,75:81,76:S,77:k,79:T,80:C},{35:122,75:81,76:S,77:k,79:T,80:C},{35:123,75:81,76:S,77:k,79:T,80:C},{35:124,75:81,76:S,77:k,79:T,80:C},{35:125,75:81,76:S,77:k,79:T,80:C},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},t(kt,[2,15]),t(Wt,[2,17],{21:22,19:130,22:e,23:s,24:o,26:l,28:a}),t(kt,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:e,23:s,24:o,26:l,28:a,34:n,36:u,37:r,38:h,39:y,40:f,41:m,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft}),t(Ot,[2,21]),t(Ot,[2,22]),t(R,[2,39]),t(ie,[2,71],{75:81,35:132,76:S,77:k,79:T,80:C}),t(Mt,[2,73]),{78:[1,133]},t(Mt,[2,75]),t(Mt,[2,76]),t(R,[2,40]),t(R,[2,41]),t(R,[2,42]),t(R,[2,43]),t(R,[2,44]),t(R,[2,45]),t(R,[2,46]),t(R,[2,47]),t(R,[2,48]),t(R,[2,49]),t(R,[2,50]),t(R,[2,51]),t(R,[2,52]),t(R,[2,53]),t(R,[2,54]),t(R,[2,55]),t(R,[2,56]),t(R,[2,57]),t(R,[2,58]),t(R,[2,60]),t(R,[2,61]),t(R,[2,62]),t(R,[2,63]),t(R,[2,64]),t(R,[2,65]),t(R,[2,66]),t(R,[2,67]),t(R,[2,68]),t(R,[2,69]),t(R,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},t(gt,[2,28]),t(gt,[2,29]),t(gt,[2,30]),t(gt,[2,31]),t(gt,[2,32]),t(gt,[2,33]),t(gt,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},t(Wt,[2,18]),t(kt,[2,38]),t(ie,[2,72]),t(Mt,[2,74]),t(R,[2,24]),t(R,[2,35]),t(Xt,[2,25]),t(Xt,[2,26],{12:[1,138]}),t(Xt,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:d(function(b,x){if(x.recoverable)this.trace(b);else{var E=new Error(b);throw E.hash=x,E}},"parseError"),parse:d(function(b){var x=this,E=[0],_=[],D=[null],i=[],Pt=this.table,p="",xt=0,oe=0,Pe=2,le=1,De=i.slice.call(arguments,1),A=Object.create(this.lexer),vt={yy:{}};for(var Ht in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Ht)&&(vt.yy[Ht]=this.yy[Ht]);A.setInput(b,vt.yy),vt.yy.lexer=A,vt.yy.parser=this,typeof A.yylloc>"u"&&(A.yylloc={});var Qt=A.yylloc;i.push(Qt);var Ne=A.options&&A.options.ranges;typeof vt.yy.parseError=="function"?this.parseError=vt.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Ae(B){E.length=E.length-2*B,D.length=D.length-B,i.length=i.length-B}d(Ae,"popStack");function ce(){var B;return B=_.pop()||A.lex()||le,typeof B!="number"&&(B instanceof Array&&(_=B,B=_.pop()),B=x.symbols_[B]||B),B}d(ce,"lex");for(var M,Et,V,Kt,Tt={},Vt,j,ue,Yt;;){if(Et=E[E.length-1],this.defaultActions[Et]?V=this.defaultActions[Et]:((M===null||typeof M>"u")&&(M=ce()),V=Pt[Et]&&Pt[Et][M]),typeof V>"u"||!V.length||!V[0]){var Gt="";Yt=[];for(Vt in Pt[Et])this.terminals_[Vt]&&Vt>Pe&&Yt.push("'"+this.terminals_[Vt]+"'");A.showPosition?Gt="Parse error on line "+(xt+1)+`: +import{d as Le}from"./chunk-F27PBJKO-B7fm5O2R.js";import{s as Ie,g as Me,a as Be,b as Ve,_ as d,c as wt,l as he,d as Ye,e as Fe,f as Dt,h as Ue,i as me,w as je,j as $t,k as de}from"./mermaid.core-BRmiRRt4.js";import{s as Jt}from"./vendor-flow-bDma3vSM.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var Ut=(function(){var t=d(function(yt,b,x,E){for(x=x||{},E=yt.length;E--;x[yt[E]]=b);return x},"o"),e=[1,24],s=[1,25],o=[1,26],l=[1,27],a=[1,28],n=[1,63],u=[1,64],r=[1,65],h=[1,66],y=[1,67],f=[1,68],m=[1,69],v=[1,29],w=[1,30],N=[1,31],O=[1,32],P=[1,33],I=[1,34],W=[1,35],X=[1,36],q=[1,37],H=[1,38],Q=[1,39],K=[1,40],G=[1,41],J=[1,42],Z=[1,43],$=[1,44],tt=[1,45],et=[1,46],nt=[1,47],st=[1,48],rt=[1,50],at=[1,51],it=[1,52],ot=[1,53],lt=[1,54],ct=[1,55],ut=[1,56],ht=[1,57],dt=[1,58],pt=[1,59],ft=[1,60],kt=[14,42],Wt=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],Ot=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],S=[1,82],k=[1,83],T=[1,84],C=[1,85],R=[12,14,42],ie=[12,14,33,42],Mt=[12,14,33,42,76,77,79,80],gt=[12,33],Xt=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],qt={trace:d(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:"error",6:"direction_tb",7:"direction_bt",8:"direction_rl",9:"direction_lr",11:"C4_CONTEXT",12:"NEWLINE",14:"EOF",15:"C4_CONTAINER",16:"C4_COMPONENT",17:"C4_DYNAMIC",18:"C4_DEPLOYMENT",22:"title",23:"accDescription",24:"acc_title",25:"acc_title_value",26:"acc_descr",27:"acc_descr_value",28:"acc_descr_multiline_value",33:"LBRACE",34:"ENTERPRISE_BOUNDARY",36:"SYSTEM_BOUNDARY",37:"BOUNDARY",38:"CONTAINER_BOUNDARY",39:"NODE",40:"NODE_L",41:"NODE_R",42:"RBRACE",44:"PERSON",45:"PERSON_EXT",46:"SYSTEM",47:"SYSTEM_DB",48:"SYSTEM_QUEUE",49:"SYSTEM_EXT",50:"SYSTEM_EXT_DB",51:"SYSTEM_EXT_QUEUE",52:"CONTAINER",53:"CONTAINER_DB",54:"CONTAINER_QUEUE",55:"CONTAINER_EXT",56:"CONTAINER_EXT_DB",57:"CONTAINER_EXT_QUEUE",58:"COMPONENT",59:"COMPONENT_DB",60:"COMPONENT_QUEUE",61:"COMPONENT_EXT",62:"COMPONENT_EXT_DB",63:"COMPONENT_EXT_QUEUE",64:"REL",65:"BIREL",66:"REL_U",67:"REL_D",68:"REL_L",69:"REL_R",70:"REL_B",71:"REL_INDEX",72:"UPDATE_EL_STYLE",73:"UPDATE_REL_STYLE",74:"UPDATE_LAYOUT_CONFIG",76:"STR",77:"STR_KEY",78:"STR_VALUE",79:"ATTRIBUTE",80:"ATTRIBUTE_EMPTY"},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:d(function(b,x,E,_,D,i,Pt){var p=i.length-1;switch(D){case 3:_.setDirection("TB");break;case 4:_.setDirection("BT");break;case 5:_.setDirection("RL");break;case 6:_.setDirection("LR");break;case 8:case 9:case 10:case 11:case 12:_.setC4Type(i[p-3]);break;case 19:_.setTitle(i[p].substring(6)),this.$=i[p].substring(6);break;case 20:_.setAccDescription(i[p].substring(15)),this.$=i[p].substring(15);break;case 21:this.$=i[p].trim(),_.setTitle(this.$);break;case 22:case 23:this.$=i[p].trim(),_.setAccDescription(this.$);break;case 28:i[p].splice(2,0,"ENTERPRISE"),_.addPersonOrSystemBoundary(...i[p]),this.$=i[p];break;case 29:i[p].splice(2,0,"SYSTEM"),_.addPersonOrSystemBoundary(...i[p]),this.$=i[p];break;case 30:_.addPersonOrSystemBoundary(...i[p]),this.$=i[p];break;case 31:i[p].splice(2,0,"CONTAINER"),_.addContainerBoundary(...i[p]),this.$=i[p];break;case 32:_.addDeploymentNode("node",...i[p]),this.$=i[p];break;case 33:_.addDeploymentNode("nodeL",...i[p]),this.$=i[p];break;case 34:_.addDeploymentNode("nodeR",...i[p]),this.$=i[p];break;case 35:_.popBoundaryParseStack();break;case 39:_.addPersonOrSystem("person",...i[p]),this.$=i[p];break;case 40:_.addPersonOrSystem("external_person",...i[p]),this.$=i[p];break;case 41:_.addPersonOrSystem("system",...i[p]),this.$=i[p];break;case 42:_.addPersonOrSystem("system_db",...i[p]),this.$=i[p];break;case 43:_.addPersonOrSystem("system_queue",...i[p]),this.$=i[p];break;case 44:_.addPersonOrSystem("external_system",...i[p]),this.$=i[p];break;case 45:_.addPersonOrSystem("external_system_db",...i[p]),this.$=i[p];break;case 46:_.addPersonOrSystem("external_system_queue",...i[p]),this.$=i[p];break;case 47:_.addContainer("container",...i[p]),this.$=i[p];break;case 48:_.addContainer("container_db",...i[p]),this.$=i[p];break;case 49:_.addContainer("container_queue",...i[p]),this.$=i[p];break;case 50:_.addContainer("external_container",...i[p]),this.$=i[p];break;case 51:_.addContainer("external_container_db",...i[p]),this.$=i[p];break;case 52:_.addContainer("external_container_queue",...i[p]),this.$=i[p];break;case 53:_.addComponent("component",...i[p]),this.$=i[p];break;case 54:_.addComponent("component_db",...i[p]),this.$=i[p];break;case 55:_.addComponent("component_queue",...i[p]),this.$=i[p];break;case 56:_.addComponent("external_component",...i[p]),this.$=i[p];break;case 57:_.addComponent("external_component_db",...i[p]),this.$=i[p];break;case 58:_.addComponent("external_component_queue",...i[p]),this.$=i[p];break;case 60:_.addRel("rel",...i[p]),this.$=i[p];break;case 61:_.addRel("birel",...i[p]),this.$=i[p];break;case 62:_.addRel("rel_u",...i[p]),this.$=i[p];break;case 63:_.addRel("rel_d",...i[p]),this.$=i[p];break;case 64:_.addRel("rel_l",...i[p]),this.$=i[p];break;case 65:_.addRel("rel_r",...i[p]),this.$=i[p];break;case 66:_.addRel("rel_b",...i[p]),this.$=i[p];break;case 67:i[p].splice(0,1),_.addRel("rel",...i[p]),this.$=i[p];break;case 68:_.updateElStyle("update_el_style",...i[p]),this.$=i[p];break;case 69:_.updateRelStyle("update_rel_style",...i[p]),this.$=i[p];break;case 70:_.updateLayoutConfig("update_layout_config",...i[p]),this.$=i[p];break;case 71:this.$=[i[p]];break;case 72:i[p].unshift(i[p-1]),this.$=i[p];break;case 73:case 75:this.$=i[p].trim();break;case 74:let xt={};xt[i[p-1].trim()]=i[p].trim(),this.$=xt;break;case 76:this.$="";break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:70,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:71,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:72,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{13:73,19:20,20:21,21:22,22:e,23:s,24:o,26:l,28:a,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{14:[1,74]},t(kt,[2,13],{43:23,29:49,30:61,32:62,20:75,34:n,36:u,37:r,38:h,39:y,40:f,41:m,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft}),t(kt,[2,14]),t(Wt,[2,16],{12:[1,76]}),t(kt,[2,36],{12:[1,77]}),t(Ot,[2,19]),t(Ot,[2,20]),{25:[1,78]},{27:[1,79]},t(Ot,[2,23]),{35:80,75:81,76:S,77:k,79:T,80:C},{35:86,75:81,76:S,77:k,79:T,80:C},{35:87,75:81,76:S,77:k,79:T,80:C},{35:88,75:81,76:S,77:k,79:T,80:C},{35:89,75:81,76:S,77:k,79:T,80:C},{35:90,75:81,76:S,77:k,79:T,80:C},{35:91,75:81,76:S,77:k,79:T,80:C},{35:92,75:81,76:S,77:k,79:T,80:C},{35:93,75:81,76:S,77:k,79:T,80:C},{35:94,75:81,76:S,77:k,79:T,80:C},{35:95,75:81,76:S,77:k,79:T,80:C},{35:96,75:81,76:S,77:k,79:T,80:C},{35:97,75:81,76:S,77:k,79:T,80:C},{35:98,75:81,76:S,77:k,79:T,80:C},{35:99,75:81,76:S,77:k,79:T,80:C},{35:100,75:81,76:S,77:k,79:T,80:C},{35:101,75:81,76:S,77:k,79:T,80:C},{35:102,75:81,76:S,77:k,79:T,80:C},{35:103,75:81,76:S,77:k,79:T,80:C},{35:104,75:81,76:S,77:k,79:T,80:C},t(R,[2,59]),{35:105,75:81,76:S,77:k,79:T,80:C},{35:106,75:81,76:S,77:k,79:T,80:C},{35:107,75:81,76:S,77:k,79:T,80:C},{35:108,75:81,76:S,77:k,79:T,80:C},{35:109,75:81,76:S,77:k,79:T,80:C},{35:110,75:81,76:S,77:k,79:T,80:C},{35:111,75:81,76:S,77:k,79:T,80:C},{35:112,75:81,76:S,77:k,79:T,80:C},{35:113,75:81,76:S,77:k,79:T,80:C},{35:114,75:81,76:S,77:k,79:T,80:C},{35:115,75:81,76:S,77:k,79:T,80:C},{20:116,29:49,30:61,32:62,34:n,36:u,37:r,38:h,39:y,40:f,41:m,43:23,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft},{12:[1,118],33:[1,117]},{35:119,75:81,76:S,77:k,79:T,80:C},{35:120,75:81,76:S,77:k,79:T,80:C},{35:121,75:81,76:S,77:k,79:T,80:C},{35:122,75:81,76:S,77:k,79:T,80:C},{35:123,75:81,76:S,77:k,79:T,80:C},{35:124,75:81,76:S,77:k,79:T,80:C},{35:125,75:81,76:S,77:k,79:T,80:C},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},t(kt,[2,15]),t(Wt,[2,17],{21:22,19:130,22:e,23:s,24:o,26:l,28:a}),t(kt,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:e,23:s,24:o,26:l,28:a,34:n,36:u,37:r,38:h,39:y,40:f,41:m,44:v,45:w,46:N,47:O,48:P,49:I,50:W,51:X,52:q,53:H,54:Q,55:K,56:G,57:J,58:Z,59:$,60:tt,61:et,62:nt,63:st,64:rt,65:at,66:it,67:ot,68:lt,69:ct,70:ut,71:ht,72:dt,73:pt,74:ft}),t(Ot,[2,21]),t(Ot,[2,22]),t(R,[2,39]),t(ie,[2,71],{75:81,35:132,76:S,77:k,79:T,80:C}),t(Mt,[2,73]),{78:[1,133]},t(Mt,[2,75]),t(Mt,[2,76]),t(R,[2,40]),t(R,[2,41]),t(R,[2,42]),t(R,[2,43]),t(R,[2,44]),t(R,[2,45]),t(R,[2,46]),t(R,[2,47]),t(R,[2,48]),t(R,[2,49]),t(R,[2,50]),t(R,[2,51]),t(R,[2,52]),t(R,[2,53]),t(R,[2,54]),t(R,[2,55]),t(R,[2,56]),t(R,[2,57]),t(R,[2,58]),t(R,[2,60]),t(R,[2,61]),t(R,[2,62]),t(R,[2,63]),t(R,[2,64]),t(R,[2,65]),t(R,[2,66]),t(R,[2,67]),t(R,[2,68]),t(R,[2,69]),t(R,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},t(gt,[2,28]),t(gt,[2,29]),t(gt,[2,30]),t(gt,[2,31]),t(gt,[2,32]),t(gt,[2,33]),t(gt,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},t(Wt,[2,18]),t(kt,[2,38]),t(ie,[2,72]),t(Mt,[2,74]),t(R,[2,24]),t(R,[2,35]),t(Xt,[2,25]),t(Xt,[2,26],{12:[1,138]}),t(Xt,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:d(function(b,x){if(x.recoverable)this.trace(b);else{var E=new Error(b);throw E.hash=x,E}},"parseError"),parse:d(function(b){var x=this,E=[0],_=[],D=[null],i=[],Pt=this.table,p="",xt=0,oe=0,Pe=2,le=1,De=i.slice.call(arguments,1),A=Object.create(this.lexer),vt={yy:{}};for(var Ht in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Ht)&&(vt.yy[Ht]=this.yy[Ht]);A.setInput(b,vt.yy),vt.yy.lexer=A,vt.yy.parser=this,typeof A.yylloc>"u"&&(A.yylloc={});var Qt=A.yylloc;i.push(Qt);var Ne=A.options&&A.options.ranges;typeof vt.yy.parseError=="function"?this.parseError=vt.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Ae(B){E.length=E.length-2*B,D.length=D.length-B,i.length=i.length-B}d(Ae,"popStack");function ce(){var B;return B=_.pop()||A.lex()||le,typeof B!="number"&&(B instanceof Array&&(_=B,B=_.pop()),B=x.symbols_[B]||B),B}d(ce,"lex");for(var M,Et,V,Kt,Tt={},Vt,j,ue,Yt;;){if(Et=E[E.length-1],this.defaultActions[Et]?V=this.defaultActions[Et]:((M===null||typeof M>"u")&&(M=ce()),V=Pt[Et]&&Pt[Et][M]),typeof V>"u"||!V.length||!V[0]){var Gt="";Yt=[];for(Vt in Pt[Et])this.terminals_[Vt]&&Vt>Pe&&Yt.push("'"+this.terminals_[Vt]+"'");A.showPosition?Gt="Parse error on line "+(xt+1)+`: `+A.showPosition()+` Expecting `+Yt.join(", ")+", got '"+(this.terminals_[M]||M)+"'":Gt="Parse error on line "+(xt+1)+": Unexpected "+(M==le?"end of input":"'"+(this.terminals_[M]||M)+"'"),this.parseError(Gt,{text:A.match,token:this.terminals_[M]||M,line:A.yylineno,loc:Qt,expected:Yt})}if(V[0]instanceof Array&&V.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Et+", token: "+M);switch(V[0]){case 1:E.push(M),D.push(A.yytext),i.push(A.yylloc),E.push(V[1]),M=null,oe=A.yyleng,p=A.yytext,xt=A.yylineno,Qt=A.yylloc;break;case 2:if(j=this.productions_[V[1]][1],Tt.$=D[D.length-j],Tt._$={first_line:i[i.length-(j||1)].first_line,last_line:i[i.length-1].last_line,first_column:i[i.length-(j||1)].first_column,last_column:i[i.length-1].last_column},Ne&&(Tt._$.range=[i[i.length-(j||1)].range[0],i[i.length-1].range[1]]),Kt=this.performAction.apply(Tt,[p,oe,xt,vt.yy,V[1],D,i].concat(De)),typeof Kt<"u")return Kt;j&&(E=E.slice(0,-1*j*2),D=D.slice(0,-1*j),i=i.slice(0,-1*j)),E.push(this.productions_[V[1]][0]),D.push(Tt.$),i.push(Tt._$),ue=Pt[E[E.length-2]][E[E.length-1]],E.push(ue);break;case 3:return!0}}return!0},"parse")},Oe=(function(){var yt={EOF:1,parseError:d(function(x,E){if(this.yy.parser)this.yy.parser.parseError(x,E);else throw new Error(x)},"parseError"),setInput:d(function(b,x){return this.yy=x||this.yy||{},this._input=b,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:d(function(){var b=this._input[0];this.yytext+=b,this.yyleng++,this.offset++,this.match+=b,this.matched+=b;var x=b.match(/(?:\r\n?|\n).*/g);return x?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),b},"input"),unput:d(function(b){var x=b.length,E=b.split(/(?:\r\n?|\n)/g);this._input=b+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-x),this.offset-=x;var _=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),E.length-1&&(this.yylineno-=E.length-1);var D=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:E?(E.length===_.length?this.yylloc.first_column:0)+_[_.length-E.length].length-E[0].length:this.yylloc.first_column-x},this.options.ranges&&(this.yylloc.range=[D[0],D[0]+this.yyleng-x]),this.yyleng=this.yytext.length,this},"unput"),more:d(function(){return this._more=!0,this},"more"),reject:d(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:d(function(b){this.unput(this.match.slice(b))},"less"),pastInput:d(function(){var b=this.matched.substr(0,this.matched.length-this.match.length);return(b.length>20?"...":"")+b.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:d(function(){var b=this.match;return b.length<20&&(b+=this._input.substr(0,20-b.length)),(b.substr(0,20)+(b.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:d(function(){var b=this.pastInput(),x=new Array(b.length+1).join("-");return b+this.upcomingInput()+` diff --git a/static/ml_canvas/assets/channel-CtKHr9fF.js b/static/ml_canvas/assets/channel-CtKHr9fF.js new file mode 100644 index 000000000..b3542aeb1 --- /dev/null +++ b/static/ml_canvas/assets/channel-CtKHr9fF.js @@ -0,0 +1 @@ +import{U as a,R as n}from"./mermaid.core-BRmiRRt4.js";const t=(r,o)=>a.lang.round(n.parse(r)[o]);export{t as c}; diff --git a/static/ml_canvas/assets/channel-Dp8JVrfa.js b/static/ml_canvas/assets/channel-Dp8JVrfa.js deleted file mode 100644 index 4185211f9..000000000 --- a/static/ml_canvas/assets/channel-Dp8JVrfa.js +++ /dev/null @@ -1 +0,0 @@ -import{U as a,R as n}from"./mermaid.core-BCO0YdKy.js";const t=(r,o)=>a.lang.round(n.parse(r)[o]);export{t as c}; diff --git a/static/ml_canvas/assets/chunk-2Q5K7J3B-DEOZDP-3.js b/static/ml_canvas/assets/chunk-2Q5K7J3B-BAAo9EN0.js similarity index 66% rename from static/ml_canvas/assets/chunk-2Q5K7J3B-DEOZDP-3.js rename to static/ml_canvas/assets/chunk-2Q5K7J3B-BAAo9EN0.js index 31cbbfca0..7b95a0dff 100644 --- a/static/ml_canvas/assets/chunk-2Q5K7J3B-DEOZDP-3.js +++ b/static/ml_canvas/assets/chunk-2Q5K7J3B-BAAo9EN0.js @@ -1 +1 @@ -import{_ as s}from"./mermaid.core-BCO0YdKy.js";var t,e=(t=class{constructor(i){this.init=i,this.records=this.init()}reset(){this.records=this.init()}},s(t,"ImperativeState"),t);export{e as I}; +import{_ as s}from"./mermaid.core-BRmiRRt4.js";var t,e=(t=class{constructor(i){this.init=i,this.records=this.init()}reset(){this.records=this.init()}},s(t,"ImperativeState"),t);export{e as I}; diff --git a/static/ml_canvas/assets/chunk-5VM5RSS4-W4WNe2RE.js b/static/ml_canvas/assets/chunk-5VM5RSS4-CKRC1CIZ.js similarity index 83% rename from static/ml_canvas/assets/chunk-5VM5RSS4-W4WNe2RE.js rename to static/ml_canvas/assets/chunk-5VM5RSS4-CKRC1CIZ.js index a64bf3469..a6ca4d074 100644 --- a/static/ml_canvas/assets/chunk-5VM5RSS4-W4WNe2RE.js +++ b/static/ml_canvas/assets/chunk-5VM5RSS4-CKRC1CIZ.js @@ -1,4 +1,4 @@ -import{_ as e}from"./mermaid.core-BCO0YdKy.js";var l=e(()=>` +import{_ as e}from"./mermaid.core-BRmiRRt4.js";var l=e(()=>` /* Font Awesome icon styling - consolidated */ .label-icon { display: inline-block; diff --git a/static/ml_canvas/assets/chunk-F27PBJKO-Dm2Us476.js b/static/ml_canvas/assets/chunk-F27PBJKO-B7fm5O2R.js similarity index 96% rename from static/ml_canvas/assets/chunk-F27PBJKO-Dm2Us476.js rename to static/ml_canvas/assets/chunk-F27PBJKO-B7fm5O2R.js index 994d0ba17..143ff629e 100644 --- a/static/ml_canvas/assets/chunk-F27PBJKO-Dm2Us476.js +++ b/static/ml_canvas/assets/chunk-F27PBJKO-B7fm5O2R.js @@ -1 +1 @@ -import{_ as i,Q as d,H as o}from"./mermaid.core-BCO0YdKy.js";import{s as l}from"./vendor-flow-bDma3vSM.js";var x=i((r,t)=>{const e=r.append("rect");if(e.attr("x",t.x),e.attr("y",t.y),e.attr("fill",t.fill),e.attr("stroke",t.stroke),e.attr("width",t.width),e.attr("height",t.height),t.name&&e.attr("name",t.name),t.rx&&e.attr("rx",t.rx),t.ry&&e.attr("ry",t.ry),t.attrs!==void 0)for(const s in t.attrs)e.attr(s,t.attrs[s]);return t.class&&e.attr("class",t.class),e},"drawRect"),y=i((r,t)=>{const e={x:t.startx,y:t.starty,width:t.stopx-t.startx,height:t.stopy-t.starty,fill:t.fill,stroke:t.stroke,class:"rect"};x(r,e).lower()},"drawBackgroundRect"),m=i((r,t)=>{const e=t.text.replace(d," "),s=r.append("text");s.attr("x",t.x),s.attr("y",t.y),s.attr("class","legend"),s.style("text-anchor",t.anchor),t.class&&s.attr("class",t.class);const a=s.append("tspan");return a.attr("x",t.x+t.textMargin*2),a.text(e),s},"drawText"),g=i((r,t,e,s)=>{const a=r.append("image");a.attr("x",t),a.attr("y",e);const n=o.sanitizeUrl(s);a.attr("xlink:href",n)},"drawImage"),f=i((r,t,e,s)=>{const a=r.append("use");a.attr("x",t),a.attr("y",e);const n=o.sanitizeUrl(s);a.attr("xlink:href",`#${n}`)},"drawEmbeddedImage"),h=i(()=>({x:0,y:0,width:100,height:100,fill:"#EDF2AE",stroke:"#666",anchor:"start",rx:0,ry:0}),"getNoteRect"),w=i(()=>({x:0,y:0,width:100,height:100,"text-anchor":"start",style:"#666",textMargin:0,rx:0,ry:0,tspan:!0}),"getTextObj"),k=i(()=>{let r=l(".mermaidTooltip");return r.empty()&&(r=l("body").append("div").attr("class","mermaidTooltip").style("opacity",0).style("position","absolute").style("text-align","center").style("max-width","200px").style("padding","2px").style("font-size","12px").style("background","#ffffde").style("border","1px solid #333").style("border-radius","2px").style("pointer-events","none").style("z-index","100")),r},"createTooltip");export{y as a,h as b,f as c,x as d,g as e,k as f,w as g,m as h}; +import{_ as i,Q as d,H as o}from"./mermaid.core-BRmiRRt4.js";import{s as l}from"./vendor-flow-bDma3vSM.js";var x=i((r,t)=>{const e=r.append("rect");if(e.attr("x",t.x),e.attr("y",t.y),e.attr("fill",t.fill),e.attr("stroke",t.stroke),e.attr("width",t.width),e.attr("height",t.height),t.name&&e.attr("name",t.name),t.rx&&e.attr("rx",t.rx),t.ry&&e.attr("ry",t.ry),t.attrs!==void 0)for(const s in t.attrs)e.attr(s,t.attrs[s]);return t.class&&e.attr("class",t.class),e},"drawRect"),y=i((r,t)=>{const e={x:t.startx,y:t.starty,width:t.stopx-t.startx,height:t.stopy-t.starty,fill:t.fill,stroke:t.stroke,class:"rect"};x(r,e).lower()},"drawBackgroundRect"),m=i((r,t)=>{const e=t.text.replace(d," "),s=r.append("text");s.attr("x",t.x),s.attr("y",t.y),s.attr("class","legend"),s.style("text-anchor",t.anchor),t.class&&s.attr("class",t.class);const a=s.append("tspan");return a.attr("x",t.x+t.textMargin*2),a.text(e),s},"drawText"),g=i((r,t,e,s)=>{const a=r.append("image");a.attr("x",t),a.attr("y",e);const n=o.sanitizeUrl(s);a.attr("xlink:href",n)},"drawImage"),f=i((r,t,e,s)=>{const a=r.append("use");a.attr("x",t),a.attr("y",e);const n=o.sanitizeUrl(s);a.attr("xlink:href",`#${n}`)},"drawEmbeddedImage"),h=i(()=>({x:0,y:0,width:100,height:100,fill:"#EDF2AE",stroke:"#666",anchor:"start",rx:0,ry:0}),"getNoteRect"),w=i(()=>({x:0,y:0,width:100,height:100,"text-anchor":"start",style:"#666",textMargin:0,rx:0,ry:0,tspan:!0}),"getTextObj"),k=i(()=>{let r=l(".mermaidTooltip");return r.empty()&&(r=l("body").append("div").attr("class","mermaidTooltip").style("opacity",0).style("position","absolute").style("text-align","center").style("max-width","200px").style("padding","2px").style("font-size","12px").style("background","#ffffde").style("border","1px solid #333").style("border-radius","2px").style("pointer-events","none").style("z-index","100")),r},"createTooltip");export{y as a,h as b,f as c,x as d,g as e,k as f,w as g,m as h}; diff --git a/static/ml_canvas/assets/chunk-IMKFNOWR-DCz6O-wt.js b/static/ml_canvas/assets/chunk-IMKFNOWR-CU8_Ku5h.js similarity index 99% rename from static/ml_canvas/assets/chunk-IMKFNOWR-DCz6O-wt.js rename to static/ml_canvas/assets/chunk-IMKFNOWR-CU8_Ku5h.js index 8b2c67831..e0278c687 100644 --- a/static/ml_canvas/assets/chunk-IMKFNOWR-DCz6O-wt.js +++ b/static/ml_canvas/assets/chunk-IMKFNOWR-CU8_Ku5h.js @@ -1,4 +1,4 @@ -import{g as ee}from"./chunk-XXDRQBXY-CZsBIZJg.js";import{s as se}from"./chunk-POPQ4Y6H-BOk39pqP.js";import{_ as S,l as b,c as F,u as ie,v as re,a as ae,b as ne,g as oe,s as le,m as ce,n as he,T as ue,j as K,o as de,O as fe}from"./mermaid.core-BCO0YdKy.js";import{f as pe}from"./chunk-F27PBJKO-Dm2Us476.js";import{s as Dt}from"./vendor-flow-bDma3vSM.js";var Ct=(function(){var t=S(function(U,l,u,n){for(u=u||{},n=U.length;n--;u[U[n]]=l);return u},"o"),e=[1,2],s=[1,3],a=[1,4],i=[2,4],o=[1,9],h=[1,11],p=[1,16],d=[1,17],T=[1,18],E=[1,19],m=[1,33],O=[1,20],v=[1,21],x=[1,22],$=[1,23],I=[1,24],f=[1,26],L=[1,27],C=[1,28],V=[1,29],P=[1,30],k=[1,31],B=[1,32],j=[1,35],nt=[1,36],ot=[1,37],lt=[1,38],J=[1,34],y=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],ct=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],Lt=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],gt={trace:S(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",6:"SD",14:"DESCR",15:"-->",16:"HIDE_EMPTY",17:"scale",18:"WIDTH",19:"COMPOSIT_STATE",20:"STRUCT_START",21:"STRUCT_STOP",22:"STATE_DESCR",23:"AS",24:"ID",25:"FORK",26:"JOIN",27:"CHOICE",28:"CONCURRENT",29:"note",31:"NOTE_TEXT",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",38:"CLICK",39:"STRING",40:"HREF",41:"classDef",42:"CLASSDEF_ID",43:"CLASSDEF_STYLEOPTS",44:"DEFAULT",45:"style",46:"STYLE_IDS",47:"STYLEDEF_STYLEOPTS",48:"class",49:"CLASSENTITY_IDS",50:"STYLECLASS",51:"direction_tb",52:"direction_bt",53:"direction_rl",54:"direction_lr",56:";",57:"EDGE_STATE",58:"STYLE_SEPARATOR",59:"left_of",60:"right_of"},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:S(function(l,u,n,g,_,r,Y){var c=r.length-1;switch(_){case 3:return g.setRootDoc(r[c]),r[c];case 4:this.$=[];break;case 5:r[c]!="nl"&&(r[c-1].push(r[c]),this.$=r[c-1]);break;case 6:case 7:this.$=r[c];break;case 8:this.$="nl";break;case 12:this.$=r[c];break;case 13:const et=r[c-1];et.description=g.trimColon(r[c]),this.$=et;break;case 14:this.$={stmt:"relation",state1:r[c-2],state2:r[c]};break;case 15:const Tt=g.trimColon(r[c]);this.$={stmt:"relation",state1:r[c-3],state2:r[c-1],description:Tt};break;case 19:this.$={stmt:"state",id:r[c-3],type:"default",description:"",doc:r[c-1]};break;case 20:var G=r[c],q=r[c-2].trim();if(r[c].match(":")){var ut=r[c].split(":");G=ut[0],q=[q,ut[1]]}this.$={stmt:"state",id:G,type:"default",description:q};break;case 21:this.$={stmt:"state",id:r[c-3],type:"default",description:r[c-5],doc:r[c-1]};break;case 22:this.$={stmt:"state",id:r[c],type:"fork"};break;case 23:this.$={stmt:"state",id:r[c],type:"join"};break;case 24:this.$={stmt:"state",id:r[c],type:"choice"};break;case 25:this.$={stmt:"state",id:g.getDividerId(),type:"divider"};break;case 26:this.$={stmt:"state",id:r[c-1].trim(),note:{position:r[c-2].trim(),text:r[c].trim()}};break;case 29:this.$=r[c].trim(),g.setAccTitle(this.$);break;case 30:case 31:this.$=r[c].trim(),g.setAccDescription(this.$);break;case 32:this.$={stmt:"click",id:r[c-3],url:r[c-2],tooltip:r[c-1]};break;case 33:this.$={stmt:"click",id:r[c-3],url:r[c-1],tooltip:""};break;case 34:case 35:this.$={stmt:"classDef",id:r[c-1].trim(),classes:r[c].trim()};break;case 36:this.$={stmt:"style",id:r[c-1].trim(),styleClass:r[c].trim()};break;case 37:this.$={stmt:"applyClass",id:r[c-1].trim(),styleClass:r[c].trim()};break;case 38:g.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 39:g.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 40:g.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 41:g.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 44:case 45:this.$={stmt:"state",id:r[c].trim(),type:"default",description:""};break;case 46:this.$={stmt:"state",id:r[c-2].trim(),classes:[r[c].trim()],type:"default",description:""};break;case 47:this.$={stmt:"state",id:r[c-2].trim(),classes:[r[c].trim()],type:"default",description:""};break}},"anonymous"),table:[{3:1,4:e,5:s,6:a},{1:[3]},{3:5,4:e,5:s,6:a},{3:6,4:e,5:s,6:a},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],i,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:h,8:8,9:10,10:12,11:13,12:14,13:15,16:p,17:d,19:T,22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:p,17:d,19:T,22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,7]),t(y,[2,8]),t(y,[2,9]),t(y,[2,10]),t(y,[2,11]),t(y,[2,12],{14:[1,40],15:[1,41]}),t(y,[2,16]),{18:[1,42]},t(y,[2,18],{20:[1,43]}),{23:[1,44]},t(y,[2,22]),t(y,[2,23]),t(y,[2,24]),t(y,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(y,[2,28]),{34:[1,49]},{36:[1,50]},t(y,[2,31]),{13:51,24:m,57:J},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(ct,[2,44],{58:[1,56]}),t(ct,[2,45],{58:[1,57]}),t(y,[2,38]),t(y,[2,39]),t(y,[2,40]),t(y,[2,41]),t(y,[2,6]),t(y,[2,13]),{13:58,24:m,57:J},t(y,[2,17]),t(Lt,i,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(y,[2,29]),t(y,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(y,[2,14],{14:[1,71]}),{4:o,5:h,8:8,9:10,10:12,11:13,12:14,13:15,16:p,17:d,19:T,21:[1,72],22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(y,[2,34]),t(y,[2,35]),t(y,[2,36]),t(y,[2,37]),t(ct,[2,46]),t(ct,[2,47]),t(y,[2,15]),t(y,[2,19]),t(Lt,i,{7:78}),t(y,[2,26]),t(y,[2,27]),{5:[1,79]},{5:[1,80]},{4:o,5:h,8:8,9:10,10:12,11:13,12:14,13:15,16:p,17:d,19:T,21:[1,81],22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,32]),t(y,[2,33]),t(y,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:S(function(l,u){if(u.recoverable)this.trace(l);else{var n=new Error(l);throw n.hash=u,n}},"parseError"),parse:S(function(l){var u=this,n=[0],g=[],_=[null],r=[],Y=this.table,c="",G=0,q=0,ut=2,et=1,Tt=r.slice.call(arguments,1),D=Object.create(this.lexer),H={yy:{}};for(var Et in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Et)&&(H.yy[Et]=this.yy[Et]);D.setInput(l,H.yy),H.yy.lexer=D,H.yy.parser=this,typeof D.yylloc>"u"&&(D.yylloc={});var _t=D.yylloc;r.push(_t);var Zt=D.options&&D.options.ranges;typeof H.yy.parseError=="function"?this.parseError=H.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function te(R){n.length=n.length-2*R,_.length=_.length-R,r.length=r.length-R}S(te,"popStack");function wt(){var R;return R=g.pop()||D.lex()||et,typeof R!="number"&&(R instanceof Array&&(g=R,R=g.pop()),R=u.symbols_[R]||R),R}S(wt,"lex");for(var w,z,N,mt,Q={},dt,M,Ot,ft;;){if(z=n[n.length-1],this.defaultActions[z]?N=this.defaultActions[z]:((w===null||typeof w>"u")&&(w=wt()),N=Y[z]&&Y[z][w]),typeof N>"u"||!N.length||!N[0]){var bt="";ft=[];for(dt in Y[z])this.terminals_[dt]&&dt>ut&&ft.push("'"+this.terminals_[dt]+"'");D.showPosition?bt="Parse error on line "+(G+1)+`: +import{g as ee}from"./chunk-XXDRQBXY-DdoFz10O.js";import{s as se}from"./chunk-POPQ4Y6H-BR_pO24v.js";import{_ as S,l as b,c as F,u as ie,v as re,a as ae,b as ne,g as oe,s as le,m as ce,n as he,T as ue,j as K,o as de,O as fe}from"./mermaid.core-BRmiRRt4.js";import{f as pe}from"./chunk-F27PBJKO-B7fm5O2R.js";import{s as Dt}from"./vendor-flow-bDma3vSM.js";var Ct=(function(){var t=S(function(U,l,u,n){for(u=u||{},n=U.length;n--;u[U[n]]=l);return u},"o"),e=[1,2],s=[1,3],a=[1,4],i=[2,4],o=[1,9],h=[1,11],p=[1,16],d=[1,17],T=[1,18],E=[1,19],m=[1,33],O=[1,20],v=[1,21],x=[1,22],$=[1,23],I=[1,24],f=[1,26],L=[1,27],C=[1,28],V=[1,29],P=[1,30],k=[1,31],B=[1,32],j=[1,35],nt=[1,36],ot=[1,37],lt=[1,38],J=[1,34],y=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],ct=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],Lt=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],gt={trace:S(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",6:"SD",14:"DESCR",15:"-->",16:"HIDE_EMPTY",17:"scale",18:"WIDTH",19:"COMPOSIT_STATE",20:"STRUCT_START",21:"STRUCT_STOP",22:"STATE_DESCR",23:"AS",24:"ID",25:"FORK",26:"JOIN",27:"CHOICE",28:"CONCURRENT",29:"note",31:"NOTE_TEXT",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",38:"CLICK",39:"STRING",40:"HREF",41:"classDef",42:"CLASSDEF_ID",43:"CLASSDEF_STYLEOPTS",44:"DEFAULT",45:"style",46:"STYLE_IDS",47:"STYLEDEF_STYLEOPTS",48:"class",49:"CLASSENTITY_IDS",50:"STYLECLASS",51:"direction_tb",52:"direction_bt",53:"direction_rl",54:"direction_lr",56:";",57:"EDGE_STATE",58:"STYLE_SEPARATOR",59:"left_of",60:"right_of"},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:S(function(l,u,n,g,_,r,Y){var c=r.length-1;switch(_){case 3:return g.setRootDoc(r[c]),r[c];case 4:this.$=[];break;case 5:r[c]!="nl"&&(r[c-1].push(r[c]),this.$=r[c-1]);break;case 6:case 7:this.$=r[c];break;case 8:this.$="nl";break;case 12:this.$=r[c];break;case 13:const et=r[c-1];et.description=g.trimColon(r[c]),this.$=et;break;case 14:this.$={stmt:"relation",state1:r[c-2],state2:r[c]};break;case 15:const Tt=g.trimColon(r[c]);this.$={stmt:"relation",state1:r[c-3],state2:r[c-1],description:Tt};break;case 19:this.$={stmt:"state",id:r[c-3],type:"default",description:"",doc:r[c-1]};break;case 20:var G=r[c],q=r[c-2].trim();if(r[c].match(":")){var ut=r[c].split(":");G=ut[0],q=[q,ut[1]]}this.$={stmt:"state",id:G,type:"default",description:q};break;case 21:this.$={stmt:"state",id:r[c-3],type:"default",description:r[c-5],doc:r[c-1]};break;case 22:this.$={stmt:"state",id:r[c],type:"fork"};break;case 23:this.$={stmt:"state",id:r[c],type:"join"};break;case 24:this.$={stmt:"state",id:r[c],type:"choice"};break;case 25:this.$={stmt:"state",id:g.getDividerId(),type:"divider"};break;case 26:this.$={stmt:"state",id:r[c-1].trim(),note:{position:r[c-2].trim(),text:r[c].trim()}};break;case 29:this.$=r[c].trim(),g.setAccTitle(this.$);break;case 30:case 31:this.$=r[c].trim(),g.setAccDescription(this.$);break;case 32:this.$={stmt:"click",id:r[c-3],url:r[c-2],tooltip:r[c-1]};break;case 33:this.$={stmt:"click",id:r[c-3],url:r[c-1],tooltip:""};break;case 34:case 35:this.$={stmt:"classDef",id:r[c-1].trim(),classes:r[c].trim()};break;case 36:this.$={stmt:"style",id:r[c-1].trim(),styleClass:r[c].trim()};break;case 37:this.$={stmt:"applyClass",id:r[c-1].trim(),styleClass:r[c].trim()};break;case 38:g.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 39:g.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 40:g.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 41:g.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 44:case 45:this.$={stmt:"state",id:r[c].trim(),type:"default",description:""};break;case 46:this.$={stmt:"state",id:r[c-2].trim(),classes:[r[c].trim()],type:"default",description:""};break;case 47:this.$={stmt:"state",id:r[c-2].trim(),classes:[r[c].trim()],type:"default",description:""};break}},"anonymous"),table:[{3:1,4:e,5:s,6:a},{1:[3]},{3:5,4:e,5:s,6:a},{3:6,4:e,5:s,6:a},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],i,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:o,5:h,8:8,9:10,10:12,11:13,12:14,13:15,16:p,17:d,19:T,22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:p,17:d,19:T,22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,7]),t(y,[2,8]),t(y,[2,9]),t(y,[2,10]),t(y,[2,11]),t(y,[2,12],{14:[1,40],15:[1,41]}),t(y,[2,16]),{18:[1,42]},t(y,[2,18],{20:[1,43]}),{23:[1,44]},t(y,[2,22]),t(y,[2,23]),t(y,[2,24]),t(y,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(y,[2,28]),{34:[1,49]},{36:[1,50]},t(y,[2,31]),{13:51,24:m,57:J},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(ct,[2,44],{58:[1,56]}),t(ct,[2,45],{58:[1,57]}),t(y,[2,38]),t(y,[2,39]),t(y,[2,40]),t(y,[2,41]),t(y,[2,6]),t(y,[2,13]),{13:58,24:m,57:J},t(y,[2,17]),t(Lt,i,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(y,[2,29]),t(y,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(y,[2,14],{14:[1,71]}),{4:o,5:h,8:8,9:10,10:12,11:13,12:14,13:15,16:p,17:d,19:T,21:[1,72],22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(y,[2,34]),t(y,[2,35]),t(y,[2,36]),t(y,[2,37]),t(ct,[2,46]),t(ct,[2,47]),t(y,[2,15]),t(y,[2,19]),t(Lt,i,{7:78}),t(y,[2,26]),t(y,[2,27]),{5:[1,79]},{5:[1,80]},{4:o,5:h,8:8,9:10,10:12,11:13,12:14,13:15,16:p,17:d,19:T,21:[1,81],22:E,24:m,25:O,26:v,27:x,28:$,29:I,32:25,33:f,35:L,37:C,38:V,41:P,45:k,48:B,51:j,52:nt,53:ot,54:lt,57:J},t(y,[2,32]),t(y,[2,33]),t(y,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:S(function(l,u){if(u.recoverable)this.trace(l);else{var n=new Error(l);throw n.hash=u,n}},"parseError"),parse:S(function(l){var u=this,n=[0],g=[],_=[null],r=[],Y=this.table,c="",G=0,q=0,ut=2,et=1,Tt=r.slice.call(arguments,1),D=Object.create(this.lexer),H={yy:{}};for(var Et in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Et)&&(H.yy[Et]=this.yy[Et]);D.setInput(l,H.yy),H.yy.lexer=D,H.yy.parser=this,typeof D.yylloc>"u"&&(D.yylloc={});var _t=D.yylloc;r.push(_t);var Zt=D.options&&D.options.ranges;typeof H.yy.parseError=="function"?this.parseError=H.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function te(R){n.length=n.length-2*R,_.length=_.length-R,r.length=r.length-R}S(te,"popStack");function wt(){var R;return R=g.pop()||D.lex()||et,typeof R!="number"&&(R instanceof Array&&(g=R,R=g.pop()),R=u.symbols_[R]||R),R}S(wt,"lex");for(var w,z,N,mt,Q={},dt,M,Ot,ft;;){if(z=n[n.length-1],this.defaultActions[z]?N=this.defaultActions[z]:((w===null||typeof w>"u")&&(w=wt()),N=Y[z]&&Y[z][w]),typeof N>"u"||!N.length||!N[0]){var bt="";ft=[];for(dt in Y[z])this.terminals_[dt]&&dt>ut&&ft.push("'"+this.terminals_[dt]+"'");D.showPosition?bt="Parse error on line "+(G+1)+`: `+D.showPosition()+` Expecting `+ft.join(", ")+", got '"+(this.terminals_[w]||w)+"'":bt="Parse error on line "+(G+1)+": Unexpected "+(w==et?"end of input":"'"+(this.terminals_[w]||w)+"'"),this.parseError(bt,{text:D.match,token:this.terminals_[w]||w,line:D.yylineno,loc:_t,expected:ft})}if(N[0]instanceof Array&&N.length>1)throw new Error("Parse Error: multiple actions possible at state: "+z+", token: "+w);switch(N[0]){case 1:n.push(w),_.push(D.yytext),r.push(D.yylloc),n.push(N[1]),w=null,q=D.yyleng,c=D.yytext,G=D.yylineno,_t=D.yylloc;break;case 2:if(M=this.productions_[N[1]][1],Q.$=_[_.length-M],Q._$={first_line:r[r.length-(M||1)].first_line,last_line:r[r.length-1].last_line,first_column:r[r.length-(M||1)].first_column,last_column:r[r.length-1].last_column},Zt&&(Q._$.range=[r[r.length-(M||1)].range[0],r[r.length-1].range[1]]),mt=this.performAction.apply(Q,[c,q,G,H.yy,N[1],_,r].concat(Tt)),typeof mt<"u")return mt;M&&(n=n.slice(0,-1*M*2),_=_.slice(0,-1*M),r=r.slice(0,-1*M)),n.push(this.productions_[N[1]][0]),_.push(Q.$),r.push(Q._$),Ot=Y[n[n.length-2]][n[n.length-1]],n.push(Ot);break;case 3:return!0}}return!0},"parse")},Qt=(function(){var U={EOF:1,parseError:S(function(u,n){if(this.yy.parser)this.yy.parser.parseError(u,n);else throw new Error(u)},"parseError"),setInput:S(function(l,u){return this.yy=u||this.yy||{},this._input=l,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:S(function(){var l=this._input[0];this.yytext+=l,this.yyleng++,this.offset++,this.match+=l,this.matched+=l;var u=l.match(/(?:\r\n?|\n).*/g);return u?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),l},"input"),unput:S(function(l){var u=l.length,n=l.split(/(?:\r\n?|\n)/g);this._input=l+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-u),this.offset-=u;var g=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var _=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===g.length?this.yylloc.first_column:0)+g[g.length-n.length].length-n[0].length:this.yylloc.first_column-u},this.options.ranges&&(this.yylloc.range=[_[0],_[0]+this.yyleng-u]),this.yyleng=this.yytext.length,this},"unput"),more:S(function(){return this._more=!0,this},"more"),reject:S(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:S(function(l){this.unput(this.match.slice(l))},"less"),pastInput:S(function(){var l=this.matched.substr(0,this.matched.length-this.match.length);return(l.length>20?"...":"")+l.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:S(function(){var l=this.match;return l.length<20&&(l+=this._input.substr(0,20-l.length)),(l.substr(0,20)+(l.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:S(function(){var l=this.pastInput(),u=new Array(l.length+1).join("-");return l+this.upcomingInput()+` diff --git a/static/ml_canvas/assets/chunk-JWPE2WC7-_bXip4eZ.js b/static/ml_canvas/assets/chunk-JWPE2WC7-BQCQvAYF.js similarity index 78% rename from static/ml_canvas/assets/chunk-JWPE2WC7-_bXip4eZ.js rename to static/ml_canvas/assets/chunk-JWPE2WC7-BQCQvAYF.js index 6c6c11447..8e6bd7976 100644 --- a/static/ml_canvas/assets/chunk-JWPE2WC7-_bXip4eZ.js +++ b/static/ml_canvas/assets/chunk-JWPE2WC7-BQCQvAYF.js @@ -1 +1 @@ -import{_ as l}from"./mermaid.core-BCO0YdKy.js";function m(e,c){var i,t,o;e.accDescr&&((i=c.setAccDescription)==null||i.call(c,e.accDescr)),e.accTitle&&((t=c.setAccTitle)==null||t.call(c,e.accTitle)),e.title&&((o=c.setDiagramTitle)==null||o.call(c,e.title))}l(m,"populateCommonDb");export{m as p}; +import{_ as l}from"./mermaid.core-BRmiRRt4.js";function m(e,c){var i,t,o;e.accDescr&&((i=c.setAccDescription)==null||i.call(c,e.accDescr)),e.accTitle&&((t=c.setAccTitle)==null||t.call(c,e.accTitle)),e.title&&((o=c.setDiagramTitle)==null||o.call(c,e.title))}l(m,"populateCommonDb");export{m as p}; diff --git a/static/ml_canvas/assets/chunk-POPQ4Y6H-BOk39pqP.js b/static/ml_canvas/assets/chunk-POPQ4Y6H-BR_pO24v.js similarity index 87% rename from static/ml_canvas/assets/chunk-POPQ4Y6H-BOk39pqP.js rename to static/ml_canvas/assets/chunk-POPQ4Y6H-BR_pO24v.js index 157e61cba..4f650a4c8 100644 --- a/static/ml_canvas/assets/chunk-POPQ4Y6H-BOk39pqP.js +++ b/static/ml_canvas/assets/chunk-POPQ4Y6H-BR_pO24v.js @@ -1 +1 @@ -import{_ as a,d as w,l as x}from"./mermaid.core-BCO0YdKy.js";var B=a((e,t,i,o)=>{e.attr("class",i);const{width:r,height:h,x:n,y:c}=u(e,t);w(e,h,r,o);const s=d(n,c,r,h,t);e.attr("viewBox",s),x.debug(`viewBox configured: ${s} with padding: ${t}`)},"setupViewPortForSVG"),u=a((e,t)=>{var o;const i=((o=e.node())==null?void 0:o.getBBox())||{width:0,height:0,x:0,y:0};return{width:i.width+t*2,height:i.height+t*2,x:i.x,y:i.y}},"calculateDimensionsWithPadding"),d=a((e,t,i,o,r)=>`${e-r} ${t-r} ${i} ${o}`,"createViewBox");export{B as s}; +import{_ as a,d as w,l as x}from"./mermaid.core-BRmiRRt4.js";var B=a((e,t,i,o)=>{e.attr("class",i);const{width:r,height:h,x:n,y:c}=u(e,t);w(e,h,r,o);const s=d(n,c,r,h,t);e.attr("viewBox",s),x.debug(`viewBox configured: ${s} with padding: ${t}`)},"setupViewPortForSVG"),u=a((e,t)=>{var o;const i=((o=e.node())==null?void 0:o.getBBox())||{width:0,height:0,x:0,y:0};return{width:i.width+t*2,height:i.height+t*2,x:i.x,y:i.y}},"calculateDimensionsWithPadding"),d=a((e,t,i,o,r)=>`${e-r} ${t-r} ${i} ${o}`,"createViewBox");export{B as s}; diff --git a/static/ml_canvas/assets/chunk-SVP7TREG-Bg03xQLN.js b/static/ml_canvas/assets/chunk-SVP7TREG-CbDuCHXJ.js similarity index 99% rename from static/ml_canvas/assets/chunk-SVP7TREG-Bg03xQLN.js rename to static/ml_canvas/assets/chunk-SVP7TREG-CbDuCHXJ.js index 8599094ab..a1d283a76 100644 --- a/static/ml_canvas/assets/chunk-SVP7TREG-Bg03xQLN.js +++ b/static/ml_canvas/assets/chunk-SVP7TREG-CbDuCHXJ.js @@ -1,4 +1,4 @@ -import{_ as p,l as C,C as H,x as B,o as q,E as G,d as U,i as j,c as K}from"./mermaid.core-BCO0YdKy.js";var A="",M="",O="",D=[],b=new Map,v=p(e=>j(e,K()),"sanitizeText"),y=p(e=>{switch(e.type){case"terminal":return{...e,value:v(e.value)};case"nonterminal":return{...e,name:v(e.name)};case"sequence":return{...e,elements:e.elements.map(y)};case"choice":return{...e,alternatives:e.alternatives.map(y)};case"optional":return{...e,element:y(e.element)};case"repetition":return{...e,element:y(e.element),separator:e.separator?y(e.separator):void 0};case"special":return{...e,text:v(e.text)}}},"sanitizeAstNode"),J=p(()=>{A="",M="",O="",D.length=0,b.clear(),q(),C.debug("[Railroad] Database cleared")},"clear"),Y=p(e=>{A=v(e),C.debug("[Railroad] Title set:",e)},"setTitle"),P=p(()=>A,"getTitle"),Q=p(e=>{const i={...e,name:v(e.name),definition:y(e.definition),comment:e.comment?v(e.comment):void 0};C.debug("[Railroad] Adding rule:",i.name),b.has(i.name)&&C.warn(`[Railroad] Rule '${i.name}' is already defined. Overwriting.`),D.push(i),b.set(i.name,i)},"addRule"),Z=p(()=>D,"getRules"),V=p(e=>b.get(e),"getRule"),ee=p(e=>{M=v(e).replace(/^\s+/g,""),C.debug("[Railroad] Accessibility title set:",e)},"setAccTitle"),te=p(()=>M,"getAccTitle"),re=p(e=>{O=v(e).replace(/\n\s+/g,` +import{_ as p,l as C,C as H,x as B,o as q,E as G,d as U,i as j,c as K}from"./mermaid.core-BRmiRRt4.js";var A="",M="",O="",D=[],b=new Map,v=p(e=>j(e,K()),"sanitizeText"),y=p(e=>{switch(e.type){case"terminal":return{...e,value:v(e.value)};case"nonterminal":return{...e,name:v(e.name)};case"sequence":return{...e,elements:e.elements.map(y)};case"choice":return{...e,alternatives:e.alternatives.map(y)};case"optional":return{...e,element:y(e.element)};case"repetition":return{...e,element:y(e.element),separator:e.separator?y(e.separator):void 0};case"special":return{...e,text:v(e.text)}}},"sanitizeAstNode"),J=p(()=>{A="",M="",O="",D.length=0,b.clear(),q(),C.debug("[Railroad] Database cleared")},"clear"),Y=p(e=>{A=v(e),C.debug("[Railroad] Title set:",e)},"setTitle"),P=p(()=>A,"getTitle"),Q=p(e=>{const i={...e,name:v(e.name),definition:y(e.definition),comment:e.comment?v(e.comment):void 0};C.debug("[Railroad] Adding rule:",i.name),b.has(i.name)&&C.warn(`[Railroad] Rule '${i.name}' is already defined. Overwriting.`),D.push(i),b.set(i.name,i)},"addRule"),Z=p(()=>D,"getRules"),V=p(e=>b.get(e),"getRule"),ee=p(e=>{M=v(e).replace(/^\s+/g,""),C.debug("[Railroad] Accessibility title set:",e)},"setAccTitle"),te=p(()=>M,"getAccTitle"),re=p(e=>{O=v(e).replace(/\n\s+/g,` `),C.debug("[Railroad] Accessibility description set:",e)},"setAccDescription"),ie=p(()=>O,"getAccDescription"),ne=Y,ae=P,oe={clear:J,setTitle:Y,getTitle:P,addRule:Q,getRules:Z,getRule:V,setAccTitle:ee,getAccTitle:te,setAccDescription:re,getAccDescription:ie,setDiagramTitle:ne,getDiagramTitle:ae},f={compactMode:!1,padding:10,verticalSeparation:8,horizontalSeparation:10,arcRadius:10,fontSize:14,fontFamily:"monospace",terminalFill:"#FFFFC0",terminalStroke:"#000000",terminalTextColor:"#000000",nonTerminalFill:"#FFFFFF",nonTerminalStroke:"#000000",nonTerminalTextColor:"#000000",lineColor:"#000000",strokeWidth:2,markerFill:"#000000",commentFill:"#E8E8E8",commentStroke:"#888888",commentTextColor:"#666666",specialFill:"#F0E0FF",specialStroke:"#8800CC",ruleNameColor:"#000066",showMarkers:!0,markerRadius:5},le=/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$|^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch)\([\d\s%+,./-]+\)$|^[a-z]+$/i,se=/^[\w "',.-]+$/,de=new Set(["compactMode","padding","verticalSeparation","horizontalSeparation","arcRadius","fontSize","fontFamily","terminalFill","terminalStroke","terminalTextColor","nonTerminalFill","nonTerminalStroke","nonTerminalTextColor","lineColor","strokeWidth","markerFill","commentFill","commentStroke","commentTextColor","specialFill","specialStroke","ruleNameColor","showMarkers","markerRadius"]),L=p(e=>e?Object.keys(e).every(i=>i==="railroad"||de.has(i)):!1,"isRailroadStyleOptions"),ce=p(e=>e?"railroad"in e&&e.railroad?e.railroad:L(e)?e:{}:{},"extractRailroadOverrides"),me=p(e=>{if(!e||L(e))return{};const{railroad:i,svgId:a,theme:n,look:t,...r}=e;return r},"extractThemeOverrides"),m=p((e,i)=>{if(typeof e!="string")return i;const a=e.trim();return le.test(a)?a:i},"sanitizeColorValue"),I=p((e,i)=>{if(typeof e!="string")return i;const a=e.trim();return se.test(a)?a:i},"sanitizeFontFamilyValue"),F=p((e,i)=>{const a=typeof e=="number"?e:typeof e=="string"?Number.parseFloat(e):Number.NaN;return Number.isFinite(a)&&a>=0?a:i},"sanitizeNumberValue"),he=p(e=>{const i=typeof e=="number"?e:typeof e=="string"?Number.parseFloat(e):Number.NaN;return Number.isFinite(i)&&i>0?i:void 0},"parseThemeFontSize"),pe=p(e=>{const i=I(e.fontFamily,f.fontFamily),a=he(e.fontSize)??f.fontSize;return{...f,fontFamily:i,fontSize:a,terminalFill:m(e.secondBkg??e.secondaryColor,f.terminalFill),terminalStroke:m(e.secondaryBorderColor??e.lineColor,f.terminalStroke),terminalTextColor:m(e.secondaryTextColor??e.textColor,f.terminalTextColor),nonTerminalFill:m(e.mainBkg??e.background,f.nonTerminalFill),nonTerminalStroke:m(e.primaryBorderColor??e.lineColor,f.nonTerminalStroke),nonTerminalTextColor:m(e.primaryTextColor??e.textColor,f.nonTerminalTextColor),lineColor:m(e.lineColor,f.lineColor),markerFill:m(e.lineColor,f.markerFill),commentFill:m(e.labelBackground??e.tertiaryColor,f.commentFill),commentStroke:m(e.tertiaryBorderColor??e.lineColor,f.commentStroke),commentTextColor:m(e.tertiaryTextColor??e.textColor,f.commentTextColor),specialFill:m(e.tertiaryColor??e.secondaryColor,f.specialFill),specialStroke:m(e.tertiaryBorderColor??e.secondaryBorderColor,f.specialStroke),ruleNameColor:m(e.titleColor??e.textColor,f.ruleNameColor)}},"buildThemeDefaults"),E=p(e=>{const i=B(),a={...G(),...i.themeVariables??{},...me(e)},n=pe(a),t={...i.railroad??{},...ce(e)};return{compactMode:t.compactMode??n.compactMode,padding:F(t.padding,n.padding),verticalSeparation:F(t.verticalSeparation,n.verticalSeparation),horizontalSeparation:F(t.horizontalSeparation,n.horizontalSeparation),arcRadius:F(t.arcRadius,n.arcRadius),fontSize:F(t.fontSize,n.fontSize),fontFamily:I(t.fontFamily,n.fontFamily),terminalFill:m(t.terminalFill,n.terminalFill),terminalStroke:m(t.terminalStroke,n.terminalStroke),terminalTextColor:m(t.terminalTextColor,n.terminalTextColor),nonTerminalFill:m(t.nonTerminalFill,n.nonTerminalFill),nonTerminalStroke:m(t.nonTerminalStroke,n.nonTerminalStroke),nonTerminalTextColor:m(t.nonTerminalTextColor,n.nonTerminalTextColor),lineColor:m(t.lineColor,n.lineColor),strokeWidth:F(t.strokeWidth,n.strokeWidth),markerFill:m(t.markerFill,n.markerFill),commentFill:m(t.commentFill,n.commentFill),commentStroke:m(t.commentStroke,n.commentStroke),commentTextColor:m(t.commentTextColor,n.commentTextColor),specialFill:m(t.specialFill,n.specialFill),specialStroke:m(t.specialStroke,n.specialStroke),ruleNameColor:m(t.ruleNameColor,n.ruleNameColor),showMarkers:t.showMarkers??n.showMarkers,markerRadius:F(t.markerRadius,n.markerRadius)}},"buildRailroadStyleOptions"),Te=p(e=>{const{fontFamily:i,fontSize:a,terminalFill:n,terminalStroke:t,terminalTextColor:r,nonTerminalFill:o,nonTerminalStroke:g,nonTerminalTextColor:l,lineColor:s,strokeWidth:h,markerFill:u,commentFill:c,commentStroke:w,commentTextColor:d,specialFill:T,specialStroke:z,ruleNameColor:S}=E(e);return` .railroad-diagram { font-family: ${i}; diff --git a/static/ml_canvas/assets/chunk-TICWLB2K-BxRYcV3C.js b/static/ml_canvas/assets/chunk-TICWLB2K-DjtJsWp0.js similarity index 99% rename from static/ml_canvas/assets/chunk-TICWLB2K-BxRYcV3C.js rename to static/ml_canvas/assets/chunk-TICWLB2K-DjtJsWp0.js index 6b6b746e8..a0b9a3c01 100644 --- a/static/ml_canvas/assets/chunk-TICWLB2K-BxRYcV3C.js +++ b/static/ml_canvas/assets/chunk-TICWLB2K-DjtJsWp0.js @@ -1,4 +1,4 @@ -import{g as st}from"./chunk-5VM5RSS4-W4WNe2RE.js";import{g as it}from"./chunk-XXDRQBXY-CZsBIZJg.js";import{s as at}from"./chunk-POPQ4Y6H-BOk39pqP.js";import{_ as g,l as we,c as F,t as rt,u as nt,v as Ve,O as ut,b as lt,a as ct,s as ot,g as ht,m as dt,n as pt,j as I,o as At,p as ft,i as gt,P as z}from"./mermaid.core-BCO0YdKy.js";import{f as mt}from"./chunk-F27PBJKO-Dm2Us476.js";import{s as fe}from"./vendor-flow-bDma3vSM.js";var Pe=(function(){var s=g(function(O,o,d,p){for(d=d||{},p=O.length;p--;d[O[p]]=o);return d},"o"),i=[1,18],a=[1,19],r=[1,20],n=[1,41],u=[1,26],h=[1,42],f=[1,24],c=[1,25],m=[1,32],B=[1,33],R=[1,34],b=[1,45],me=[1,35],Ce=[1,36],be=[1,37],ke=[1,38],Ee=[1,27],Te=[1,28],ye=[1,29],De=[1,30],Fe=[1,31],k=[1,44],E=[1,46],T=[1,43],y=[1,47],Be=[1,9],A=[1,8,9],te=[1,58],se=[1,59],ie=[1,60],ae=[1,61],re=[1,62],_e=[1,63],Se=[1,64],S=[1,8,9,41],Me=[1,77],G=[1,8,9,12,13,22,39,41,44,46,68,69,70,71,72,73,74,79,81],ne=[1,8,9,12,13,18,20,22,39,41,44,46,47,60,68,69,70,71,72,73,74,79,81,86,100,102,103],ue=[13,60,86,100,102,103],K=[13,60,73,74,86,100,102,103],Re=[13,60,68,69,70,71,72,86,100,102,103],le=[1,103],W=[1,121],Q=[1,117],j=[1,113],X=[1,119],q=[1,114],H=[1,115],J=[1,116],Z=[1,118],$=[1,120],Ge=[22,50,60,61,82,86,87,88,89,90],Ue=[1,128],ce=[12,39],Ne=[1,8,9,39,41,44,46],oe=[1,8,9,22],ze=[1,153],Ye=[1,8,9,61],x=[1,8,9,22,50,60,61,82,86,87,88,89,90],Le={trace:g(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,ANNOTATION_START:46,ANNOTATION_END:47,CLASS:48,emptyBody:49,SPACE:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:"error",7:"CLASS_DIAGRAM",8:"NEWLINE",9:"EOF",12:"SQS",13:"STR",14:"SQE",18:"DOT",20:"GENERICTYPE",22:"LABEL",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",39:"STRUCT_START",41:"STRUCT_STOP",42:"NAMESPACE",44:"STYLE_SEPARATOR",46:"ANNOTATION_START",47:"ANNOTATION_END",48:"CLASS",50:"SPACE",51:"MEMBER",52:"SEPARATOR",54:"NOTE_FOR",56:"NOTE",57:"CLASSDEF",60:"ALPHA",61:"COMMA",62:"direction_tb",63:"direction_bt",64:"direction_rl",65:"direction_lr",68:"AGGREGATION",69:"EXTENSION",70:"COMPOSITION",71:"DEPENDENCY",72:"LOLLIPOP",73:"LINE",74:"DOTTED_LINE",75:"CALLBACK",76:"LINK",77:"LINK_TARGET",78:"CLICK",79:"CALLBACK_NAME",80:"CALLBACK_ARGS",81:"HREF",82:"STYLE",83:"CSSCLASS",86:"NUM",87:"COLON",88:"UNIT",89:"BRKT",90:"PCT",93:"graphCodeTokens",95:"TAGSTART",96:"TAGEND",97:"==",98:"--",99:"DEFAULT",100:"MINUS",101:"keywords",102:"UNICODE_TEXT",103:"BQUOTE_STR"},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[38,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[24,4],[24,7],[24,6],[43,2],[43,3],[49,0],[49,2],[49,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:g(function(o,d,p,l,C,e,ee){var t=e.length-1;switch(C){case 8:this.$=e[t-1];break;case 9:case 10:case 13:case 15:this.$=e[t];break;case 11:case 14:this.$=e[t-2]+"."+e[t];break;case 12:case 16:this.$=e[t-1]+e[t];break;case 17:case 18:this.$=e[t-1]+"~"+e[t]+"~";break;case 19:l.addRelation(e[t]);break;case 20:e[t-1].title=l.cleanupLabel(e[t]),l.addRelation(e[t-1]);break;case 31:this.$=e[t].trim(),l.setAccTitle(this.$);break;case 32:case 33:this.$=e[t].trim(),l.setAccDescription(this.$);break;case 34:l.addClassesToNamespace(e[t-3],e[t-1][0],e[t-1][1]),l.popNamespace();break;case 35:l.addClassesToNamespace(e[t-4],e[t-1][0],e[t-1][1]),l.popNamespace();break;case 36:this.$=l.addNamespace(e[t]);break;case 37:this.$=l.addNamespace(e[t-1],e[t]);break;case 38:this.$=[[e[t]],[]];break;case 39:this.$=[[e[t-1]],[]];break;case 40:e[t][0].unshift(e[t-2]),this.$=e[t];break;case 41:this.$=[[],[e[t]]];break;case 42:this.$=[[],[e[t-1]]];break;case 43:e[t][1].unshift(e[t-2]),this.$=e[t];break;case 44:case 45:this.$=[[],[]];break;case 46:this.$=e[t];break;case 48:l.setCssClass(e[t-2],e[t]);break;case 49:l.addMembers(e[t-3],e[t-1]);break;case 51:l.setCssClass(e[t-5],e[t-3]),l.addMembers(e[t-5],e[t-1]);break;case 52:l.addAnnotation(e[t-3],e[t-1]);break;case 53:l.addAnnotation(e[t-6],e[t-4]),l.addMembers(e[t-6],e[t-1]);break;case 54:l.addAnnotation(e[t-5],e[t-3]);break;case 55:this.$=e[t],l.addClass(e[t]);break;case 56:this.$=e[t-1],l.addClass(e[t-1]),l.setClassLabel(e[t-1],e[t]);break;case 60:l.addAnnotation(e[t],e[t-2]);break;case 61:case 74:this.$=[e[t]];break;case 62:e[t].push(e[t-1]),this.$=e[t];break;case 63:break;case 64:l.addMember(e[t-1],l.cleanupLabel(e[t]));break;case 65:break;case 66:break;case 67:this.$={id1:e[t-2],id2:e[t],relation:e[t-1],relationTitle1:"none",relationTitle2:"none"};break;case 68:this.$={id1:e[t-3],id2:e[t],relation:e[t-1],relationTitle1:e[t-2],relationTitle2:"none"};break;case 69:this.$={id1:e[t-3],id2:e[t],relation:e[t-2],relationTitle1:"none",relationTitle2:e[t-1]};break;case 70:this.$={id1:e[t-4],id2:e[t],relation:e[t-2],relationTitle1:e[t-3],relationTitle2:e[t-1]};break;case 71:this.$=l.addNote(e[t],e[t-1]);break;case 72:this.$=l.addNote(e[t]);break;case 73:this.$=e[t-2],l.defineClass(e[t-1],e[t]);break;case 75:this.$=e[t-2].concat([e[t]]);break;case 76:l.setDirection("TB");break;case 77:l.setDirection("BT");break;case 78:l.setDirection("RL");break;case 79:l.setDirection("LR");break;case 80:this.$={type1:e[t-2],type2:e[t],lineType:e[t-1]};break;case 81:this.$={type1:"none",type2:e[t],lineType:e[t-1]};break;case 82:this.$={type1:e[t-1],type2:"none",lineType:e[t]};break;case 83:this.$={type1:"none",type2:"none",lineType:e[t]};break;case 84:this.$=l.relationType.AGGREGATION;break;case 85:this.$=l.relationType.EXTENSION;break;case 86:this.$=l.relationType.COMPOSITION;break;case 87:this.$=l.relationType.DEPENDENCY;break;case 88:this.$=l.relationType.LOLLIPOP;break;case 89:this.$=l.lineType.LINE;break;case 90:this.$=l.lineType.DOTTED_LINE;break;case 91:case 97:this.$=e[t-2],l.setClickEvent(e[t-1],e[t]);break;case 92:case 98:this.$=e[t-3],l.setClickEvent(e[t-2],e[t-1]),l.setTooltip(e[t-2],e[t]);break;case 93:this.$=e[t-2],l.setLink(e[t-1],e[t]);break;case 94:this.$=e[t-3],l.setLink(e[t-2],e[t-1],e[t]);break;case 95:this.$=e[t-3],l.setLink(e[t-2],e[t-1]),l.setTooltip(e[t-2],e[t]);break;case 96:this.$=e[t-4],l.setLink(e[t-3],e[t-2],e[t]),l.setTooltip(e[t-3],e[t-1]);break;case 99:this.$=e[t-3],l.setClickEvent(e[t-2],e[t-1],e[t]);break;case 100:this.$=e[t-4],l.setClickEvent(e[t-3],e[t-2],e[t-1]),l.setTooltip(e[t-3],e[t]);break;case 101:this.$=e[t-3],l.setLink(e[t-2],e[t]);break;case 102:this.$=e[t-4],l.setLink(e[t-3],e[t-1],e[t]);break;case 103:this.$=e[t-4],l.setLink(e[t-3],e[t-1]),l.setTooltip(e[t-3],e[t]);break;case 104:this.$=e[t-5],l.setLink(e[t-4],e[t-2],e[t]),l.setTooltip(e[t-4],e[t-1]);break;case 105:this.$=e[t-2],l.setCssStyle(e[t-1],e[t]);break;case 106:l.setCssClass(e[t-1],e[t]);break;case 107:this.$=[e[t]];break;case 108:e[t-2].push(e[t]),this.$=e[t-2];break;case 110:this.$=e[t-1]+e[t];break}},"anonymous"),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:i,35:a,37:r,38:22,42:n,43:23,46:u,48:h,51:f,52:c,54:m,56:B,57:R,60:b,62:me,63:Ce,64:be,65:ke,75:Ee,76:Te,78:ye,82:De,83:Fe,86:k,100:E,102:T,103:y},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},s(Be,[2,5],{8:[1,48]}),{8:[1,49]},s(A,[2,19],{22:[1,50]}),s(A,[2,21]),s(A,[2,22]),s(A,[2,23]),s(A,[2,24]),s(A,[2,25]),s(A,[2,26]),s(A,[2,27]),s(A,[2,28]),s(A,[2,29]),s(A,[2,30]),{34:[1,51]},{36:[1,52]},s(A,[2,33]),s(A,[2,63],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:te,69:se,70:ie,71:ae,72:re,73:_e,74:Se}),{39:[1,65]},s(S,[2,47],{39:[1,67],44:[1,66],46:[1,68]}),s(A,[2,65]),s(A,[2,66]),{16:69,60:b,86:k,100:E,102:T},{16:39,17:40,19:70,60:b,86:k,100:E,102:T,103:y},{16:39,17:40,19:71,60:b,86:k,100:E,102:T,103:y},{16:39,17:40,19:72,60:b,86:k,100:E,102:T,103:y},{60:[1,73]},{13:[1,74]},{16:39,17:40,19:75,60:b,86:k,100:E,102:T,103:y},{13:Me,55:76},{58:78,60:[1,79]},s(A,[2,76]),s(A,[2,77]),s(A,[2,78]),s(A,[2,79]),s(G,[2,13],{16:39,17:40,19:81,18:[1,80],20:[1,82],60:b,86:k,100:E,102:T,103:y}),s(G,[2,15],{20:[1,83]}),{15:84,16:85,17:86,60:b,86:k,100:E,102:T,103:y},{16:39,17:40,19:87,60:b,86:k,100:E,102:T,103:y},s(ne,[2,133]),s(ne,[2,134]),s(ne,[2,135]),s(ne,[2,136]),s([1,8,9,12,13,20,22,39,41,44,46,68,69,70,71,72,73,74,79,81],[2,137]),s(Be,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:88,33:i,35:a,37:r,42:n,46:u,48:h,51:f,52:c,54:m,56:B,57:R,60:b,62:me,63:Ce,64:be,65:ke,75:Ee,76:Te,78:ye,82:De,83:Fe,86:k,100:E,102:T,103:y}),{5:89,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:i,35:a,37:r,38:22,42:n,43:23,46:u,48:h,51:f,52:c,54:m,56:B,57:R,60:b,62:me,63:Ce,64:be,65:ke,75:Ee,76:Te,78:ye,82:De,83:Fe,86:k,100:E,102:T,103:y},s(A,[2,20]),s(A,[2,31]),s(A,[2,32]),{13:[1,91],16:39,17:40,19:90,60:b,86:k,100:E,102:T,103:y},{53:92,66:56,67:57,68:te,69:se,70:ie,71:ae,72:re,73:_e,74:Se},s(A,[2,64]),{67:93,73:_e,74:Se},s(ue,[2,83],{66:94,68:te,69:se,70:ie,71:ae,72:re}),s(K,[2,84]),s(K,[2,85]),s(K,[2,86]),s(K,[2,87]),s(K,[2,88]),s(Re,[2,89]),s(Re,[2,90]),{8:[1,96],23:99,24:97,30:98,38:22,40:95,42:n,43:23,48:h,54:m,56:B},{16:100,60:b,86:k,100:E,102:T},{41:[1,102],45:101,51:le},{16:104,60:b,86:k,100:E,102:T},{47:[1,105]},{13:[1,106]},{13:[1,107]},{79:[1,108],81:[1,109]},{22:W,50:Q,59:110,60:j,82:X,84:111,85:112,86:q,87:H,88:J,89:Z,90:$},{60:[1,122]},{13:Me,55:123},s(S,[2,72]),s(S,[2,138]),{22:W,50:Q,59:124,60:j,61:[1,125],82:X,84:111,85:112,86:q,87:H,88:J,89:Z,90:$},s(Ge,[2,74]),{16:39,17:40,19:126,60:b,86:k,100:E,102:T,103:y},s(G,[2,16]),s(G,[2,17]),s(G,[2,18]),{11:127,12:Ue,39:[2,36]},s(ce,[2,9],{16:85,17:86,15:130,18:[1,129],60:b,86:k,100:E,102:T,103:y}),s(ce,[2,10]),s(Ne,[2,55],{11:131,12:Ue}),s(Be,[2,7]),{9:[1,132]},s(oe,[2,67]),{16:39,17:40,19:133,60:b,86:k,100:E,102:T,103:y},{13:[1,135],16:39,17:40,19:134,60:b,86:k,100:E,102:T,103:y},s(ue,[2,82],{66:136,68:te,69:se,70:ie,71:ae,72:re}),s(ue,[2,81]),{41:[1,137]},{23:99,24:97,30:98,38:22,40:138,42:n,43:23,48:h,54:m,56:B},{8:[1,139],41:[2,38]},{8:[1,140],41:[2,41]},{8:[1,141],41:[2,44]},s(S,[2,48],{39:[1,142]}),{41:[1,143]},s(S,[2,50]),{41:[2,61],45:144,51:le},{47:[1,145]},{16:39,17:40,19:146,60:b,86:k,100:E,102:T,103:y},s(A,[2,91],{13:[1,147]}),s(A,[2,93],{13:[1,149],77:[1,148]}),s(A,[2,97],{13:[1,150],80:[1,151]}),{13:[1,152]},s(A,[2,105],{61:ze}),s(Ye,[2,107],{85:154,22:W,50:Q,60:j,82:X,86:q,87:H,88:J,89:Z,90:$}),s(x,[2,109]),s(x,[2,111]),s(x,[2,112]),s(x,[2,113]),s(x,[2,114]),s(x,[2,115]),s(x,[2,116]),s(x,[2,117]),s(x,[2,118]),s(x,[2,119]),s(A,[2,106]),s(S,[2,71]),s(A,[2,73],{61:ze}),{60:[1,155]},s(G,[2,14]),{39:[2,37]},{13:[1,156]},{15:157,16:85,17:86,60:b,86:k,100:E,102:T,103:y},s(ce,[2,12]),s(Ne,[2,56]),{1:[2,4]},s(oe,[2,69]),s(oe,[2,68]),{16:39,17:40,19:158,60:b,86:k,100:E,102:T,103:y},s(ue,[2,80]),s(S,[2,34]),{41:[1,159]},{23:99,24:97,30:98,38:22,40:160,41:[2,39],42:n,43:23,48:h,54:m,56:B},{23:99,24:97,30:98,38:22,40:161,41:[2,42],42:n,43:23,48:h,54:m,56:B},{23:99,24:97,30:98,38:22,40:162,41:[2,45],42:n,43:23,48:h,54:m,56:B},{45:163,51:le},s(S,[2,49]),{41:[2,62]},s(S,[2,52],{39:[1,164]}),s(A,[2,60]),s(A,[2,92]),s(A,[2,94]),s(A,[2,95],{77:[1,165]}),s(A,[2,98]),s(A,[2,99],{13:[1,166]}),s(A,[2,101],{13:[1,168],77:[1,167]}),{22:W,50:Q,60:j,82:X,84:169,85:112,86:q,87:H,88:J,89:Z,90:$},s(x,[2,110]),s(Ge,[2,75]),{14:[1,170]},s(ce,[2,11]),s(oe,[2,70]),s(S,[2,35]),{41:[2,40]},{41:[2,43]},{41:[2,46]},{41:[1,171]},{41:[1,173],45:172,51:le},s(A,[2,96]),s(A,[2,100]),s(A,[2,102]),s(A,[2,103],{77:[1,174]}),s(Ye,[2,108],{85:154,22:W,50:Q,60:j,82:X,86:q,87:H,88:J,89:Z,90:$}),s(Ne,[2,8]),s(S,[2,51]),{41:[1,175]},s(S,[2,54]),s(A,[2,104]),s(S,[2,53])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],127:[2,37],132:[2,4],144:[2,62],160:[2,40],161:[2,43],162:[2,46]},parseError:g(function(o,d){if(d.recoverable)this.trace(o);else{var p=new Error(o);throw p.hash=d,p}},"parseError"),parse:g(function(o){var d=this,p=[0],l=[],C=[null],e=[],ee=this.table,t="",de=0,Ke=0,Ze=2,We=1,$e=e.slice.call(arguments,1),D=Object.create(this.lexer),V={yy:{}};for(var xe in this.yy)Object.prototype.hasOwnProperty.call(this.yy,xe)&&(V.yy[xe]=this.yy[xe]);D.setInput(o,V.yy),V.yy.lexer=D,V.yy.parser=this,typeof D.yylloc>"u"&&(D.yylloc={});var ve=D.yylloc;e.push(ve);var et=D.options&&D.options.ranges;typeof V.yy.parseError=="function"?this.parseError=V.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function tt(N){p.length=p.length-2*N,C.length=C.length-N,e.length=e.length-N}g(tt,"popStack");function Qe(){var N;return N=l.pop()||D.lex()||We,typeof N!="number"&&(N instanceof Array&&(l=N,N=l.pop()),N=d.symbols_[N]||N),N}g(Qe,"lex");for(var _,P,L,Ie,U={},pe,v,je,Ae;;){if(P=p[p.length-1],this.defaultActions[P]?L=this.defaultActions[P]:((_===null||typeof _>"u")&&(_=Qe()),L=ee[P]&&ee[P][_]),typeof L>"u"||!L.length||!L[0]){var Oe="";Ae=[];for(pe in ee[P])this.terminals_[pe]&&pe>Ze&&Ae.push("'"+this.terminals_[pe]+"'");D.showPosition?Oe="Parse error on line "+(de+1)+`: +import{g as st}from"./chunk-5VM5RSS4-CKRC1CIZ.js";import{g as it}from"./chunk-XXDRQBXY-DdoFz10O.js";import{s as at}from"./chunk-POPQ4Y6H-BR_pO24v.js";import{_ as g,l as we,c as F,t as rt,u as nt,v as Ve,O as ut,b as lt,a as ct,s as ot,g as ht,m as dt,n as pt,j as I,o as At,p as ft,i as gt,P as z}from"./mermaid.core-BRmiRRt4.js";import{f as mt}from"./chunk-F27PBJKO-B7fm5O2R.js";import{s as fe}from"./vendor-flow-bDma3vSM.js";var Pe=(function(){var s=g(function(O,o,d,p){for(d=d||{},p=O.length;p--;d[O[p]]=o);return d},"o"),i=[1,18],a=[1,19],r=[1,20],n=[1,41],u=[1,26],h=[1,42],f=[1,24],c=[1,25],m=[1,32],B=[1,33],R=[1,34],b=[1,45],me=[1,35],Ce=[1,36],be=[1,37],ke=[1,38],Ee=[1,27],Te=[1,28],ye=[1,29],De=[1,30],Fe=[1,31],k=[1,44],E=[1,46],T=[1,43],y=[1,47],Be=[1,9],A=[1,8,9],te=[1,58],se=[1,59],ie=[1,60],ae=[1,61],re=[1,62],_e=[1,63],Se=[1,64],S=[1,8,9,41],Me=[1,77],G=[1,8,9,12,13,22,39,41,44,46,68,69,70,71,72,73,74,79,81],ne=[1,8,9,12,13,18,20,22,39,41,44,46,47,60,68,69,70,71,72,73,74,79,81,86,100,102,103],ue=[13,60,86,100,102,103],K=[13,60,73,74,86,100,102,103],Re=[13,60,68,69,70,71,72,86,100,102,103],le=[1,103],W=[1,121],Q=[1,117],j=[1,113],X=[1,119],q=[1,114],H=[1,115],J=[1,116],Z=[1,118],$=[1,120],Ge=[22,50,60,61,82,86,87,88,89,90],Ue=[1,128],ce=[12,39],Ne=[1,8,9,39,41,44,46],oe=[1,8,9,22],ze=[1,153],Ye=[1,8,9,61],x=[1,8,9,22,50,60,61,82,86,87,88,89,90],Le={trace:g(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,ANNOTATION_START:46,ANNOTATION_END:47,CLASS:48,emptyBody:49,SPACE:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:"error",7:"CLASS_DIAGRAM",8:"NEWLINE",9:"EOF",12:"SQS",13:"STR",14:"SQE",18:"DOT",20:"GENERICTYPE",22:"LABEL",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",39:"STRUCT_START",41:"STRUCT_STOP",42:"NAMESPACE",44:"STYLE_SEPARATOR",46:"ANNOTATION_START",47:"ANNOTATION_END",48:"CLASS",50:"SPACE",51:"MEMBER",52:"SEPARATOR",54:"NOTE_FOR",56:"NOTE",57:"CLASSDEF",60:"ALPHA",61:"COMMA",62:"direction_tb",63:"direction_bt",64:"direction_rl",65:"direction_lr",68:"AGGREGATION",69:"EXTENSION",70:"COMPOSITION",71:"DEPENDENCY",72:"LOLLIPOP",73:"LINE",74:"DOTTED_LINE",75:"CALLBACK",76:"LINK",77:"LINK_TARGET",78:"CLICK",79:"CALLBACK_NAME",80:"CALLBACK_ARGS",81:"HREF",82:"STYLE",83:"CSSCLASS",86:"NUM",87:"COLON",88:"UNIT",89:"BRKT",90:"PCT",93:"graphCodeTokens",95:"TAGSTART",96:"TAGEND",97:"==",98:"--",99:"DEFAULT",100:"MINUS",101:"keywords",102:"UNICODE_TEXT",103:"BQUOTE_STR"},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[38,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[24,4],[24,7],[24,6],[43,2],[43,3],[49,0],[49,2],[49,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:g(function(o,d,p,l,C,e,ee){var t=e.length-1;switch(C){case 8:this.$=e[t-1];break;case 9:case 10:case 13:case 15:this.$=e[t];break;case 11:case 14:this.$=e[t-2]+"."+e[t];break;case 12:case 16:this.$=e[t-1]+e[t];break;case 17:case 18:this.$=e[t-1]+"~"+e[t]+"~";break;case 19:l.addRelation(e[t]);break;case 20:e[t-1].title=l.cleanupLabel(e[t]),l.addRelation(e[t-1]);break;case 31:this.$=e[t].trim(),l.setAccTitle(this.$);break;case 32:case 33:this.$=e[t].trim(),l.setAccDescription(this.$);break;case 34:l.addClassesToNamespace(e[t-3],e[t-1][0],e[t-1][1]),l.popNamespace();break;case 35:l.addClassesToNamespace(e[t-4],e[t-1][0],e[t-1][1]),l.popNamespace();break;case 36:this.$=l.addNamespace(e[t]);break;case 37:this.$=l.addNamespace(e[t-1],e[t]);break;case 38:this.$=[[e[t]],[]];break;case 39:this.$=[[e[t-1]],[]];break;case 40:e[t][0].unshift(e[t-2]),this.$=e[t];break;case 41:this.$=[[],[e[t]]];break;case 42:this.$=[[],[e[t-1]]];break;case 43:e[t][1].unshift(e[t-2]),this.$=e[t];break;case 44:case 45:this.$=[[],[]];break;case 46:this.$=e[t];break;case 48:l.setCssClass(e[t-2],e[t]);break;case 49:l.addMembers(e[t-3],e[t-1]);break;case 51:l.setCssClass(e[t-5],e[t-3]),l.addMembers(e[t-5],e[t-1]);break;case 52:l.addAnnotation(e[t-3],e[t-1]);break;case 53:l.addAnnotation(e[t-6],e[t-4]),l.addMembers(e[t-6],e[t-1]);break;case 54:l.addAnnotation(e[t-5],e[t-3]);break;case 55:this.$=e[t],l.addClass(e[t]);break;case 56:this.$=e[t-1],l.addClass(e[t-1]),l.setClassLabel(e[t-1],e[t]);break;case 60:l.addAnnotation(e[t],e[t-2]);break;case 61:case 74:this.$=[e[t]];break;case 62:e[t].push(e[t-1]),this.$=e[t];break;case 63:break;case 64:l.addMember(e[t-1],l.cleanupLabel(e[t]));break;case 65:break;case 66:break;case 67:this.$={id1:e[t-2],id2:e[t],relation:e[t-1],relationTitle1:"none",relationTitle2:"none"};break;case 68:this.$={id1:e[t-3],id2:e[t],relation:e[t-1],relationTitle1:e[t-2],relationTitle2:"none"};break;case 69:this.$={id1:e[t-3],id2:e[t],relation:e[t-2],relationTitle1:"none",relationTitle2:e[t-1]};break;case 70:this.$={id1:e[t-4],id2:e[t],relation:e[t-2],relationTitle1:e[t-3],relationTitle2:e[t-1]};break;case 71:this.$=l.addNote(e[t],e[t-1]);break;case 72:this.$=l.addNote(e[t]);break;case 73:this.$=e[t-2],l.defineClass(e[t-1],e[t]);break;case 75:this.$=e[t-2].concat([e[t]]);break;case 76:l.setDirection("TB");break;case 77:l.setDirection("BT");break;case 78:l.setDirection("RL");break;case 79:l.setDirection("LR");break;case 80:this.$={type1:e[t-2],type2:e[t],lineType:e[t-1]};break;case 81:this.$={type1:"none",type2:e[t],lineType:e[t-1]};break;case 82:this.$={type1:e[t-1],type2:"none",lineType:e[t]};break;case 83:this.$={type1:"none",type2:"none",lineType:e[t]};break;case 84:this.$=l.relationType.AGGREGATION;break;case 85:this.$=l.relationType.EXTENSION;break;case 86:this.$=l.relationType.COMPOSITION;break;case 87:this.$=l.relationType.DEPENDENCY;break;case 88:this.$=l.relationType.LOLLIPOP;break;case 89:this.$=l.lineType.LINE;break;case 90:this.$=l.lineType.DOTTED_LINE;break;case 91:case 97:this.$=e[t-2],l.setClickEvent(e[t-1],e[t]);break;case 92:case 98:this.$=e[t-3],l.setClickEvent(e[t-2],e[t-1]),l.setTooltip(e[t-2],e[t]);break;case 93:this.$=e[t-2],l.setLink(e[t-1],e[t]);break;case 94:this.$=e[t-3],l.setLink(e[t-2],e[t-1],e[t]);break;case 95:this.$=e[t-3],l.setLink(e[t-2],e[t-1]),l.setTooltip(e[t-2],e[t]);break;case 96:this.$=e[t-4],l.setLink(e[t-3],e[t-2],e[t]),l.setTooltip(e[t-3],e[t-1]);break;case 99:this.$=e[t-3],l.setClickEvent(e[t-2],e[t-1],e[t]);break;case 100:this.$=e[t-4],l.setClickEvent(e[t-3],e[t-2],e[t-1]),l.setTooltip(e[t-3],e[t]);break;case 101:this.$=e[t-3],l.setLink(e[t-2],e[t]);break;case 102:this.$=e[t-4],l.setLink(e[t-3],e[t-1],e[t]);break;case 103:this.$=e[t-4],l.setLink(e[t-3],e[t-1]),l.setTooltip(e[t-3],e[t]);break;case 104:this.$=e[t-5],l.setLink(e[t-4],e[t-2],e[t]),l.setTooltip(e[t-4],e[t-1]);break;case 105:this.$=e[t-2],l.setCssStyle(e[t-1],e[t]);break;case 106:l.setCssClass(e[t-1],e[t]);break;case 107:this.$=[e[t]];break;case 108:e[t-2].push(e[t]),this.$=e[t-2];break;case 110:this.$=e[t-1]+e[t];break}},"anonymous"),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:i,35:a,37:r,38:22,42:n,43:23,46:u,48:h,51:f,52:c,54:m,56:B,57:R,60:b,62:me,63:Ce,64:be,65:ke,75:Ee,76:Te,78:ye,82:De,83:Fe,86:k,100:E,102:T,103:y},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},s(Be,[2,5],{8:[1,48]}),{8:[1,49]},s(A,[2,19],{22:[1,50]}),s(A,[2,21]),s(A,[2,22]),s(A,[2,23]),s(A,[2,24]),s(A,[2,25]),s(A,[2,26]),s(A,[2,27]),s(A,[2,28]),s(A,[2,29]),s(A,[2,30]),{34:[1,51]},{36:[1,52]},s(A,[2,33]),s(A,[2,63],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:te,69:se,70:ie,71:ae,72:re,73:_e,74:Se}),{39:[1,65]},s(S,[2,47],{39:[1,67],44:[1,66],46:[1,68]}),s(A,[2,65]),s(A,[2,66]),{16:69,60:b,86:k,100:E,102:T},{16:39,17:40,19:70,60:b,86:k,100:E,102:T,103:y},{16:39,17:40,19:71,60:b,86:k,100:E,102:T,103:y},{16:39,17:40,19:72,60:b,86:k,100:E,102:T,103:y},{60:[1,73]},{13:[1,74]},{16:39,17:40,19:75,60:b,86:k,100:E,102:T,103:y},{13:Me,55:76},{58:78,60:[1,79]},s(A,[2,76]),s(A,[2,77]),s(A,[2,78]),s(A,[2,79]),s(G,[2,13],{16:39,17:40,19:81,18:[1,80],20:[1,82],60:b,86:k,100:E,102:T,103:y}),s(G,[2,15],{20:[1,83]}),{15:84,16:85,17:86,60:b,86:k,100:E,102:T,103:y},{16:39,17:40,19:87,60:b,86:k,100:E,102:T,103:y},s(ne,[2,133]),s(ne,[2,134]),s(ne,[2,135]),s(ne,[2,136]),s([1,8,9,12,13,20,22,39,41,44,46,68,69,70,71,72,73,74,79,81],[2,137]),s(Be,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:88,33:i,35:a,37:r,42:n,46:u,48:h,51:f,52:c,54:m,56:B,57:R,60:b,62:me,63:Ce,64:be,65:ke,75:Ee,76:Te,78:ye,82:De,83:Fe,86:k,100:E,102:T,103:y}),{5:89,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:i,35:a,37:r,38:22,42:n,43:23,46:u,48:h,51:f,52:c,54:m,56:B,57:R,60:b,62:me,63:Ce,64:be,65:ke,75:Ee,76:Te,78:ye,82:De,83:Fe,86:k,100:E,102:T,103:y},s(A,[2,20]),s(A,[2,31]),s(A,[2,32]),{13:[1,91],16:39,17:40,19:90,60:b,86:k,100:E,102:T,103:y},{53:92,66:56,67:57,68:te,69:se,70:ie,71:ae,72:re,73:_e,74:Se},s(A,[2,64]),{67:93,73:_e,74:Se},s(ue,[2,83],{66:94,68:te,69:se,70:ie,71:ae,72:re}),s(K,[2,84]),s(K,[2,85]),s(K,[2,86]),s(K,[2,87]),s(K,[2,88]),s(Re,[2,89]),s(Re,[2,90]),{8:[1,96],23:99,24:97,30:98,38:22,40:95,42:n,43:23,48:h,54:m,56:B},{16:100,60:b,86:k,100:E,102:T},{41:[1,102],45:101,51:le},{16:104,60:b,86:k,100:E,102:T},{47:[1,105]},{13:[1,106]},{13:[1,107]},{79:[1,108],81:[1,109]},{22:W,50:Q,59:110,60:j,82:X,84:111,85:112,86:q,87:H,88:J,89:Z,90:$},{60:[1,122]},{13:Me,55:123},s(S,[2,72]),s(S,[2,138]),{22:W,50:Q,59:124,60:j,61:[1,125],82:X,84:111,85:112,86:q,87:H,88:J,89:Z,90:$},s(Ge,[2,74]),{16:39,17:40,19:126,60:b,86:k,100:E,102:T,103:y},s(G,[2,16]),s(G,[2,17]),s(G,[2,18]),{11:127,12:Ue,39:[2,36]},s(ce,[2,9],{16:85,17:86,15:130,18:[1,129],60:b,86:k,100:E,102:T,103:y}),s(ce,[2,10]),s(Ne,[2,55],{11:131,12:Ue}),s(Be,[2,7]),{9:[1,132]},s(oe,[2,67]),{16:39,17:40,19:133,60:b,86:k,100:E,102:T,103:y},{13:[1,135],16:39,17:40,19:134,60:b,86:k,100:E,102:T,103:y},s(ue,[2,82],{66:136,68:te,69:se,70:ie,71:ae,72:re}),s(ue,[2,81]),{41:[1,137]},{23:99,24:97,30:98,38:22,40:138,42:n,43:23,48:h,54:m,56:B},{8:[1,139],41:[2,38]},{8:[1,140],41:[2,41]},{8:[1,141],41:[2,44]},s(S,[2,48],{39:[1,142]}),{41:[1,143]},s(S,[2,50]),{41:[2,61],45:144,51:le},{47:[1,145]},{16:39,17:40,19:146,60:b,86:k,100:E,102:T,103:y},s(A,[2,91],{13:[1,147]}),s(A,[2,93],{13:[1,149],77:[1,148]}),s(A,[2,97],{13:[1,150],80:[1,151]}),{13:[1,152]},s(A,[2,105],{61:ze}),s(Ye,[2,107],{85:154,22:W,50:Q,60:j,82:X,86:q,87:H,88:J,89:Z,90:$}),s(x,[2,109]),s(x,[2,111]),s(x,[2,112]),s(x,[2,113]),s(x,[2,114]),s(x,[2,115]),s(x,[2,116]),s(x,[2,117]),s(x,[2,118]),s(x,[2,119]),s(A,[2,106]),s(S,[2,71]),s(A,[2,73],{61:ze}),{60:[1,155]},s(G,[2,14]),{39:[2,37]},{13:[1,156]},{15:157,16:85,17:86,60:b,86:k,100:E,102:T,103:y},s(ce,[2,12]),s(Ne,[2,56]),{1:[2,4]},s(oe,[2,69]),s(oe,[2,68]),{16:39,17:40,19:158,60:b,86:k,100:E,102:T,103:y},s(ue,[2,80]),s(S,[2,34]),{41:[1,159]},{23:99,24:97,30:98,38:22,40:160,41:[2,39],42:n,43:23,48:h,54:m,56:B},{23:99,24:97,30:98,38:22,40:161,41:[2,42],42:n,43:23,48:h,54:m,56:B},{23:99,24:97,30:98,38:22,40:162,41:[2,45],42:n,43:23,48:h,54:m,56:B},{45:163,51:le},s(S,[2,49]),{41:[2,62]},s(S,[2,52],{39:[1,164]}),s(A,[2,60]),s(A,[2,92]),s(A,[2,94]),s(A,[2,95],{77:[1,165]}),s(A,[2,98]),s(A,[2,99],{13:[1,166]}),s(A,[2,101],{13:[1,168],77:[1,167]}),{22:W,50:Q,60:j,82:X,84:169,85:112,86:q,87:H,88:J,89:Z,90:$},s(x,[2,110]),s(Ge,[2,75]),{14:[1,170]},s(ce,[2,11]),s(oe,[2,70]),s(S,[2,35]),{41:[2,40]},{41:[2,43]},{41:[2,46]},{41:[1,171]},{41:[1,173],45:172,51:le},s(A,[2,96]),s(A,[2,100]),s(A,[2,102]),s(A,[2,103],{77:[1,174]}),s(Ye,[2,108],{85:154,22:W,50:Q,60:j,82:X,86:q,87:H,88:J,89:Z,90:$}),s(Ne,[2,8]),s(S,[2,51]),{41:[1,175]},s(S,[2,54]),s(A,[2,104]),s(S,[2,53])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],127:[2,37],132:[2,4],144:[2,62],160:[2,40],161:[2,43],162:[2,46]},parseError:g(function(o,d){if(d.recoverable)this.trace(o);else{var p=new Error(o);throw p.hash=d,p}},"parseError"),parse:g(function(o){var d=this,p=[0],l=[],C=[null],e=[],ee=this.table,t="",de=0,Ke=0,Ze=2,We=1,$e=e.slice.call(arguments,1),D=Object.create(this.lexer),V={yy:{}};for(var xe in this.yy)Object.prototype.hasOwnProperty.call(this.yy,xe)&&(V.yy[xe]=this.yy[xe]);D.setInput(o,V.yy),V.yy.lexer=D,V.yy.parser=this,typeof D.yylloc>"u"&&(D.yylloc={});var ve=D.yylloc;e.push(ve);var et=D.options&&D.options.ranges;typeof V.yy.parseError=="function"?this.parseError=V.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function tt(N){p.length=p.length-2*N,C.length=C.length-N,e.length=e.length-N}g(tt,"popStack");function Qe(){var N;return N=l.pop()||D.lex()||We,typeof N!="number"&&(N instanceof Array&&(l=N,N=l.pop()),N=d.symbols_[N]||N),N}g(Qe,"lex");for(var _,P,L,Ie,U={},pe,v,je,Ae;;){if(P=p[p.length-1],this.defaultActions[P]?L=this.defaultActions[P]:((_===null||typeof _>"u")&&(_=Qe()),L=ee[P]&&ee[P][_]),typeof L>"u"||!L.length||!L[0]){var Oe="";Ae=[];for(pe in ee[P])this.terminals_[pe]&&pe>Ze&&Ae.push("'"+this.terminals_[pe]+"'");D.showPosition?Oe="Parse error on line "+(de+1)+`: `+D.showPosition()+` Expecting `+Ae.join(", ")+", got '"+(this.terminals_[_]||_)+"'":Oe="Parse error on line "+(de+1)+": Unexpected "+(_==We?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(Oe,{text:D.match,token:this.terminals_[_]||_,line:D.yylineno,loc:ve,expected:Ae})}if(L[0]instanceof Array&&L.length>1)throw new Error("Parse Error: multiple actions possible at state: "+P+", token: "+_);switch(L[0]){case 1:p.push(_),C.push(D.yytext),e.push(D.yylloc),p.push(L[1]),_=null,Ke=D.yyleng,t=D.yytext,de=D.yylineno,ve=D.yylloc;break;case 2:if(v=this.productions_[L[1]][1],U.$=C[C.length-v],U._$={first_line:e[e.length-(v||1)].first_line,last_line:e[e.length-1].last_line,first_column:e[e.length-(v||1)].first_column,last_column:e[e.length-1].last_column},et&&(U._$.range=[e[e.length-(v||1)].range[0],e[e.length-1].range[1]]),Ie=this.performAction.apply(U,[t,Ke,de,V.yy,L[1],C,e].concat($e)),typeof Ie<"u")return Ie;v&&(p=p.slice(0,-1*v*2),C=C.slice(0,-1*v),e=e.slice(0,-1*v)),p.push(this.productions_[L[1]][0]),C.push(U.$),e.push(U._$),je=ee[p[p.length-2]][p[p.length-1]],p.push(je);break;case 3:return!0}}return!0},"parse")},Je=(function(){var O={EOF:1,parseError:g(function(d,p){if(this.yy.parser)this.yy.parser.parseError(d,p);else throw new Error(d)},"parseError"),setInput:g(function(o,d){return this.yy=d||this.yy||{},this._input=o,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:g(function(){var o=this._input[0];this.yytext+=o,this.yyleng++,this.offset++,this.match+=o,this.matched+=o;var d=o.match(/(?:\r\n?|\n).*/g);return d?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),o},"input"),unput:g(function(o){var d=o.length,p=o.split(/(?:\r\n?|\n)/g);this._input=o+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-d),this.offset-=d;var l=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),p.length-1&&(this.yylineno-=p.length-1);var C=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:p?(p.length===l.length?this.yylloc.first_column:0)+l[l.length-p.length].length-p[0].length:this.yylloc.first_column-d},this.options.ranges&&(this.yylloc.range=[C[0],C[0]+this.yyleng-d]),this.yyleng=this.yytext.length,this},"unput"),more:g(function(){return this._more=!0,this},"more"),reject:g(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:g(function(o){this.unput(this.match.slice(o))},"less"),pastInput:g(function(){var o=this.matched.substr(0,this.matched.length-this.match.length);return(o.length>20?"...":"")+o.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:g(function(){var o=this.match;return o.length<20&&(o+=this._input.substr(0,20-o.length)),(o.substr(0,20)+(o.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:g(function(){var o=this.pastInput(),d=new Array(o.length+1).join("-");return o+this.upcomingInput()+` diff --git a/static/ml_canvas/assets/chunk-XXDRQBXY-CZsBIZJg.js b/static/ml_canvas/assets/chunk-XXDRQBXY-DdoFz10O.js similarity index 76% rename from static/ml_canvas/assets/chunk-XXDRQBXY-CZsBIZJg.js rename to static/ml_canvas/assets/chunk-XXDRQBXY-DdoFz10O.js index 477c5cb5f..edce76f81 100644 --- a/static/ml_canvas/assets/chunk-XXDRQBXY-CZsBIZJg.js +++ b/static/ml_canvas/assets/chunk-XXDRQBXY-DdoFz10O.js @@ -1 +1 @@ -import{_ as s}from"./mermaid.core-BCO0YdKy.js";import{s as o}from"./vendor-flow-bDma3vSM.js";var d=s((t,e)=>{let n;return e==="sandbox"&&(n=o("#i"+t)),(e==="sandbox"?o(n.nodes()[0].contentDocument.body):o("body")).select(`[id="${t}"]`)},"getDiagramElement");export{d as g}; +import{_ as s}from"./mermaid.core-BRmiRRt4.js";import{s as o}from"./vendor-flow-bDma3vSM.js";var d=s((t,e)=>{let n;return e==="sandbox"&&(n=o("#i"+t)),(e==="sandbox"?o(n.nodes()[0].contentDocument.body):o("body")).select(`[id="${t}"]`)},"getDiagramElement");export{d as g}; diff --git a/static/ml_canvas/assets/classDiagram-ZZMXUADV-CFWCbgE-.js b/static/ml_canvas/assets/classDiagram-ZZMXUADV-CFWCbgE-.js deleted file mode 100644 index ef4eca905..000000000 --- a/static/ml_canvas/assets/classDiagram-ZZMXUADV-CFWCbgE-.js +++ /dev/null @@ -1 +0,0 @@ -import{s as a,c as s,a as e,C as t}from"./chunk-TICWLB2K-BxRYcV3C.js";import{_ as i}from"./mermaid.core-BCO0YdKy.js";import"./vendor-flow-bDma3vSM.js";import"./chunk-5VM5RSS4-W4WNe2RE.js";import"./chunk-XXDRQBXY-CZsBIZJg.js";import"./chunk-POPQ4Y6H-BOk39pqP.js";import"./chunk-F27PBJKO-Dm2Us476.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var c={parser:e,get db(){return new t},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{c as diagram}; diff --git a/static/ml_canvas/assets/classDiagram-ZZMXUADV-H8j0jcWO.js b/static/ml_canvas/assets/classDiagram-ZZMXUADV-H8j0jcWO.js new file mode 100644 index 000000000..c014eab81 --- /dev/null +++ b/static/ml_canvas/assets/classDiagram-ZZMXUADV-H8j0jcWO.js @@ -0,0 +1 @@ +import{s as a,c as s,a as e,C as t}from"./chunk-TICWLB2K-DjtJsWp0.js";import{_ as i}from"./mermaid.core-BRmiRRt4.js";import"./vendor-flow-bDma3vSM.js";import"./chunk-5VM5RSS4-CKRC1CIZ.js";import"./chunk-XXDRQBXY-DdoFz10O.js";import"./chunk-POPQ4Y6H-BR_pO24v.js";import"./chunk-F27PBJKO-B7fm5O2R.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var c={parser:e,get db(){return new t},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{c as diagram}; diff --git a/static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-CFWCbgE-.js b/static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-CFWCbgE-.js deleted file mode 100644 index ef4eca905..000000000 --- a/static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-CFWCbgE-.js +++ /dev/null @@ -1 +0,0 @@ -import{s as a,c as s,a as e,C as t}from"./chunk-TICWLB2K-BxRYcV3C.js";import{_ as i}from"./mermaid.core-BCO0YdKy.js";import"./vendor-flow-bDma3vSM.js";import"./chunk-5VM5RSS4-W4WNe2RE.js";import"./chunk-XXDRQBXY-CZsBIZJg.js";import"./chunk-POPQ4Y6H-BOk39pqP.js";import"./chunk-F27PBJKO-Dm2Us476.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var c={parser:e,get db(){return new t},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{c as diagram}; diff --git a/static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-H8j0jcWO.js b/static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-H8j0jcWO.js new file mode 100644 index 000000000..c014eab81 --- /dev/null +++ b/static/ml_canvas/assets/classDiagram-v2-VYDZK3BY-H8j0jcWO.js @@ -0,0 +1 @@ +import{s as a,c as s,a as e,C as t}from"./chunk-TICWLB2K-DjtJsWp0.js";import{_ as i}from"./mermaid.core-BRmiRRt4.js";import"./vendor-flow-bDma3vSM.js";import"./chunk-5VM5RSS4-CKRC1CIZ.js";import"./chunk-XXDRQBXY-DdoFz10O.js";import"./chunk-POPQ4Y6H-BR_pO24v.js";import"./chunk-F27PBJKO-B7fm5O2R.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var c={parser:e,get db(){return new t},renderer:s,styles:a,init:i(r=>{r.class||(r.class={}),r.class.arrowMarkerAbsolute=r.arrowMarkerAbsolute},"init")};export{c as diagram}; diff --git a/static/ml_canvas/assets/cose-bilkent-JH36ORCC-CDsnQ2ME.js b/static/ml_canvas/assets/cose-bilkent-JH36ORCC-Bxg7khAP.js similarity index 99% rename from static/ml_canvas/assets/cose-bilkent-JH36ORCC-CDsnQ2ME.js rename to static/ml_canvas/assets/cose-bilkent-JH36ORCC-Bxg7khAP.js index c833f7fdf..2648ff768 100644 --- a/static/ml_canvas/assets/cose-bilkent-JH36ORCC-CDsnQ2ME.js +++ b/static/ml_canvas/assets/cose-bilkent-JH36ORCC-Bxg7khAP.js @@ -1 +1 @@ -import{_ as V,l as k}from"./mermaid.core-BCO0YdKy.js";import{c as tt}from"./cytoscape.esm-Bch-eiPH.js";import{g as lt}from"./vendor-utils-_6D5wMFs.js";import{s as gt}from"./vendor-flow-bDma3vSM.js";import"./index-BXksgzya.js";import"./vendor-charts-CwfdE1jD.js";var Z={exports:{}},$={exports:{}},Q={exports:{}},ut=Q.exports,j;function ft(){return j||(j=1,(function(G,b){(function(I,T){G.exports=T()})(ut,function(){return(function(N){var I={};function T(o){if(I[o])return I[o].exports;var e=I[o]={i:o,l:!1,exports:{}};return N[o].call(e.exports,e,e.exports,T),e.l=!0,e.exports}return T.m=N,T.c=I,T.i=function(o){return o},T.d=function(o,e,t){T.o(o,e)||Object.defineProperty(o,e,{configurable:!1,enumerable:!0,get:t})},T.n=function(o){var e=o&&o.__esModule?function(){return o.default}:function(){return o};return T.d(e,"a",e),e},T.o=function(o,e){return Object.prototype.hasOwnProperty.call(o,e)},T.p="",T(T.s=26)})([(function(N,I,T){function o(){}o.QUALITY=1,o.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,o.DEFAULT_INCREMENTAL=!1,o.DEFAULT_ANIMATION_ON_LAYOUT=!0,o.DEFAULT_ANIMATION_DURING_LAYOUT=!1,o.DEFAULT_ANIMATION_PERIOD=50,o.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,o.DEFAULT_GRAPH_MARGIN=15,o.NODE_DIMENSIONS_INCLUDE_LABELS=!1,o.SIMPLE_NODE_SIZE=40,o.SIMPLE_NODE_HALF_SIZE=o.SIMPLE_NODE_SIZE/2,o.EMPTY_COMPOUND_NODE_SIZE=40,o.MIN_EDGE_LENGTH=1,o.WORLD_BOUNDARY=1e6,o.INITIAL_WORLD_BOUNDARY=o.WORLD_BOUNDARY/1e3,o.WORLD_CENTER_X=1200,o.WORLD_CENTER_Y=900,N.exports=o}),(function(N,I,T){var o=T(2),e=T(8),t=T(9);function i(g,n,d){o.call(this,d),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=d,this.bendpoints=[],this.source=g,this.target=n}i.prototype=Object.create(o.prototype);for(var l in o)i[l]=o[l];i.prototype.getSource=function(){return this.source},i.prototype.getTarget=function(){return this.target},i.prototype.isInterGraph=function(){return this.isInterGraph},i.prototype.getLength=function(){return this.length},i.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},i.prototype.getBendpoints=function(){return this.bendpoints},i.prototype.getLca=function(){return this.lca},i.prototype.getSourceInLca=function(){return this.sourceInLca},i.prototype.getTargetInLca=function(){return this.targetInLca},i.prototype.getOtherEnd=function(g){if(this.source===g)return this.target;if(this.target===g)return this.source;throw"Node is not incident with this edge"},i.prototype.getOtherEndInGraph=function(g,n){for(var d=this.getOtherEnd(g),r=n.getGraphManager().getRoot();;){if(d.getOwner()==n)return d;if(d.getOwner()==r)break;d=d.getOwner().getParent()}return null},i.prototype.updateLength=function(){var g=new Array(4);this.isOverlapingSourceAndTarget=e.getIntersection(this.target.getRect(),this.source.getRect(),g),this.isOverlapingSourceAndTarget||(this.lengthX=g[0]-g[2],this.lengthY=g[1]-g[3],Math.abs(this.lengthX)<1&&(this.lengthX=t.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=t.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},i.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=t.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=t.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},N.exports=i}),(function(N,I,T){function o(e){this.vGraphObject=e}N.exports=o}),(function(N,I,T){var o=T(2),e=T(10),t=T(13),i=T(0),l=T(16),g=T(4);function n(r,h,a,p){a==null&&p==null&&(p=h),o.call(this,p),r.graphManager!=null&&(r=r.graphManager),this.estimatedSize=e.MIN_VALUE,this.inclusionTreeDepth=e.MAX_VALUE,this.vGraphObject=p,this.edges=[],this.graphManager=r,a!=null&&h!=null?this.rect=new t(h.x,h.y,a.width,a.height):this.rect=new t}n.prototype=Object.create(o.prototype);for(var d in o)n[d]=o[d];n.prototype.getEdges=function(){return this.edges},n.prototype.getChild=function(){return this.child},n.prototype.getOwner=function(){return this.owner},n.prototype.getWidth=function(){return this.rect.width},n.prototype.setWidth=function(r){this.rect.width=r},n.prototype.getHeight=function(){return this.rect.height},n.prototype.setHeight=function(r){this.rect.height=r},n.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},n.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},n.prototype.getCenter=function(){return new g(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},n.prototype.getLocation=function(){return new g(this.rect.x,this.rect.y)},n.prototype.getRect=function(){return this.rect},n.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},n.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},n.prototype.setRect=function(r,h){this.rect.x=r.x,this.rect.y=r.y,this.rect.width=h.width,this.rect.height=h.height},n.prototype.setCenter=function(r,h){this.rect.x=r-this.rect.width/2,this.rect.y=h-this.rect.height/2},n.prototype.setLocation=function(r,h){this.rect.x=r,this.rect.y=h},n.prototype.moveBy=function(r,h){this.rect.x+=r,this.rect.y+=h},n.prototype.getEdgeListToNode=function(r){var h=[],a=this;return a.edges.forEach(function(p){if(p.target==r){if(p.source!=a)throw"Incorrect edge source!";h.push(p)}}),h},n.prototype.getEdgesBetween=function(r){var h=[],a=this;return a.edges.forEach(function(p){if(!(p.source==a||p.target==a))throw"Incorrect edge source and/or target";(p.target==r||p.source==r)&&h.push(p)}),h},n.prototype.getNeighborsList=function(){var r=new Set,h=this;return h.edges.forEach(function(a){if(a.source==h)r.add(a.target);else{if(a.target!=h)throw"Incorrect incidency!";r.add(a.source)}}),r},n.prototype.withChildren=function(){var r=new Set,h,a;if(r.add(this),this.child!=null)for(var p=this.child.getNodes(),v=0;vh&&(this.rect.x-=(this.labelWidth-h)/2,this.setWidth(this.labelWidth)),this.labelHeight>a&&(this.labelPos=="center"?this.rect.y-=(this.labelHeight-a)/2:this.labelPos=="top"&&(this.rect.y-=this.labelHeight-a),this.setHeight(this.labelHeight))}}},n.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==e.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},n.prototype.transform=function(r){var h=this.rect.x;h>i.WORLD_BOUNDARY?h=i.WORLD_BOUNDARY:h<-i.WORLD_BOUNDARY&&(h=-i.WORLD_BOUNDARY);var a=this.rect.y;a>i.WORLD_BOUNDARY?a=i.WORLD_BOUNDARY:a<-i.WORLD_BOUNDARY&&(a=-i.WORLD_BOUNDARY);var p=new g(h,a),v=r.inverseTransformPoint(p);this.setLocation(v.x,v.y)},n.prototype.getLeft=function(){return this.rect.x},n.prototype.getRight=function(){return this.rect.x+this.rect.width},n.prototype.getTop=function(){return this.rect.y},n.prototype.getBottom=function(){return this.rect.y+this.rect.height},n.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},N.exports=n}),(function(N,I,T){function o(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}o.prototype.getX=function(){return this.x},o.prototype.getY=function(){return this.y},o.prototype.setX=function(e){this.x=e},o.prototype.setY=function(e){this.y=e},o.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},o.prototype.getCopy=function(){return new o(this.x,this.y)},o.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},N.exports=o}),(function(N,I,T){var o=T(2),e=T(10),t=T(0),i=T(6),l=T(3),g=T(1),n=T(13),d=T(12),r=T(11);function h(p,v,D){o.call(this,D),this.estimatedSize=e.MIN_VALUE,this.margin=t.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=p,v!=null&&v instanceof i?this.graphManager=v:v!=null&&v instanceof Layout&&(this.graphManager=v.graphManager)}h.prototype=Object.create(o.prototype);for(var a in o)h[a]=o[a];h.prototype.getNodes=function(){return this.nodes},h.prototype.getEdges=function(){return this.edges},h.prototype.getGraphManager=function(){return this.graphManager},h.prototype.getParent=function(){return this.parent},h.prototype.getLeft=function(){return this.left},h.prototype.getRight=function(){return this.right},h.prototype.getTop=function(){return this.top},h.prototype.getBottom=function(){return this.bottom},h.prototype.isConnected=function(){return this.isConnected},h.prototype.add=function(p,v,D){if(v==null&&D==null){var u=p;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(u)>-1)throw"Node already in graph!";return u.owner=this,this.getNodes().push(u),u}else{var E=p;if(!(this.getNodes().indexOf(v)>-1&&this.getNodes().indexOf(D)>-1))throw"Source or target not in graph!";if(!(v.owner==D.owner&&v.owner==this))throw"Both owners must be this graph!";return v.owner!=D.owner?null:(E.source=v,E.target=D,E.isInterGraph=!1,this.getEdges().push(E),v.edges.push(E),D!=v&&D.edges.push(E),E)}},h.prototype.remove=function(p){var v=p;if(p instanceof l){if(v==null)throw"Node is null!";if(!(v.owner!=null&&v.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var D=v.edges.slice(),u,E=D.length,y=0;y-1&&f>-1))throw"Source and/or target doesn't know this edge!";u.source.edges.splice(s,1),u.target!=u.source&&u.target.edges.splice(f,1);var O=u.source.owner.getEdges().indexOf(u);if(O==-1)throw"Not in owner's edge list!";u.source.owner.getEdges().splice(O,1)}},h.prototype.updateLeftTop=function(){for(var p=e.MAX_VALUE,v=e.MAX_VALUE,D,u,E,y=this.getNodes(),O=y.length,s=0;sD&&(p=D),v>u&&(v=u)}return p==e.MAX_VALUE?null:(y[0].getParent().paddingLeft!=null?E=y[0].getParent().paddingLeft:E=this.margin,this.left=v-E,this.top=p-E,new d(this.left,this.top))},h.prototype.updateBounds=function(p){for(var v=e.MAX_VALUE,D=-e.MAX_VALUE,u=e.MAX_VALUE,E=-e.MAX_VALUE,y,O,s,f,c,L=this.nodes,A=L.length,m=0;my&&(v=y),Ds&&(u=s),Ey&&(v=y),Ds&&(u=s),E=this.nodes.length){var A=0;D.forEach(function(m){m.owner==p&&A++}),A==this.nodes.length&&(this.isConnected=!0)}},N.exports=h}),(function(N,I,T){var o,e=T(1);function t(i){o=T(5),this.layout=i,this.graphs=[],this.edges=[]}t.prototype.addRoot=function(){var i=this.layout.newGraph(),l=this.layout.newNode(null),g=this.add(i,l);return this.setRootGraph(g),this.rootGraph},t.prototype.add=function(i,l,g,n,d){if(g==null&&n==null&&d==null){if(i==null)throw"Graph is null!";if(l==null)throw"Parent node is null!";if(this.graphs.indexOf(i)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(i),i.parent!=null)throw"Already has a parent!";if(l.child!=null)throw"Already has a child!";return i.parent=l,l.child=i,i}else{d=g,n=l,g=i;var r=n.getOwner(),h=d.getOwner();if(!(r!=null&&r.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(h!=null&&h.getGraphManager()==this))throw"Target not in this graph mgr!";if(r==h)return g.isInterGraph=!1,r.add(g,n,d);if(g.isInterGraph=!0,g.source=n,g.target=d,this.edges.indexOf(g)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(g),!(g.source!=null&&g.target!=null))throw"Edge source and/or target is null!";if(!(g.source.edges.indexOf(g)==-1&&g.target.edges.indexOf(g)==-1))throw"Edge already in source and/or target incidency list!";return g.source.edges.push(g),g.target.edges.push(g),g}},t.prototype.remove=function(i){if(i instanceof o){var l=i;if(l.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(l==this.rootGraph||l.parent!=null&&l.parent.graphManager==this))throw"Invalid parent node!";var g=[];g=g.concat(l.getEdges());for(var n,d=g.length,r=0;r=i.getRight()?l[0]+=Math.min(i.getX()-t.getX(),t.getRight()-i.getRight()):i.getX()<=t.getX()&&i.getRight()>=t.getRight()&&(l[0]+=Math.min(t.getX()-i.getX(),i.getRight()-t.getRight())),t.getY()<=i.getY()&&t.getBottom()>=i.getBottom()?l[1]+=Math.min(i.getY()-t.getY(),t.getBottom()-i.getBottom()):i.getY()<=t.getY()&&i.getBottom()>=t.getBottom()&&(l[1]+=Math.min(t.getY()-i.getY(),i.getBottom()-t.getBottom()));var d=Math.abs((i.getCenterY()-t.getCenterY())/(i.getCenterX()-t.getCenterX()));i.getCenterY()===t.getCenterY()&&i.getCenterX()===t.getCenterX()&&(d=1);var r=d*l[0],h=l[1]/d;l[0]r)return l[0]=g,l[1]=a,l[2]=d,l[3]=L,!1;if(nd)return l[0]=h,l[1]=n,l[2]=f,l[3]=r,!1;if(gd?(l[0]=v,l[1]=D,R=!0):(l[0]=p,l[1]=a,R=!0):S===w&&(g>d?(l[0]=h,l[1]=a,R=!0):(l[0]=u,l[1]=D,R=!0)),-Y===w?d>g?(l[2]=c,l[3]=L,M=!0):(l[2]=f,l[3]=s,M=!0):Y===w&&(d>g?(l[2]=O,l[3]=s,M=!0):(l[2]=A,l[3]=L,M=!0)),R&&M)return!1;if(g>d?n>r?(x=this.getCardinalDirection(S,w,4),F=this.getCardinalDirection(Y,w,2)):(x=this.getCardinalDirection(-S,w,3),F=this.getCardinalDirection(-Y,w,1)):n>r?(x=this.getCardinalDirection(-S,w,1),F=this.getCardinalDirection(-Y,w,3)):(x=this.getCardinalDirection(S,w,2),F=this.getCardinalDirection(Y,w,4)),!R)switch(x){case 1:P=a,U=g+-y/w,l[0]=U,l[1]=P;break;case 2:U=u,P=n+E*w,l[0]=U,l[1]=P;break;case 3:P=D,U=g+y/w,l[0]=U,l[1]=P;break;case 4:U=v,P=n+-E*w,l[0]=U,l[1]=P;break}if(!M)switch(F){case 1:X=s,_=d+-C/w,l[2]=_,l[3]=X;break;case 2:_=A,X=r+m*w,l[2]=_,l[3]=X;break;case 3:X=L,_=d+C/w,l[2]=_,l[3]=X;break;case 4:_=c,X=r+-m*w,l[2]=_,l[3]=X;break}}return!1},e.getCardinalDirection=function(t,i,l){return t>i?l:1+l%4},e.getIntersection=function(t,i,l,g){if(g==null)return this.getIntersection2(t,i,l);var n=t.x,d=t.y,r=i.x,h=i.y,a=l.x,p=l.y,v=g.x,D=g.y,u=void 0,E=void 0,y=void 0,O=void 0,s=void 0,f=void 0,c=void 0,L=void 0,A=void 0;return y=h-d,s=n-r,c=r*d-n*h,O=D-p,f=a-v,L=v*p-a*D,A=y*f-O*s,A===0?null:(u=(s*L-f*c)/A,E=(O*c-y*L)/A,new o(u,E))},e.angleOfVector=function(t,i,l,g){var n=void 0;return t!==l?(n=Math.atan((g-i)/(l-t)),l0?1:e<0?-1:0},o.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},o.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},N.exports=o}),(function(N,I,T){function o(){}o.MAX_VALUE=2147483647,o.MIN_VALUE=-2147483648,N.exports=o}),(function(N,I,T){var o=(function(){function n(d,r){for(var h=0;h"u"?"undefined":o(t);return t==null||i!="object"&&i!="function"},N.exports=e}),(function(N,I,T){function o(a){if(Array.isArray(a)){for(var p=0,v=Array(a.length);p0&&p;){for(y.push(s[0]);y.length>0&&p;){var f=y[0];y.splice(0,1),E.add(f);for(var c=f.getEdges(),u=0;u-1&&s.splice(C,1)}E=new Set,O=new Map}}return a},h.prototype.createDummyNodesForBendpoints=function(a){for(var p=[],v=a.source,D=this.graphManager.calcLowestCommonAncestor(a.source,a.target),u=0;u0){for(var D=this.edgeToDummyNodes.get(v),u=0;u=0&&p.splice(L,1);var A=O.getNeighborsList();A.forEach(function(R){if(v.indexOf(R)<0){var M=D.get(R),S=M-1;S==1&&f.push(R),D.set(R,S)}})}v=v.concat(f),(p.length==1||p.length==2)&&(u=!0,E=p[0])}return E},h.prototype.setGraphManager=function(a){this.graphManager=a},N.exports=h}),(function(N,I,T){function o(){}o.seed=1,o.x=0,o.nextDouble=function(){return o.x=Math.sin(o.seed++)*1e4,o.x-Math.floor(o.x)},N.exports=o}),(function(N,I,T){var o=T(4);function e(t,i){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}e.prototype.getWorldOrgX=function(){return this.lworldOrgX},e.prototype.setWorldOrgX=function(t){this.lworldOrgX=t},e.prototype.getWorldOrgY=function(){return this.lworldOrgY},e.prototype.setWorldOrgY=function(t){this.lworldOrgY=t},e.prototype.getWorldExtX=function(){return this.lworldExtX},e.prototype.setWorldExtX=function(t){this.lworldExtX=t},e.prototype.getWorldExtY=function(){return this.lworldExtY},e.prototype.setWorldExtY=function(t){this.lworldExtY=t},e.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},e.prototype.setDeviceOrgX=function(t){this.ldeviceOrgX=t},e.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},e.prototype.setDeviceOrgY=function(t){this.ldeviceOrgY=t},e.prototype.getDeviceExtX=function(){return this.ldeviceExtX},e.prototype.setDeviceExtX=function(t){this.ldeviceExtX=t},e.prototype.getDeviceExtY=function(){return this.ldeviceExtY},e.prototype.setDeviceExtY=function(t){this.ldeviceExtY=t},e.prototype.transformX=function(t){var i=0,l=this.lworldExtX;return l!=0&&(i=this.ldeviceOrgX+(t-this.lworldOrgX)*this.ldeviceExtX/l),i},e.prototype.transformY=function(t){var i=0,l=this.lworldExtY;return l!=0&&(i=this.ldeviceOrgY+(t-this.lworldOrgY)*this.ldeviceExtY/l),i},e.prototype.inverseTransformX=function(t){var i=0,l=this.ldeviceExtX;return l!=0&&(i=this.lworldOrgX+(t-this.ldeviceOrgX)*this.lworldExtX/l),i},e.prototype.inverseTransformY=function(t){var i=0,l=this.ldeviceExtY;return l!=0&&(i=this.lworldOrgY+(t-this.ldeviceOrgY)*this.lworldExtY/l),i},e.prototype.inverseTransformPoint=function(t){var i=new o(this.inverseTransformX(t.x),this.inverseTransformY(t.y));return i},N.exports=e}),(function(N,I,T){function o(r){if(Array.isArray(r)){for(var h=0,a=Array(r.length);ht.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*t.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(r-t.ADAPTATION_LOWER_NODE_LIMIT)/(t.ADAPTATION_UPPER_NODE_LIMIT-t.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-t.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=t.MAX_NODE_DISPLACEMENT_INCREMENTAL):(r>t.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(t.COOLING_ADAPTATION_FACTOR,1-(r-t.ADAPTATION_LOWER_NODE_LIMIT)/(t.ADAPTATION_UPPER_NODE_LIMIT-t.ADAPTATION_LOWER_NODE_LIMIT)*(1-t.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=t.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},n.prototype.calcSpringForces=function(){for(var r=this.getAllEdges(),h,a=0;a0&&arguments[0]!==void 0?arguments[0]:!0,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,a,p,v,D,u=this.getAllNodes(),E;if(this.useFRGridVariant)for(this.totalIterations%t.GRID_CALCULATION_CHECK_PERIOD==1&&r&&this.updateGrid(),E=new Set,a=0;ay||E>y)&&(r.gravitationForceX=-this.gravityConstant*v,r.gravitationForceY=-this.gravityConstant*D)):(y=h.getEstimatedSize()*this.compoundGravityRangeFactor,(u>y||E>y)&&(r.gravitationForceX=-this.gravityConstant*v*this.compoundGravityConstant,r.gravitationForceY=-this.gravityConstant*D*this.compoundGravityConstant))},n.prototype.isConverged=function(){var r,h=!1;return this.totalIterations>this.maxIterations/3&&(h=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),r=this.totalDisplacement=u.length||y>=u[0].length)){for(var O=0;On}}]),l})();N.exports=i}),(function(N,I,T){var o=(function(){function i(l,g){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,d=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;e(this,i),this.sequence1=l,this.sequence2=g,this.match_score=n,this.mismatch_penalty=d,this.gap_penalty=r,this.iMax=l.length+1,this.jMax=g.length+1,this.grid=new Array(this.iMax);for(var h=0;h=0;l--){var g=this.listeners[l];g.event===t&&g.callback===i&&this.listeners.splice(l,1)}},e.emit=function(t,i){for(var l=0;lg.coolingFactor*g.maxNodeDisplacement&&(this.displacementX=g.coolingFactor*g.maxNodeDisplacement*t.sign(this.displacementX)),Math.abs(this.displacementY)>g.coolingFactor*g.maxNodeDisplacement&&(this.displacementY=g.coolingFactor*g.maxNodeDisplacement*t.sign(this.displacementY)),this.child==null?this.moveBy(this.displacementX,this.displacementY):this.child.getNodes().length==0?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),g.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},i.prototype.propogateDisplacementToChildren=function(g,n){for(var d=this.getChild().getNodes(),r,h=0;h0)this.positionNodesRadially(s);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var f=new Set(this.getAllNodes()),c=this.nodesWithGravity.filter(function(L){return f.has(L)});this.graphManager.setAllNodesToApplyGravitation(c),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},y.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%d.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var s=new Set(this.getAllNodes()),f=this.nodesWithGravity.filter(function(A){return s.has(A)});this.graphManager.setAllNodesToApplyGravitation(f),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var c=!this.isTreeGrowing&&!this.isGrowthFinished,L=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(c,L),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},y.prototype.getPositionsData=function(){for(var s=this.graphManager.getAllNodes(),f={},c=0;c1){var R;for(R=0;RL&&(L=Math.floor(C.y)),m=Math.floor(C.x+n.DEFAULT_COMPONENT_SEPERATION)}this.transform(new a(r.WORLD_CENTER_X-C.x/2,r.WORLD_CENTER_Y-C.y/2))},y.radialLayout=function(s,f,c){var L=Math.max(this.maxDiagonalInTree(s),n.DEFAULT_RADIAL_SEPARATION);y.branchRadialLayout(f,null,0,359,0,L);var A=u.calculateBounds(s),m=new E;m.setDeviceOrgX(A.getMinX()),m.setDeviceOrgY(A.getMinY()),m.setWorldOrgX(c.x),m.setWorldOrgY(c.y);for(var C=0;C1;){var X=_[0];_.splice(0,1);var H=w.indexOf(X);H>=0&&w.splice(H,1),U--,x--}f!=null?P=(w.indexOf(_[0])+1)%U:P=0;for(var W=Math.abs(L-c)/x,B=P;F!=x;B=++B%U){var K=w[B].getOtherEnd(s);if(K!=f){var q=(c+F*W)%360,ht=(q+W)%360;y.branchRadialLayout(K,s,q,ht,A+m,m),F++}}},y.maxDiagonalInTree=function(s){for(var f=v.MIN_VALUE,c=0;cf&&(f=A)}return f},y.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},y.prototype.groupZeroDegreeMembers=function(){var s=this,f={};this.memberGroups={},this.idToDummyNode={};for(var c=[],L=this.graphManager.getAllNodes(),A=0;A"u"&&(f[R]=[]),f[R]=f[R].concat(m)}Object.keys(f).forEach(function(M){if(f[M].length>1){var S="DummyCompound_"+M;s.memberGroups[S]=f[M];var Y=f[M][0].getParent(),w=new l(s.graphManager);w.id=S,w.paddingLeft=Y.paddingLeft||0,w.paddingRight=Y.paddingRight||0,w.paddingBottom=Y.paddingBottom||0,w.paddingTop=Y.paddingTop||0,s.idToDummyNode[S]=w;var x=s.getGraphManager().add(s.newGraph(),w),F=Y.getChild();F.add(w);for(var U=0;U=0;s--){var f=this.compoundOrder[s],c=f.id,L=f.paddingLeft,A=f.paddingTop;this.adjustLocations(this.tiledMemberPack[c],f.rect.x,f.rect.y,L,A)}},y.prototype.repopulateZeroDegreeMembers=function(){var s=this,f=this.tiledZeroDegreePack;Object.keys(f).forEach(function(c){var L=s.idToDummyNode[c],A=L.paddingLeft,m=L.paddingTop;s.adjustLocations(f[c],L.rect.x,L.rect.y,A,m)})},y.prototype.getToBeTiled=function(s){var f=s.id;if(this.toBeTiled[f]!=null)return this.toBeTiled[f];var c=s.getChild();if(c==null)return this.toBeTiled[f]=!1,!1;for(var L=c.getNodes(),A=0;A0)return this.toBeTiled[f]=!1,!1;if(m.getChild()==null){this.toBeTiled[m.id]=!1;continue}if(!this.getToBeTiled(m))return this.toBeTiled[f]=!1,!1}return this.toBeTiled[f]=!0,!0},y.prototype.getNodeDegree=function(s){s.id;for(var f=s.getEdges(),c=0,L=0;LM&&(M=Y.rect.height)}c+=M+s.verticalPadding}},y.prototype.tileCompoundMembers=function(s,f){var c=this;this.tiledMemberPack=[],Object.keys(s).forEach(function(L){var A=f[L];c.tiledMemberPack[L]=c.tileNodes(s[L],A.paddingLeft+A.paddingRight),A.rect.width=c.tiledMemberPack[L].width,A.rect.height=c.tiledMemberPack[L].height})},y.prototype.tileNodes=function(s,f){var c=n.TILING_PADDING_VERTICAL,L=n.TILING_PADDING_HORIZONTAL,A={rows:[],rowWidth:[],rowHeight:[],width:0,height:f,verticalPadding:c,horizontalPadding:L};s.sort(function(R,M){return R.rect.width*R.rect.height>M.rect.width*M.rect.height?-1:R.rect.width*R.rect.height0&&(C+=s.horizontalPadding),s.rowWidth[c]=C,s.width0&&(R+=s.verticalPadding);var M=0;R>s.rowHeight[c]&&(M=s.rowHeight[c],s.rowHeight[c]=R,M=s.rowHeight[c]-M),s.height+=M,s.rows[c].push(f)},y.prototype.getShortestRowIndex=function(s){for(var f=-1,c=Number.MAX_VALUE,L=0;Lc&&(f=L,c=s.rowWidth[L]);return f},y.prototype.canAddHorizontal=function(s,f,c){var L=this.getShortestRowIndex(s);if(L<0)return!0;var A=s.rowWidth[L];if(A+s.horizontalPadding+f<=s.width)return!0;var m=0;s.rowHeight[L]0&&(m=c+s.verticalPadding-s.rowHeight[L]);var C;s.width-A>=f+s.horizontalPadding?C=(s.height+m)/(A+f+s.horizontalPadding):C=(s.height+m)/s.width,m=c+s.verticalPadding;var R;return s.widthm&&f!=c){L.splice(-1,1),s.rows[c].push(A),s.rowWidth[f]=s.rowWidth[f]-m,s.rowWidth[c]=s.rowWidth[c]+m,s.width=s.rowWidth[instance.getLongestRowIndex(s)];for(var C=Number.MIN_VALUE,R=0;RC&&(C=L[R].height);f>0&&(C+=s.verticalPadding);var M=s.rowHeight[f]+s.rowHeight[c];s.rowHeight[f]=C,s.rowHeight[c]0)for(var F=A;F<=m;F++)x[0]+=this.grid[F][C-1].length+this.grid[F][C].length-1;if(m0)for(var F=C;F<=R;F++)x[3]+=this.grid[A-1][F].length+this.grid[A][F].length-1;for(var U=v.MAX_VALUE,P,_,X=0;X0){var R;R=E.getGraphManager().add(E.newGraph(),c),this.processChildrenList(R,f,E)}}},a.prototype.stop=function(){return this.stopped=!0,this};var v=function(u){u("layout","cose-bilkent",a)};typeof cytoscape<"u"&&v(cytoscape),I.exports=v})])})})(Z)),Z.exports}var yt=vt();const Et=lt(yt);tt.use(Et);function et(G,b){G.forEach(N=>{const I={id:N.id,labelText:N.label,height:N.height,width:N.width,padding:N.padding??0};Object.keys(N).forEach(T=>{["id","label","height","width","padding","x","y"].includes(T)||(I[T]=N[T])}),b.add({group:"nodes",data:I,position:{x:N.x??0,y:N.y??0}})})}V(et,"addNodes");function rt(G,b){G.forEach(N=>{const I={id:N.id,source:N.start,target:N.end};Object.keys(N).forEach(T=>{["id","start","end"].includes(T)||(I[T]=N[T])}),b.add({group:"edges",data:I})})}V(rt,"addEdges");function it(G){return new Promise(b=>{const N=gt("body").append("div").attr("id","cy").attr("style","display:none"),I=tt({container:document.getElementById("cy"),style:[{selector:"edge",style:{"curve-style":"bezier"}}]});N.remove(),et(G.nodes,I),rt(G.edges,I),I.nodes().forEach(function(o){o.layoutDimensions=()=>{const e=o.data();return{w:e.width,h:e.height}}});const T={name:"cose-bilkent",quality:"proof",styleEnabled:!1,animate:!1};I.layout(T).run(),I.ready(o=>{k.info("Cytoscape ready",o),b(I)})})}V(it,"createCytoscapeInstance");function nt(G){return G.nodes().map(b=>{const N=b.data(),I=b.position(),T={id:N.id,x:I.x,y:I.y};return Object.keys(N).forEach(o=>{o!=="id"&&(T[o]=N[o])}),T})}V(nt,"extractPositionedNodes");function ot(G){return G.edges().map(b=>{const N=b.data(),I=b._private.rscratch,T={id:N.id,source:N.source,target:N.target,startX:I.startX,startY:I.startY,midX:I.midX,midY:I.midY,endX:I.endX,endY:I.endY};return Object.keys(N).forEach(o=>{["id","source","target"].includes(o)||(T[o]=N[o])}),T})}V(ot,"extractPositionedEdges");async function st(G,b){k.debug("Starting cose-bilkent layout algorithm");try{at(G);const N=await it(G),I=nt(N),T=ot(N);return k.debug(`Layout completed: ${I.length} nodes, ${T.length} edges`),{nodes:I,edges:T}}catch(N){throw k.error("Error in cose-bilkent layout algorithm:",N),N}}V(st,"executeCoseBilkentLayout");function at(G){if(!G)throw new Error("Layout data is required");if(!G.config)throw new Error("Configuration is required in layout data");if(!G.rootNode)throw new Error("Root node is required");if(!G.nodes||!Array.isArray(G.nodes))throw new Error("No nodes found in layout data");if(!Array.isArray(G.edges))throw new Error("Edges array is required in layout data");return!0}V(at,"validateLayoutData");var Lt=V(async(G,b,{insertCluster:N,insertEdge:I,insertEdgeLabel:T,insertMarkers:o,insertNode:e,log:t,positionEdgeLabel:i},{algorithm:l})=>{const g={},n={},d=b.select("g");o(d,G.markers,G.type,G.diagramId);const r=d.insert("g").attr("class","subgraphs"),h=d.insert("g").attr("class","edgePaths"),a=d.insert("g").attr("class","edgeLabels"),p=d.insert("g").attr("class","nodes");t.debug("Inserting nodes into DOM for dimension calculation"),await Promise.all(G.nodes.map(async u=>{if(u.isGroup){const E={...u};n[u.id]=E,g[u.id]=E,await N(r,u)}else{const E={...u};g[u.id]=E;const y=await e(p,u,{config:G.config,dir:G.direction||"TB"}),O=y.node().getBBox();E.width=O.width,E.height=O.height,E.domId=y,t.debug(`Node ${u.id} dimensions: ${O.width}x${O.height}`)}})),t.debug("Running cose-bilkent layout algorithm");const v={...G,nodes:G.nodes.map(u=>{const E=g[u.id];return{...u,width:E.width,height:E.height}})},D=await st(v,G.config);t.debug("Positioning nodes based on layout results"),D.nodes.forEach(u=>{const E=g[u.id];E!=null&&E.domId&&(E.domId.attr("transform",`translate(${u.x}, ${u.y})`),E.x=u.x,E.y=u.y,t.debug(`Positioned node ${E.id} at center (${u.x}, ${u.y})`))}),D.edges.forEach(u=>{const E=G.edges.find(y=>y.id===u.id);E&&(E.points=[{x:u.startX,y:u.startY},{x:u.midX,y:u.midY},{x:u.endX,y:u.endY}])}),t.debug("Inserting and positioning edges"),await Promise.all(G.edges.map(async u=>{await T(a,u);const E=g[u.start??""],y=g[u.end??""];if(E&&y){const O=D.edges.find(s=>s.id===u.id);if(O){t.debug("APA01 positionedEdge",O);const s={...u},f=I(h,s,n,G.type,E,y,G.diagramId);i(s,f)}else{const s={...u,points:[{x:E.x||0,y:E.y||0},{x:y.x||0,y:y.y||0}]},f=I(h,s,n,G.type,E,y,G.diagramId);i(s,f)}}})),t.debug("Cose-bilkent rendering completed")},"render"),mt=Lt;export{mt as render}; +import{_ as V,l as k}from"./mermaid.core-BRmiRRt4.js";import{c as tt}from"./cytoscape.esm-Bch-eiPH.js";import{g as lt}from"./vendor-utils-_6D5wMFs.js";import{s as gt}from"./vendor-flow-bDma3vSM.js";import"./index-DYMv5Ibu.js";import"./vendor-charts-CwfdE1jD.js";var Z={exports:{}},$={exports:{}},Q={exports:{}},ut=Q.exports,j;function ft(){return j||(j=1,(function(G,b){(function(I,T){G.exports=T()})(ut,function(){return(function(N){var I={};function T(o){if(I[o])return I[o].exports;var e=I[o]={i:o,l:!1,exports:{}};return N[o].call(e.exports,e,e.exports,T),e.l=!0,e.exports}return T.m=N,T.c=I,T.i=function(o){return o},T.d=function(o,e,t){T.o(o,e)||Object.defineProperty(o,e,{configurable:!1,enumerable:!0,get:t})},T.n=function(o){var e=o&&o.__esModule?function(){return o.default}:function(){return o};return T.d(e,"a",e),e},T.o=function(o,e){return Object.prototype.hasOwnProperty.call(o,e)},T.p="",T(T.s=26)})([(function(N,I,T){function o(){}o.QUALITY=1,o.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,o.DEFAULT_INCREMENTAL=!1,o.DEFAULT_ANIMATION_ON_LAYOUT=!0,o.DEFAULT_ANIMATION_DURING_LAYOUT=!1,o.DEFAULT_ANIMATION_PERIOD=50,o.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,o.DEFAULT_GRAPH_MARGIN=15,o.NODE_DIMENSIONS_INCLUDE_LABELS=!1,o.SIMPLE_NODE_SIZE=40,o.SIMPLE_NODE_HALF_SIZE=o.SIMPLE_NODE_SIZE/2,o.EMPTY_COMPOUND_NODE_SIZE=40,o.MIN_EDGE_LENGTH=1,o.WORLD_BOUNDARY=1e6,o.INITIAL_WORLD_BOUNDARY=o.WORLD_BOUNDARY/1e3,o.WORLD_CENTER_X=1200,o.WORLD_CENTER_Y=900,N.exports=o}),(function(N,I,T){var o=T(2),e=T(8),t=T(9);function i(g,n,d){o.call(this,d),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=d,this.bendpoints=[],this.source=g,this.target=n}i.prototype=Object.create(o.prototype);for(var l in o)i[l]=o[l];i.prototype.getSource=function(){return this.source},i.prototype.getTarget=function(){return this.target},i.prototype.isInterGraph=function(){return this.isInterGraph},i.prototype.getLength=function(){return this.length},i.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},i.prototype.getBendpoints=function(){return this.bendpoints},i.prototype.getLca=function(){return this.lca},i.prototype.getSourceInLca=function(){return this.sourceInLca},i.prototype.getTargetInLca=function(){return this.targetInLca},i.prototype.getOtherEnd=function(g){if(this.source===g)return this.target;if(this.target===g)return this.source;throw"Node is not incident with this edge"},i.prototype.getOtherEndInGraph=function(g,n){for(var d=this.getOtherEnd(g),r=n.getGraphManager().getRoot();;){if(d.getOwner()==n)return d;if(d.getOwner()==r)break;d=d.getOwner().getParent()}return null},i.prototype.updateLength=function(){var g=new Array(4);this.isOverlapingSourceAndTarget=e.getIntersection(this.target.getRect(),this.source.getRect(),g),this.isOverlapingSourceAndTarget||(this.lengthX=g[0]-g[2],this.lengthY=g[1]-g[3],Math.abs(this.lengthX)<1&&(this.lengthX=t.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=t.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},i.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=t.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=t.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},N.exports=i}),(function(N,I,T){function o(e){this.vGraphObject=e}N.exports=o}),(function(N,I,T){var o=T(2),e=T(10),t=T(13),i=T(0),l=T(16),g=T(4);function n(r,h,a,p){a==null&&p==null&&(p=h),o.call(this,p),r.graphManager!=null&&(r=r.graphManager),this.estimatedSize=e.MIN_VALUE,this.inclusionTreeDepth=e.MAX_VALUE,this.vGraphObject=p,this.edges=[],this.graphManager=r,a!=null&&h!=null?this.rect=new t(h.x,h.y,a.width,a.height):this.rect=new t}n.prototype=Object.create(o.prototype);for(var d in o)n[d]=o[d];n.prototype.getEdges=function(){return this.edges},n.prototype.getChild=function(){return this.child},n.prototype.getOwner=function(){return this.owner},n.prototype.getWidth=function(){return this.rect.width},n.prototype.setWidth=function(r){this.rect.width=r},n.prototype.getHeight=function(){return this.rect.height},n.prototype.setHeight=function(r){this.rect.height=r},n.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},n.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},n.prototype.getCenter=function(){return new g(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},n.prototype.getLocation=function(){return new g(this.rect.x,this.rect.y)},n.prototype.getRect=function(){return this.rect},n.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},n.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},n.prototype.setRect=function(r,h){this.rect.x=r.x,this.rect.y=r.y,this.rect.width=h.width,this.rect.height=h.height},n.prototype.setCenter=function(r,h){this.rect.x=r-this.rect.width/2,this.rect.y=h-this.rect.height/2},n.prototype.setLocation=function(r,h){this.rect.x=r,this.rect.y=h},n.prototype.moveBy=function(r,h){this.rect.x+=r,this.rect.y+=h},n.prototype.getEdgeListToNode=function(r){var h=[],a=this;return a.edges.forEach(function(p){if(p.target==r){if(p.source!=a)throw"Incorrect edge source!";h.push(p)}}),h},n.prototype.getEdgesBetween=function(r){var h=[],a=this;return a.edges.forEach(function(p){if(!(p.source==a||p.target==a))throw"Incorrect edge source and/or target";(p.target==r||p.source==r)&&h.push(p)}),h},n.prototype.getNeighborsList=function(){var r=new Set,h=this;return h.edges.forEach(function(a){if(a.source==h)r.add(a.target);else{if(a.target!=h)throw"Incorrect incidency!";r.add(a.source)}}),r},n.prototype.withChildren=function(){var r=new Set,h,a;if(r.add(this),this.child!=null)for(var p=this.child.getNodes(),v=0;vh&&(this.rect.x-=(this.labelWidth-h)/2,this.setWidth(this.labelWidth)),this.labelHeight>a&&(this.labelPos=="center"?this.rect.y-=(this.labelHeight-a)/2:this.labelPos=="top"&&(this.rect.y-=this.labelHeight-a),this.setHeight(this.labelHeight))}}},n.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==e.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},n.prototype.transform=function(r){var h=this.rect.x;h>i.WORLD_BOUNDARY?h=i.WORLD_BOUNDARY:h<-i.WORLD_BOUNDARY&&(h=-i.WORLD_BOUNDARY);var a=this.rect.y;a>i.WORLD_BOUNDARY?a=i.WORLD_BOUNDARY:a<-i.WORLD_BOUNDARY&&(a=-i.WORLD_BOUNDARY);var p=new g(h,a),v=r.inverseTransformPoint(p);this.setLocation(v.x,v.y)},n.prototype.getLeft=function(){return this.rect.x},n.prototype.getRight=function(){return this.rect.x+this.rect.width},n.prototype.getTop=function(){return this.rect.y},n.prototype.getBottom=function(){return this.rect.y+this.rect.height},n.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},N.exports=n}),(function(N,I,T){function o(e,t){e==null&&t==null?(this.x=0,this.y=0):(this.x=e,this.y=t)}o.prototype.getX=function(){return this.x},o.prototype.getY=function(){return this.y},o.prototype.setX=function(e){this.x=e},o.prototype.setY=function(e){this.y=e},o.prototype.getDifference=function(e){return new DimensionD(this.x-e.x,this.y-e.y)},o.prototype.getCopy=function(){return new o(this.x,this.y)},o.prototype.translate=function(e){return this.x+=e.width,this.y+=e.height,this},N.exports=o}),(function(N,I,T){var o=T(2),e=T(10),t=T(0),i=T(6),l=T(3),g=T(1),n=T(13),d=T(12),r=T(11);function h(p,v,D){o.call(this,D),this.estimatedSize=e.MIN_VALUE,this.margin=t.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=p,v!=null&&v instanceof i?this.graphManager=v:v!=null&&v instanceof Layout&&(this.graphManager=v.graphManager)}h.prototype=Object.create(o.prototype);for(var a in o)h[a]=o[a];h.prototype.getNodes=function(){return this.nodes},h.prototype.getEdges=function(){return this.edges},h.prototype.getGraphManager=function(){return this.graphManager},h.prototype.getParent=function(){return this.parent},h.prototype.getLeft=function(){return this.left},h.prototype.getRight=function(){return this.right},h.prototype.getTop=function(){return this.top},h.prototype.getBottom=function(){return this.bottom},h.prototype.isConnected=function(){return this.isConnected},h.prototype.add=function(p,v,D){if(v==null&&D==null){var u=p;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(u)>-1)throw"Node already in graph!";return u.owner=this,this.getNodes().push(u),u}else{var E=p;if(!(this.getNodes().indexOf(v)>-1&&this.getNodes().indexOf(D)>-1))throw"Source or target not in graph!";if(!(v.owner==D.owner&&v.owner==this))throw"Both owners must be this graph!";return v.owner!=D.owner?null:(E.source=v,E.target=D,E.isInterGraph=!1,this.getEdges().push(E),v.edges.push(E),D!=v&&D.edges.push(E),E)}},h.prototype.remove=function(p){var v=p;if(p instanceof l){if(v==null)throw"Node is null!";if(!(v.owner!=null&&v.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var D=v.edges.slice(),u,E=D.length,y=0;y-1&&f>-1))throw"Source and/or target doesn't know this edge!";u.source.edges.splice(s,1),u.target!=u.source&&u.target.edges.splice(f,1);var O=u.source.owner.getEdges().indexOf(u);if(O==-1)throw"Not in owner's edge list!";u.source.owner.getEdges().splice(O,1)}},h.prototype.updateLeftTop=function(){for(var p=e.MAX_VALUE,v=e.MAX_VALUE,D,u,E,y=this.getNodes(),O=y.length,s=0;sD&&(p=D),v>u&&(v=u)}return p==e.MAX_VALUE?null:(y[0].getParent().paddingLeft!=null?E=y[0].getParent().paddingLeft:E=this.margin,this.left=v-E,this.top=p-E,new d(this.left,this.top))},h.prototype.updateBounds=function(p){for(var v=e.MAX_VALUE,D=-e.MAX_VALUE,u=e.MAX_VALUE,E=-e.MAX_VALUE,y,O,s,f,c,L=this.nodes,A=L.length,m=0;my&&(v=y),Ds&&(u=s),Ey&&(v=y),Ds&&(u=s),E=this.nodes.length){var A=0;D.forEach(function(m){m.owner==p&&A++}),A==this.nodes.length&&(this.isConnected=!0)}},N.exports=h}),(function(N,I,T){var o,e=T(1);function t(i){o=T(5),this.layout=i,this.graphs=[],this.edges=[]}t.prototype.addRoot=function(){var i=this.layout.newGraph(),l=this.layout.newNode(null),g=this.add(i,l);return this.setRootGraph(g),this.rootGraph},t.prototype.add=function(i,l,g,n,d){if(g==null&&n==null&&d==null){if(i==null)throw"Graph is null!";if(l==null)throw"Parent node is null!";if(this.graphs.indexOf(i)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(i),i.parent!=null)throw"Already has a parent!";if(l.child!=null)throw"Already has a child!";return i.parent=l,l.child=i,i}else{d=g,n=l,g=i;var r=n.getOwner(),h=d.getOwner();if(!(r!=null&&r.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(h!=null&&h.getGraphManager()==this))throw"Target not in this graph mgr!";if(r==h)return g.isInterGraph=!1,r.add(g,n,d);if(g.isInterGraph=!0,g.source=n,g.target=d,this.edges.indexOf(g)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(g),!(g.source!=null&&g.target!=null))throw"Edge source and/or target is null!";if(!(g.source.edges.indexOf(g)==-1&&g.target.edges.indexOf(g)==-1))throw"Edge already in source and/or target incidency list!";return g.source.edges.push(g),g.target.edges.push(g),g}},t.prototype.remove=function(i){if(i instanceof o){var l=i;if(l.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(l==this.rootGraph||l.parent!=null&&l.parent.graphManager==this))throw"Invalid parent node!";var g=[];g=g.concat(l.getEdges());for(var n,d=g.length,r=0;r=i.getRight()?l[0]+=Math.min(i.getX()-t.getX(),t.getRight()-i.getRight()):i.getX()<=t.getX()&&i.getRight()>=t.getRight()&&(l[0]+=Math.min(t.getX()-i.getX(),i.getRight()-t.getRight())),t.getY()<=i.getY()&&t.getBottom()>=i.getBottom()?l[1]+=Math.min(i.getY()-t.getY(),t.getBottom()-i.getBottom()):i.getY()<=t.getY()&&i.getBottom()>=t.getBottom()&&(l[1]+=Math.min(t.getY()-i.getY(),i.getBottom()-t.getBottom()));var d=Math.abs((i.getCenterY()-t.getCenterY())/(i.getCenterX()-t.getCenterX()));i.getCenterY()===t.getCenterY()&&i.getCenterX()===t.getCenterX()&&(d=1);var r=d*l[0],h=l[1]/d;l[0]r)return l[0]=g,l[1]=a,l[2]=d,l[3]=L,!1;if(nd)return l[0]=h,l[1]=n,l[2]=f,l[3]=r,!1;if(gd?(l[0]=v,l[1]=D,R=!0):(l[0]=p,l[1]=a,R=!0):S===w&&(g>d?(l[0]=h,l[1]=a,R=!0):(l[0]=u,l[1]=D,R=!0)),-Y===w?d>g?(l[2]=c,l[3]=L,M=!0):(l[2]=f,l[3]=s,M=!0):Y===w&&(d>g?(l[2]=O,l[3]=s,M=!0):(l[2]=A,l[3]=L,M=!0)),R&&M)return!1;if(g>d?n>r?(x=this.getCardinalDirection(S,w,4),F=this.getCardinalDirection(Y,w,2)):(x=this.getCardinalDirection(-S,w,3),F=this.getCardinalDirection(-Y,w,1)):n>r?(x=this.getCardinalDirection(-S,w,1),F=this.getCardinalDirection(-Y,w,3)):(x=this.getCardinalDirection(S,w,2),F=this.getCardinalDirection(Y,w,4)),!R)switch(x){case 1:P=a,U=g+-y/w,l[0]=U,l[1]=P;break;case 2:U=u,P=n+E*w,l[0]=U,l[1]=P;break;case 3:P=D,U=g+y/w,l[0]=U,l[1]=P;break;case 4:U=v,P=n+-E*w,l[0]=U,l[1]=P;break}if(!M)switch(F){case 1:X=s,_=d+-C/w,l[2]=_,l[3]=X;break;case 2:_=A,X=r+m*w,l[2]=_,l[3]=X;break;case 3:X=L,_=d+C/w,l[2]=_,l[3]=X;break;case 4:_=c,X=r+-m*w,l[2]=_,l[3]=X;break}}return!1},e.getCardinalDirection=function(t,i,l){return t>i?l:1+l%4},e.getIntersection=function(t,i,l,g){if(g==null)return this.getIntersection2(t,i,l);var n=t.x,d=t.y,r=i.x,h=i.y,a=l.x,p=l.y,v=g.x,D=g.y,u=void 0,E=void 0,y=void 0,O=void 0,s=void 0,f=void 0,c=void 0,L=void 0,A=void 0;return y=h-d,s=n-r,c=r*d-n*h,O=D-p,f=a-v,L=v*p-a*D,A=y*f-O*s,A===0?null:(u=(s*L-f*c)/A,E=(O*c-y*L)/A,new o(u,E))},e.angleOfVector=function(t,i,l,g){var n=void 0;return t!==l?(n=Math.atan((g-i)/(l-t)),l0?1:e<0?-1:0},o.floor=function(e){return e<0?Math.ceil(e):Math.floor(e)},o.ceil=function(e){return e<0?Math.floor(e):Math.ceil(e)},N.exports=o}),(function(N,I,T){function o(){}o.MAX_VALUE=2147483647,o.MIN_VALUE=-2147483648,N.exports=o}),(function(N,I,T){var o=(function(){function n(d,r){for(var h=0;h"u"?"undefined":o(t);return t==null||i!="object"&&i!="function"},N.exports=e}),(function(N,I,T){function o(a){if(Array.isArray(a)){for(var p=0,v=Array(a.length);p0&&p;){for(y.push(s[0]);y.length>0&&p;){var f=y[0];y.splice(0,1),E.add(f);for(var c=f.getEdges(),u=0;u-1&&s.splice(C,1)}E=new Set,O=new Map}}return a},h.prototype.createDummyNodesForBendpoints=function(a){for(var p=[],v=a.source,D=this.graphManager.calcLowestCommonAncestor(a.source,a.target),u=0;u0){for(var D=this.edgeToDummyNodes.get(v),u=0;u=0&&p.splice(L,1);var A=O.getNeighborsList();A.forEach(function(R){if(v.indexOf(R)<0){var M=D.get(R),S=M-1;S==1&&f.push(R),D.set(R,S)}})}v=v.concat(f),(p.length==1||p.length==2)&&(u=!0,E=p[0])}return E},h.prototype.setGraphManager=function(a){this.graphManager=a},N.exports=h}),(function(N,I,T){function o(){}o.seed=1,o.x=0,o.nextDouble=function(){return o.x=Math.sin(o.seed++)*1e4,o.x-Math.floor(o.x)},N.exports=o}),(function(N,I,T){var o=T(4);function e(t,i){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}e.prototype.getWorldOrgX=function(){return this.lworldOrgX},e.prototype.setWorldOrgX=function(t){this.lworldOrgX=t},e.prototype.getWorldOrgY=function(){return this.lworldOrgY},e.prototype.setWorldOrgY=function(t){this.lworldOrgY=t},e.prototype.getWorldExtX=function(){return this.lworldExtX},e.prototype.setWorldExtX=function(t){this.lworldExtX=t},e.prototype.getWorldExtY=function(){return this.lworldExtY},e.prototype.setWorldExtY=function(t){this.lworldExtY=t},e.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},e.prototype.setDeviceOrgX=function(t){this.ldeviceOrgX=t},e.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},e.prototype.setDeviceOrgY=function(t){this.ldeviceOrgY=t},e.prototype.getDeviceExtX=function(){return this.ldeviceExtX},e.prototype.setDeviceExtX=function(t){this.ldeviceExtX=t},e.prototype.getDeviceExtY=function(){return this.ldeviceExtY},e.prototype.setDeviceExtY=function(t){this.ldeviceExtY=t},e.prototype.transformX=function(t){var i=0,l=this.lworldExtX;return l!=0&&(i=this.ldeviceOrgX+(t-this.lworldOrgX)*this.ldeviceExtX/l),i},e.prototype.transformY=function(t){var i=0,l=this.lworldExtY;return l!=0&&(i=this.ldeviceOrgY+(t-this.lworldOrgY)*this.ldeviceExtY/l),i},e.prototype.inverseTransformX=function(t){var i=0,l=this.ldeviceExtX;return l!=0&&(i=this.lworldOrgX+(t-this.ldeviceOrgX)*this.lworldExtX/l),i},e.prototype.inverseTransformY=function(t){var i=0,l=this.ldeviceExtY;return l!=0&&(i=this.lworldOrgY+(t-this.ldeviceOrgY)*this.lworldExtY/l),i},e.prototype.inverseTransformPoint=function(t){var i=new o(this.inverseTransformX(t.x),this.inverseTransformY(t.y));return i},N.exports=e}),(function(N,I,T){function o(r){if(Array.isArray(r)){for(var h=0,a=Array(r.length);ht.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*t.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(r-t.ADAPTATION_LOWER_NODE_LIMIT)/(t.ADAPTATION_UPPER_NODE_LIMIT-t.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-t.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=t.MAX_NODE_DISPLACEMENT_INCREMENTAL):(r>t.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(t.COOLING_ADAPTATION_FACTOR,1-(r-t.ADAPTATION_LOWER_NODE_LIMIT)/(t.ADAPTATION_UPPER_NODE_LIMIT-t.ADAPTATION_LOWER_NODE_LIMIT)*(1-t.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=t.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},n.prototype.calcSpringForces=function(){for(var r=this.getAllEdges(),h,a=0;a0&&arguments[0]!==void 0?arguments[0]:!0,h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,a,p,v,D,u=this.getAllNodes(),E;if(this.useFRGridVariant)for(this.totalIterations%t.GRID_CALCULATION_CHECK_PERIOD==1&&r&&this.updateGrid(),E=new Set,a=0;ay||E>y)&&(r.gravitationForceX=-this.gravityConstant*v,r.gravitationForceY=-this.gravityConstant*D)):(y=h.getEstimatedSize()*this.compoundGravityRangeFactor,(u>y||E>y)&&(r.gravitationForceX=-this.gravityConstant*v*this.compoundGravityConstant,r.gravitationForceY=-this.gravityConstant*D*this.compoundGravityConstant))},n.prototype.isConverged=function(){var r,h=!1;return this.totalIterations>this.maxIterations/3&&(h=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),r=this.totalDisplacement=u.length||y>=u[0].length)){for(var O=0;On}}]),l})();N.exports=i}),(function(N,I,T){var o=(function(){function i(l,g){for(var n=0;n2&&arguments[2]!==void 0?arguments[2]:1,d=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;e(this,i),this.sequence1=l,this.sequence2=g,this.match_score=n,this.mismatch_penalty=d,this.gap_penalty=r,this.iMax=l.length+1,this.jMax=g.length+1,this.grid=new Array(this.iMax);for(var h=0;h=0;l--){var g=this.listeners[l];g.event===t&&g.callback===i&&this.listeners.splice(l,1)}},e.emit=function(t,i){for(var l=0;lg.coolingFactor*g.maxNodeDisplacement&&(this.displacementX=g.coolingFactor*g.maxNodeDisplacement*t.sign(this.displacementX)),Math.abs(this.displacementY)>g.coolingFactor*g.maxNodeDisplacement&&(this.displacementY=g.coolingFactor*g.maxNodeDisplacement*t.sign(this.displacementY)),this.child==null?this.moveBy(this.displacementX,this.displacementY):this.child.getNodes().length==0?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),g.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},i.prototype.propogateDisplacementToChildren=function(g,n){for(var d=this.getChild().getNodes(),r,h=0;h0)this.positionNodesRadially(s);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var f=new Set(this.getAllNodes()),c=this.nodesWithGravity.filter(function(L){return f.has(L)});this.graphManager.setAllNodesToApplyGravitation(c),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},y.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%d.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var s=new Set(this.getAllNodes()),f=this.nodesWithGravity.filter(function(A){return s.has(A)});this.graphManager.setAllNodesToApplyGravitation(f),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=d.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var c=!this.isTreeGrowing&&!this.isGrowthFinished,L=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(c,L),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},y.prototype.getPositionsData=function(){for(var s=this.graphManager.getAllNodes(),f={},c=0;c1){var R;for(R=0;RL&&(L=Math.floor(C.y)),m=Math.floor(C.x+n.DEFAULT_COMPONENT_SEPERATION)}this.transform(new a(r.WORLD_CENTER_X-C.x/2,r.WORLD_CENTER_Y-C.y/2))},y.radialLayout=function(s,f,c){var L=Math.max(this.maxDiagonalInTree(s),n.DEFAULT_RADIAL_SEPARATION);y.branchRadialLayout(f,null,0,359,0,L);var A=u.calculateBounds(s),m=new E;m.setDeviceOrgX(A.getMinX()),m.setDeviceOrgY(A.getMinY()),m.setWorldOrgX(c.x),m.setWorldOrgY(c.y);for(var C=0;C1;){var X=_[0];_.splice(0,1);var H=w.indexOf(X);H>=0&&w.splice(H,1),U--,x--}f!=null?P=(w.indexOf(_[0])+1)%U:P=0;for(var W=Math.abs(L-c)/x,B=P;F!=x;B=++B%U){var K=w[B].getOtherEnd(s);if(K!=f){var q=(c+F*W)%360,ht=(q+W)%360;y.branchRadialLayout(K,s,q,ht,A+m,m),F++}}},y.maxDiagonalInTree=function(s){for(var f=v.MIN_VALUE,c=0;cf&&(f=A)}return f},y.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},y.prototype.groupZeroDegreeMembers=function(){var s=this,f={};this.memberGroups={},this.idToDummyNode={};for(var c=[],L=this.graphManager.getAllNodes(),A=0;A"u"&&(f[R]=[]),f[R]=f[R].concat(m)}Object.keys(f).forEach(function(M){if(f[M].length>1){var S="DummyCompound_"+M;s.memberGroups[S]=f[M];var Y=f[M][0].getParent(),w=new l(s.graphManager);w.id=S,w.paddingLeft=Y.paddingLeft||0,w.paddingRight=Y.paddingRight||0,w.paddingBottom=Y.paddingBottom||0,w.paddingTop=Y.paddingTop||0,s.idToDummyNode[S]=w;var x=s.getGraphManager().add(s.newGraph(),w),F=Y.getChild();F.add(w);for(var U=0;U=0;s--){var f=this.compoundOrder[s],c=f.id,L=f.paddingLeft,A=f.paddingTop;this.adjustLocations(this.tiledMemberPack[c],f.rect.x,f.rect.y,L,A)}},y.prototype.repopulateZeroDegreeMembers=function(){var s=this,f=this.tiledZeroDegreePack;Object.keys(f).forEach(function(c){var L=s.idToDummyNode[c],A=L.paddingLeft,m=L.paddingTop;s.adjustLocations(f[c],L.rect.x,L.rect.y,A,m)})},y.prototype.getToBeTiled=function(s){var f=s.id;if(this.toBeTiled[f]!=null)return this.toBeTiled[f];var c=s.getChild();if(c==null)return this.toBeTiled[f]=!1,!1;for(var L=c.getNodes(),A=0;A0)return this.toBeTiled[f]=!1,!1;if(m.getChild()==null){this.toBeTiled[m.id]=!1;continue}if(!this.getToBeTiled(m))return this.toBeTiled[f]=!1,!1}return this.toBeTiled[f]=!0,!0},y.prototype.getNodeDegree=function(s){s.id;for(var f=s.getEdges(),c=0,L=0;LM&&(M=Y.rect.height)}c+=M+s.verticalPadding}},y.prototype.tileCompoundMembers=function(s,f){var c=this;this.tiledMemberPack=[],Object.keys(s).forEach(function(L){var A=f[L];c.tiledMemberPack[L]=c.tileNodes(s[L],A.paddingLeft+A.paddingRight),A.rect.width=c.tiledMemberPack[L].width,A.rect.height=c.tiledMemberPack[L].height})},y.prototype.tileNodes=function(s,f){var c=n.TILING_PADDING_VERTICAL,L=n.TILING_PADDING_HORIZONTAL,A={rows:[],rowWidth:[],rowHeight:[],width:0,height:f,verticalPadding:c,horizontalPadding:L};s.sort(function(R,M){return R.rect.width*R.rect.height>M.rect.width*M.rect.height?-1:R.rect.width*R.rect.height0&&(C+=s.horizontalPadding),s.rowWidth[c]=C,s.width0&&(R+=s.verticalPadding);var M=0;R>s.rowHeight[c]&&(M=s.rowHeight[c],s.rowHeight[c]=R,M=s.rowHeight[c]-M),s.height+=M,s.rows[c].push(f)},y.prototype.getShortestRowIndex=function(s){for(var f=-1,c=Number.MAX_VALUE,L=0;Lc&&(f=L,c=s.rowWidth[L]);return f},y.prototype.canAddHorizontal=function(s,f,c){var L=this.getShortestRowIndex(s);if(L<0)return!0;var A=s.rowWidth[L];if(A+s.horizontalPadding+f<=s.width)return!0;var m=0;s.rowHeight[L]0&&(m=c+s.verticalPadding-s.rowHeight[L]);var C;s.width-A>=f+s.horizontalPadding?C=(s.height+m)/(A+f+s.horizontalPadding):C=(s.height+m)/s.width,m=c+s.verticalPadding;var R;return s.widthm&&f!=c){L.splice(-1,1),s.rows[c].push(A),s.rowWidth[f]=s.rowWidth[f]-m,s.rowWidth[c]=s.rowWidth[c]+m,s.width=s.rowWidth[instance.getLongestRowIndex(s)];for(var C=Number.MIN_VALUE,R=0;RC&&(C=L[R].height);f>0&&(C+=s.verticalPadding);var M=s.rowHeight[f]+s.rowHeight[c];s.rowHeight[f]=C,s.rowHeight[c]0)for(var F=A;F<=m;F++)x[0]+=this.grid[F][C-1].length+this.grid[F][C].length-1;if(m0)for(var F=C;F<=R;F++)x[3]+=this.grid[A-1][F].length+this.grid[A][F].length-1;for(var U=v.MAX_VALUE,P,_,X=0;X0){var R;R=E.getGraphManager().add(E.newGraph(),c),this.processChildrenList(R,f,E)}}},a.prototype.stop=function(){return this.stopped=!0,this};var v=function(u){u("layout","cose-bilkent",a)};typeof cytoscape<"u"&&v(cytoscape),I.exports=v})])})})(Z)),Z.exports}var yt=vt();const Et=lt(yt);tt.use(Et);function et(G,b){G.forEach(N=>{const I={id:N.id,labelText:N.label,height:N.height,width:N.width,padding:N.padding??0};Object.keys(N).forEach(T=>{["id","label","height","width","padding","x","y"].includes(T)||(I[T]=N[T])}),b.add({group:"nodes",data:I,position:{x:N.x??0,y:N.y??0}})})}V(et,"addNodes");function rt(G,b){G.forEach(N=>{const I={id:N.id,source:N.start,target:N.end};Object.keys(N).forEach(T=>{["id","start","end"].includes(T)||(I[T]=N[T])}),b.add({group:"edges",data:I})})}V(rt,"addEdges");function it(G){return new Promise(b=>{const N=gt("body").append("div").attr("id","cy").attr("style","display:none"),I=tt({container:document.getElementById("cy"),style:[{selector:"edge",style:{"curve-style":"bezier"}}]});N.remove(),et(G.nodes,I),rt(G.edges,I),I.nodes().forEach(function(o){o.layoutDimensions=()=>{const e=o.data();return{w:e.width,h:e.height}}});const T={name:"cose-bilkent",quality:"proof",styleEnabled:!1,animate:!1};I.layout(T).run(),I.ready(o=>{k.info("Cytoscape ready",o),b(I)})})}V(it,"createCytoscapeInstance");function nt(G){return G.nodes().map(b=>{const N=b.data(),I=b.position(),T={id:N.id,x:I.x,y:I.y};return Object.keys(N).forEach(o=>{o!=="id"&&(T[o]=N[o])}),T})}V(nt,"extractPositionedNodes");function ot(G){return G.edges().map(b=>{const N=b.data(),I=b._private.rscratch,T={id:N.id,source:N.source,target:N.target,startX:I.startX,startY:I.startY,midX:I.midX,midY:I.midY,endX:I.endX,endY:I.endY};return Object.keys(N).forEach(o=>{["id","source","target"].includes(o)||(T[o]=N[o])}),T})}V(ot,"extractPositionedEdges");async function st(G,b){k.debug("Starting cose-bilkent layout algorithm");try{at(G);const N=await it(G),I=nt(N),T=ot(N);return k.debug(`Layout completed: ${I.length} nodes, ${T.length} edges`),{nodes:I,edges:T}}catch(N){throw k.error("Error in cose-bilkent layout algorithm:",N),N}}V(st,"executeCoseBilkentLayout");function at(G){if(!G)throw new Error("Layout data is required");if(!G.config)throw new Error("Configuration is required in layout data");if(!G.rootNode)throw new Error("Root node is required");if(!G.nodes||!Array.isArray(G.nodes))throw new Error("No nodes found in layout data");if(!Array.isArray(G.edges))throw new Error("Edges array is required in layout data");return!0}V(at,"validateLayoutData");var Lt=V(async(G,b,{insertCluster:N,insertEdge:I,insertEdgeLabel:T,insertMarkers:o,insertNode:e,log:t,positionEdgeLabel:i},{algorithm:l})=>{const g={},n={},d=b.select("g");o(d,G.markers,G.type,G.diagramId);const r=d.insert("g").attr("class","subgraphs"),h=d.insert("g").attr("class","edgePaths"),a=d.insert("g").attr("class","edgeLabels"),p=d.insert("g").attr("class","nodes");t.debug("Inserting nodes into DOM for dimension calculation"),await Promise.all(G.nodes.map(async u=>{if(u.isGroup){const E={...u};n[u.id]=E,g[u.id]=E,await N(r,u)}else{const E={...u};g[u.id]=E;const y=await e(p,u,{config:G.config,dir:G.direction||"TB"}),O=y.node().getBBox();E.width=O.width,E.height=O.height,E.domId=y,t.debug(`Node ${u.id} dimensions: ${O.width}x${O.height}`)}})),t.debug("Running cose-bilkent layout algorithm");const v={...G,nodes:G.nodes.map(u=>{const E=g[u.id];return{...u,width:E.width,height:E.height}})},D=await st(v,G.config);t.debug("Positioning nodes based on layout results"),D.nodes.forEach(u=>{const E=g[u.id];E!=null&&E.domId&&(E.domId.attr("transform",`translate(${u.x}, ${u.y})`),E.x=u.x,E.y=u.y,t.debug(`Positioned node ${E.id} at center (${u.x}, ${u.y})`))}),D.edges.forEach(u=>{const E=G.edges.find(y=>y.id===u.id);E&&(E.points=[{x:u.startX,y:u.startY},{x:u.midX,y:u.midY},{x:u.endX,y:u.endY}])}),t.debug("Inserting and positioning edges"),await Promise.all(G.edges.map(async u=>{await T(a,u);const E=g[u.start??""],y=g[u.end??""];if(E&&y){const O=D.edges.find(s=>s.id===u.id);if(O){t.debug("APA01 positionedEdge",O);const s={...u},f=I(h,s,n,G.type,E,y,G.diagramId);i(s,f)}else{const s={...u,points:[{x:E.x||0,y:E.y||0},{x:y.x||0,y:y.y||0}]},f=I(h,s,n,G.type,E,y,G.diagramId);i(s,f)}}})),t.debug("Cose-bilkent rendering completed")},"render"),mt=Lt;export{mt as render}; diff --git a/static/ml_canvas/assets/cynefin-OW5HDTMX-WQ4gGbOM.js b/static/ml_canvas/assets/cynefin-OW5HDTMX-DHAz5VCH.js similarity index 99% rename from static/ml_canvas/assets/cynefin-OW5HDTMX-WQ4gGbOM.js rename to static/ml_canvas/assets/cynefin-OW5HDTMX-DHAz5VCH.js index f517301be..a5d67a35e 100644 --- a/static/ml_canvas/assets/cynefin-OW5HDTMX-WQ4gGbOM.js +++ b/static/ml_canvas/assets/cynefin-OW5HDTMX-DHAz5VCH.js @@ -1,4 +1,4 @@ -var dk=Object.defineProperty;var pk=(t,e,r)=>e in t?dk(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Br=(t,e,r)=>pk(t,typeof e!="symbol"?e+"":e,r);import{a1 as ut}from"./index-BXksgzya.js";var mk=Object.create,Du=Object.defineProperty,hk=Object.getOwnPropertyDescriptor,Th=Object.getOwnPropertyNames,yk=Object.getPrototypeOf,gk=Object.prototype.hasOwnProperty,s=(t,e)=>Du(t,"name",{value:e,configurable:!0}),vk=(t,e)=>function(){return t&&(e=(0,t[Th(t)[0]])(t=0)),e},X=(t,e)=>function(){return e||(0,t[Th(t)[0]])((e={exports:{}}).exports,e),e.exports},tn=(t,e)=>{for(var r in e)Du(t,r,{get:e[r],enumerable:!0})},$h=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Th(e))!gk.call(t,a)&&a!==r&&Du(t,a,{get:()=>e[a],enumerable:!(n=hk(e,a))||n.enumerable});return t},Of=(t,e,r)=>($h(t,e,"default"),r),Rh=(t,e,r)=>(r=t!=null?mk(yk(t)):{},$h(Du(r,"default",{value:t,enumerable:!0}),t)),Ah=t=>$h(Du({},"__esModule",{value:!0}),t),Lf={};tn(Lf,{AnnotatedTextEdit:()=>Ar,ChangeAnnotation:()=>mn,ChangeAnnotationIdentifier:()=>et,CodeAction:()=>Qp,CodeActionContext:()=>Zp,CodeActionKind:()=>Jp,CodeActionTriggerKind:()=>Xl,CodeDescription:()=>Ip,CodeLens:()=>em,Color:()=>Ec,ColorInformation:()=>Ep,ColorPresentation:()=>Cp,Command:()=>pn,CompletionItem:()=>Fp,CompletionItemKind:()=>Op,CompletionItemLabelDetails:()=>Gp,CompletionItemTag:()=>Dp,CompletionList:()=>zp,CreateFile:()=>_a,DeleteFile:()=>wa,Diagnostic:()=>Vl,DiagnosticRelatedInformation:()=>Cc,DiagnosticSeverity:()=>Sp,DiagnosticTag:()=>wp,DocumentHighlight:()=>Wp,DocumentHighlightKind:()=>Kp,DocumentLink:()=>rm,DocumentSymbol:()=>Xp,DocumentUri:()=>$p,EOL:()=>x$,FoldingRange:()=>_p,FoldingRangeKind:()=>bp,FormattingOptions:()=>tm,Hover:()=>jp,InlayHint:()=>fm,InlayHintKind:()=>Sc,InlayHintLabelPart:()=>wc,InlineCompletionContext:()=>gm,InlineCompletionItem:()=>pm,InlineCompletionList:()=>mm,InlineCompletionTriggerKind:()=>hm,InlineValueContext:()=>cm,InlineValueEvaluatableExpression:()=>um,InlineValueText:()=>om,InlineValueVariableLookup:()=>lm,InsertReplaceEdit:()=>Mp,InsertTextFormat:()=>Lp,InsertTextMode:()=>xp,Location:()=>Wl,LocationLink:()=>Ap,MarkedString:()=>Yl,MarkupContent:()=>Ia,MarkupKind:()=>_c,OptionalVersionedTextDocumentIdentifier:()=>Hl,ParameterInformation:()=>Bp,Position:()=>oe,Range:()=>te,RenameFile:()=>Sa,SelectedCompletionInfo:()=>ym,SelectionRange:()=>nm,SemanticTokenModifiers:()=>im,SemanticTokenTypes:()=>am,SemanticTokens:()=>sm,SignatureInformation:()=>Up,StringValue:()=>dm,SymbolInformation:()=>Hp,SymbolKind:()=>Vp,SymbolTag:()=>qp,TextDocument:()=>Tm,TextDocumentEdit:()=>ql,TextDocumentIdentifier:()=>Np,TextDocumentItem:()=>kp,TextEdit:()=>ar,URI:()=>Ac,VersionedTextDocumentIdentifier:()=>Pp,WorkspaceChange:()=>M$,WorkspaceEdit:()=>bc,WorkspaceFolder:()=>vm,WorkspaceSymbol:()=>Yp,integer:()=>Rp,uinteger:()=>Kl});var $p,Ac,Rp,Kl,oe,te,Wl,Ap,Ec,Ep,Cp,bp,_p,Cc,Sp,wp,Ip,Vl,pn,ar,mn,et,Ar,ql,_a,Sa,wa,bc,kl,Ud,M$,Np,Pp,Hl,kp,_c,Ia,Op,Lp,Dp,Mp,xp,Gp,Fp,zp,Yl,jp,Bp,Up,Kp,Wp,Vp,qp,Hp,Yp,Xp,Jp,Xl,Zp,Qp,em,tm,rm,nm,am,im,sm,om,lm,um,cm,Sc,wc,fm,dm,pm,mm,hm,ym,gm,vm,x$,Tm,iv,C,Mu=vk({"../../node_modules/.pnpm/vscode-languageserver-types@3.17.5/node_modules/vscode-languageserver-types/lib/esm/main.js"(){var t,e,r,n;(function(a){function i(o){return typeof o=="string"}s(i,"is"),a.is=i})($p||($p={})),(function(a){function i(o){return typeof o=="string"}s(i,"is"),a.is=i})(Ac||(Ac={})),(function(a){a.MIN_VALUE=-2147483648,a.MAX_VALUE=2147483647;function i(o){return typeof o=="number"&&a.MIN_VALUE<=o&&o<=a.MAX_VALUE}s(i,"is"),a.is=i})(Rp||(Rp={})),(function(a){a.MIN_VALUE=0,a.MAX_VALUE=2147483647;function i(o){return typeof o=="number"&&a.MIN_VALUE<=o&&o<=a.MAX_VALUE}s(i,"is"),a.is=i})(Kl||(Kl={})),(function(a){function i(u,l){return u===Number.MAX_VALUE&&(u=Kl.MAX_VALUE),l===Number.MAX_VALUE&&(l=Kl.MAX_VALUE),{line:u,character:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&C.uinteger(l.line)&&C.uinteger(l.character)}s(o,"is"),a.is=o})(oe||(oe={})),(function(a){function i(u,l,c,f){if(C.uinteger(u)&&C.uinteger(l)&&C.uinteger(c)&&C.uinteger(f))return{start:oe.create(u,l),end:oe.create(c,f)};if(oe.is(u)&&oe.is(l))return{start:u,end:l};throw new Error(`Range#create called with invalid arguments[${u}, ${l}, ${c}, ${f}]`)}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&oe.is(l.start)&&oe.is(l.end)}s(o,"is"),a.is=o})(te||(te={})),(function(a){function i(u,l){return{uri:u,range:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&te.is(l.range)&&(C.string(l.uri)||C.undefined(l.uri))}s(o,"is"),a.is=o})(Wl||(Wl={})),(function(a){function i(u,l,c,f){return{targetUri:u,targetRange:l,targetSelectionRange:c,originSelectionRange:f}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&te.is(l.targetRange)&&C.string(l.targetUri)&&te.is(l.targetSelectionRange)&&(te.is(l.originSelectionRange)||C.undefined(l.originSelectionRange))}s(o,"is"),a.is=o})(Ap||(Ap={})),(function(a){function i(u,l,c,f){return{red:u,green:l,blue:c,alpha:f}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.numberRange(l.red,0,1)&&C.numberRange(l.green,0,1)&&C.numberRange(l.blue,0,1)&&C.numberRange(l.alpha,0,1)}s(o,"is"),a.is=o})(Ec||(Ec={})),(function(a){function i(u,l){return{range:u,color:l}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&te.is(l.range)&&Ec.is(l.color)}s(o,"is"),a.is=o})(Ep||(Ep={})),(function(a){function i(u,l,c){return{label:u,textEdit:l,additionalTextEdits:c}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.string(l.label)&&(C.undefined(l.textEdit)||ar.is(l))&&(C.undefined(l.additionalTextEdits)||C.typedArray(l.additionalTextEdits,ar.is))}s(o,"is"),a.is=o})(Cp||(Cp={})),(function(a){a.Comment="comment",a.Imports="imports",a.Region="region"})(bp||(bp={})),(function(a){function i(u,l,c,f,d,p){const h={startLine:u,endLine:l};return C.defined(c)&&(h.startCharacter=c),C.defined(f)&&(h.endCharacter=f),C.defined(d)&&(h.kind=d),C.defined(p)&&(h.collapsedText=p),h}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.uinteger(l.startLine)&&C.uinteger(l.startLine)&&(C.undefined(l.startCharacter)||C.uinteger(l.startCharacter))&&(C.undefined(l.endCharacter)||C.uinteger(l.endCharacter))&&(C.undefined(l.kind)||C.string(l.kind))}s(o,"is"),a.is=o})(_p||(_p={})),(function(a){function i(u,l){return{location:u,message:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&Wl.is(l.location)&&C.string(l.message)}s(o,"is"),a.is=o})(Cc||(Cc={})),(function(a){a.Error=1,a.Warning=2,a.Information=3,a.Hint=4})(Sp||(Sp={})),(function(a){a.Unnecessary=1,a.Deprecated=2})(wp||(wp={})),(function(a){function i(o){const u=o;return C.objectLiteral(u)&&C.string(u.href)}s(i,"is"),a.is=i})(Ip||(Ip={})),(function(a){function i(u,l,c,f,d,p){let h={range:u,message:l};return C.defined(c)&&(h.severity=c),C.defined(f)&&(h.code=f),C.defined(d)&&(h.source=d),C.defined(p)&&(h.relatedInformation=p),h}s(i,"create"),a.create=i;function o(u){var l;let c=u;return C.defined(c)&&te.is(c.range)&&C.string(c.message)&&(C.number(c.severity)||C.undefined(c.severity))&&(C.integer(c.code)||C.string(c.code)||C.undefined(c.code))&&(C.undefined(c.codeDescription)||C.string((l=c.codeDescription)===null||l===void 0?void 0:l.href))&&(C.string(c.source)||C.undefined(c.source))&&(C.undefined(c.relatedInformation)||C.typedArray(c.relatedInformation,Cc.is))}s(o,"is"),a.is=o})(Vl||(Vl={})),(function(a){function i(u,l,...c){let f={title:u,command:l};return C.defined(c)&&c.length>0&&(f.arguments=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.title)&&C.string(l.command)}s(o,"is"),a.is=o})(pn||(pn={})),(function(a){function i(c,f){return{range:c,newText:f}}s(i,"replace"),a.replace=i;function o(c,f){return{range:{start:c,end:c},newText:f}}s(o,"insert"),a.insert=o;function u(c){return{range:c,newText:""}}s(u,"del"),a.del=u;function l(c){const f=c;return C.objectLiteral(f)&&C.string(f.newText)&&te.is(f.range)}s(l,"is"),a.is=l})(ar||(ar={})),(function(a){function i(u,l,c){const f={label:u};return l!==void 0&&(f.needsConfirmation=l),c!==void 0&&(f.description=c),f}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.string(l.label)&&(C.boolean(l.needsConfirmation)||l.needsConfirmation===void 0)&&(C.string(l.description)||l.description===void 0)}s(o,"is"),a.is=o})(mn||(mn={})),(function(a){function i(o){const u=o;return C.string(u)}s(i,"is"),a.is=i})(et||(et={})),(function(a){function i(c,f,d){return{range:c,newText:f,annotationId:d}}s(i,"replace"),a.replace=i;function o(c,f,d){return{range:{start:c,end:c},newText:f,annotationId:d}}s(o,"insert"),a.insert=o;function u(c,f){return{range:c,newText:"",annotationId:f}}s(u,"del"),a.del=u;function l(c){const f=c;return ar.is(f)&&(mn.is(f.annotationId)||et.is(f.annotationId))}s(l,"is"),a.is=l})(Ar||(Ar={})),(function(a){function i(u,l){return{textDocument:u,edits:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&Hl.is(l.textDocument)&&Array.isArray(l.edits)}s(o,"is"),a.is=o})(ql||(ql={})),(function(a){function i(u,l,c){let f={kind:"create",uri:u};return l!==void 0&&(l.overwrite!==void 0||l.ignoreIfExists!==void 0)&&(f.options=l),c!==void 0&&(f.annotationId=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return l&&l.kind==="create"&&C.string(l.uri)&&(l.options===void 0||(l.options.overwrite===void 0||C.boolean(l.options.overwrite))&&(l.options.ignoreIfExists===void 0||C.boolean(l.options.ignoreIfExists)))&&(l.annotationId===void 0||et.is(l.annotationId))}s(o,"is"),a.is=o})(_a||(_a={})),(function(a){function i(u,l,c,f){let d={kind:"rename",oldUri:u,newUri:l};return c!==void 0&&(c.overwrite!==void 0||c.ignoreIfExists!==void 0)&&(d.options=c),f!==void 0&&(d.annotationId=f),d}s(i,"create"),a.create=i;function o(u){let l=u;return l&&l.kind==="rename"&&C.string(l.oldUri)&&C.string(l.newUri)&&(l.options===void 0||(l.options.overwrite===void 0||C.boolean(l.options.overwrite))&&(l.options.ignoreIfExists===void 0||C.boolean(l.options.ignoreIfExists)))&&(l.annotationId===void 0||et.is(l.annotationId))}s(o,"is"),a.is=o})(Sa||(Sa={})),(function(a){function i(u,l,c){let f={kind:"delete",uri:u};return l!==void 0&&(l.recursive!==void 0||l.ignoreIfNotExists!==void 0)&&(f.options=l),c!==void 0&&(f.annotationId=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return l&&l.kind==="delete"&&C.string(l.uri)&&(l.options===void 0||(l.options.recursive===void 0||C.boolean(l.options.recursive))&&(l.options.ignoreIfNotExists===void 0||C.boolean(l.options.ignoreIfNotExists)))&&(l.annotationId===void 0||et.is(l.annotationId))}s(o,"is"),a.is=o})(wa||(wa={})),(function(a){function i(o){let u=o;return u&&(u.changes!==void 0||u.documentChanges!==void 0)&&(u.documentChanges===void 0||u.documentChanges.every(l=>C.string(l.kind)?_a.is(l)||Sa.is(l)||wa.is(l):ql.is(l)))}s(i,"is"),a.is=i})(bc||(bc={})),kl=(t=class{constructor(i,o){this.edits=i,this.changeAnnotations=o}insert(i,o,u){let l,c;if(u===void 0?l=ar.insert(i,o):et.is(u)?(c=u,l=Ar.insert(i,o,u)):(this.assertChangeAnnotations(this.changeAnnotations),c=this.changeAnnotations.manage(u),l=Ar.insert(i,o,c)),this.edits.push(l),c!==void 0)return c}replace(i,o,u){let l,c;if(u===void 0?l=ar.replace(i,o):et.is(u)?(c=u,l=Ar.replace(i,o,u)):(this.assertChangeAnnotations(this.changeAnnotations),c=this.changeAnnotations.manage(u),l=Ar.replace(i,o,c)),this.edits.push(l),c!==void 0)return c}delete(i,o){let u,l;if(o===void 0?u=ar.del(i):et.is(o)?(l=o,u=Ar.del(i,o)):(this.assertChangeAnnotations(this.changeAnnotations),l=this.changeAnnotations.manage(o),u=Ar.del(i,l)),this.edits.push(u),l!==void 0)return l}add(i){this.edits.push(i)}all(){return this.edits}clear(){this.edits.splice(0,this.edits.length)}assertChangeAnnotations(i){if(i===void 0)throw new Error("Text edit change is not configured to manage change annotations.")}},s(t,"TextEditChangeImpl"),t),Ud=(e=class{constructor(i){this._annotations=i===void 0?Object.create(null):i,this._counter=0,this._size=0}all(){return this._annotations}get size(){return this._size}manage(i,o){let u;if(et.is(i)?u=i:(u=this.nextId(),o=i),this._annotations[u]!==void 0)throw new Error(`Id ${u} is already in use.`);if(o===void 0)throw new Error(`No annotation provided for id ${u}`);return this._annotations[u]=o,this._size++,u}nextId(){return this._counter++,this._counter.toString()}},s(e,"ChangeAnnotations"),e),M$=(r=class{constructor(i){this._textEditChanges=Object.create(null),i!==void 0?(this._workspaceEdit=i,i.documentChanges?(this._changeAnnotations=new Ud(i.changeAnnotations),i.changeAnnotations=this._changeAnnotations.all(),i.documentChanges.forEach(o=>{if(ql.is(o)){const u=new kl(o.edits,this._changeAnnotations);this._textEditChanges[o.textDocument.uri]=u}})):i.changes&&Object.keys(i.changes).forEach(o=>{const u=new kl(i.changes[o]);this._textEditChanges[o]=u})):this._workspaceEdit={}}get edit(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit}getTextEditChange(i){if(Hl.is(i)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");const o={uri:i.uri,version:i.version};let u=this._textEditChanges[o.uri];if(!u){const l=[],c={textDocument:o,edits:l};this._workspaceEdit.documentChanges.push(c),u=new kl(l,this._changeAnnotations),this._textEditChanges[o.uri]=u}return u}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw new Error("Workspace edit is not configured for normal text edit changes.");let o=this._textEditChanges[i];if(!o){let u=[];this._workspaceEdit.changes[i]=u,o=new kl(u),this._textEditChanges[i]=o}return o}}initDocumentChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new Ud,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())}initChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))}createFile(i,o,u){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let l;mn.is(o)||et.is(o)?l=o:u=o;let c,f;if(l===void 0?c=_a.create(i,u):(f=et.is(l)?l:this._changeAnnotations.manage(l),c=_a.create(i,u,f)),this._workspaceEdit.documentChanges.push(c),f!==void 0)return f}renameFile(i,o,u,l){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let c;mn.is(u)||et.is(u)?c=u:l=u;let f,d;if(c===void 0?f=Sa.create(i,o,l):(d=et.is(c)?c:this._changeAnnotations.manage(c),f=Sa.create(i,o,l,d)),this._workspaceEdit.documentChanges.push(f),d!==void 0)return d}deleteFile(i,o,u){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let l;mn.is(o)||et.is(o)?l=o:u=o;let c,f;if(l===void 0?c=wa.create(i,u):(f=et.is(l)?l:this._changeAnnotations.manage(l),c=wa.create(i,u,f)),this._workspaceEdit.documentChanges.push(c),f!==void 0)return f}},s(r,"WorkspaceChange"),r),(function(a){function i(u){return{uri:u}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)}s(o,"is"),a.is=o})(Np||(Np={})),(function(a){function i(u,l){return{uri:u,version:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)&&C.integer(l.version)}s(o,"is"),a.is=o})(Pp||(Pp={})),(function(a){function i(u,l){return{uri:u,version:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)&&(l.version===null||C.integer(l.version))}s(o,"is"),a.is=o})(Hl||(Hl={})),(function(a){function i(u,l,c,f){return{uri:u,languageId:l,version:c,text:f}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)&&C.string(l.languageId)&&C.integer(l.version)&&C.string(l.text)}s(o,"is"),a.is=o})(kp||(kp={})),(function(a){a.PlainText="plaintext",a.Markdown="markdown";function i(o){const u=o;return u===a.PlainText||u===a.Markdown}s(i,"is"),a.is=i})(_c||(_c={})),(function(a){function i(o){const u=o;return C.objectLiteral(o)&&_c.is(u.kind)&&C.string(u.value)}s(i,"is"),a.is=i})(Ia||(Ia={})),(function(a){a.Text=1,a.Method=2,a.Function=3,a.Constructor=4,a.Field=5,a.Variable=6,a.Class=7,a.Interface=8,a.Module=9,a.Property=10,a.Unit=11,a.Value=12,a.Enum=13,a.Keyword=14,a.Snippet=15,a.Color=16,a.File=17,a.Reference=18,a.Folder=19,a.EnumMember=20,a.Constant=21,a.Struct=22,a.Event=23,a.Operator=24,a.TypeParameter=25})(Op||(Op={})),(function(a){a.PlainText=1,a.Snippet=2})(Lp||(Lp={})),(function(a){a.Deprecated=1})(Dp||(Dp={})),(function(a){function i(u,l,c){return{newText:u,insert:l,replace:c}}s(i,"create"),a.create=i;function o(u){const l=u;return l&&C.string(l.newText)&&te.is(l.insert)&&te.is(l.replace)}s(o,"is"),a.is=o})(Mp||(Mp={})),(function(a){a.asIs=1,a.adjustIndentation=2})(xp||(xp={})),(function(a){function i(o){const u=o;return u&&(C.string(u.detail)||u.detail===void 0)&&(C.string(u.description)||u.description===void 0)}s(i,"is"),a.is=i})(Gp||(Gp={})),(function(a){function i(o){return{label:o}}s(i,"create"),a.create=i})(Fp||(Fp={})),(function(a){function i(o,u){return{items:o||[],isIncomplete:!!u}}s(i,"create"),a.create=i})(zp||(zp={})),(function(a){function i(u){return u.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}s(i,"fromPlainText"),a.fromPlainText=i;function o(u){const l=u;return C.string(l)||C.objectLiteral(l)&&C.string(l.language)&&C.string(l.value)}s(o,"is"),a.is=o})(Yl||(Yl={})),(function(a){function i(o){let u=o;return!!u&&C.objectLiteral(u)&&(Ia.is(u.contents)||Yl.is(u.contents)||C.typedArray(u.contents,Yl.is))&&(o.range===void 0||te.is(o.range))}s(i,"is"),a.is=i})(jp||(jp={})),(function(a){function i(o,u){return u?{label:o,documentation:u}:{label:o}}s(i,"create"),a.create=i})(Bp||(Bp={})),(function(a){function i(o,u,...l){let c={label:o};return C.defined(u)&&(c.documentation=u),C.defined(l)?c.parameters=l:c.parameters=[],c}s(i,"create"),a.create=i})(Up||(Up={})),(function(a){a.Text=1,a.Read=2,a.Write=3})(Kp||(Kp={})),(function(a){function i(o,u){let l={range:o};return C.number(u)&&(l.kind=u),l}s(i,"create"),a.create=i})(Wp||(Wp={})),(function(a){a.File=1,a.Module=2,a.Namespace=3,a.Package=4,a.Class=5,a.Method=6,a.Property=7,a.Field=8,a.Constructor=9,a.Enum=10,a.Interface=11,a.Function=12,a.Variable=13,a.Constant=14,a.String=15,a.Number=16,a.Boolean=17,a.Array=18,a.Object=19,a.Key=20,a.Null=21,a.EnumMember=22,a.Struct=23,a.Event=24,a.Operator=25,a.TypeParameter=26})(Vp||(Vp={})),(function(a){a.Deprecated=1})(qp||(qp={})),(function(a){function i(o,u,l,c,f){let d={name:o,kind:u,location:{uri:c,range:l}};return f&&(d.containerName=f),d}s(i,"create"),a.create=i})(Hp||(Hp={})),(function(a){function i(o,u,l,c){return c!==void 0?{name:o,kind:u,location:{uri:l,range:c}}:{name:o,kind:u,location:{uri:l}}}s(i,"create"),a.create=i})(Yp||(Yp={})),(function(a){function i(u,l,c,f,d,p){let h={name:u,detail:l,kind:c,range:f,selectionRange:d};return p!==void 0&&(h.children=p),h}s(i,"create"),a.create=i;function o(u){let l=u;return l&&C.string(l.name)&&C.number(l.kind)&&te.is(l.range)&&te.is(l.selectionRange)&&(l.detail===void 0||C.string(l.detail))&&(l.deprecated===void 0||C.boolean(l.deprecated))&&(l.children===void 0||Array.isArray(l.children))&&(l.tags===void 0||Array.isArray(l.tags))}s(o,"is"),a.is=o})(Xp||(Xp={})),(function(a){a.Empty="",a.QuickFix="quickfix",a.Refactor="refactor",a.RefactorExtract="refactor.extract",a.RefactorInline="refactor.inline",a.RefactorRewrite="refactor.rewrite",a.Source="source",a.SourceOrganizeImports="source.organizeImports",a.SourceFixAll="source.fixAll"})(Jp||(Jp={})),(function(a){a.Invoked=1,a.Automatic=2})(Xl||(Xl={})),(function(a){function i(u,l,c){let f={diagnostics:u};return l!=null&&(f.only=l),c!=null&&(f.triggerKind=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.typedArray(l.diagnostics,Vl.is)&&(l.only===void 0||C.typedArray(l.only,C.string))&&(l.triggerKind===void 0||l.triggerKind===Xl.Invoked||l.triggerKind===Xl.Automatic)}s(o,"is"),a.is=o})(Zp||(Zp={})),(function(a){function i(u,l,c){let f={title:u},d=!0;return typeof l=="string"?(d=!1,f.kind=l):pn.is(l)?f.command=l:f.edit=l,d&&c!==void 0&&(f.kind=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return l&&C.string(l.title)&&(l.diagnostics===void 0||C.typedArray(l.diagnostics,Vl.is))&&(l.kind===void 0||C.string(l.kind))&&(l.edit!==void 0||l.command!==void 0)&&(l.command===void 0||pn.is(l.command))&&(l.isPreferred===void 0||C.boolean(l.isPreferred))&&(l.edit===void 0||bc.is(l.edit))}s(o,"is"),a.is=o})(Qp||(Qp={})),(function(a){function i(u,l){let c={range:u};return C.defined(l)&&(c.data=l),c}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&te.is(l.range)&&(C.undefined(l.command)||pn.is(l.command))}s(o,"is"),a.is=o})(em||(em={})),(function(a){function i(u,l){return{tabSize:u,insertSpaces:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.uinteger(l.tabSize)&&C.boolean(l.insertSpaces)}s(o,"is"),a.is=o})(tm||(tm={})),(function(a){function i(u,l,c){return{range:u,target:l,data:c}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&te.is(l.range)&&(C.undefined(l.target)||C.string(l.target))}s(o,"is"),a.is=o})(rm||(rm={})),(function(a){function i(u,l){return{range:u,parent:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&te.is(l.range)&&(l.parent===void 0||a.is(l.parent))}s(o,"is"),a.is=o})(nm||(nm={})),(function(a){a.namespace="namespace",a.type="type",a.class="class",a.enum="enum",a.interface="interface",a.struct="struct",a.typeParameter="typeParameter",a.parameter="parameter",a.variable="variable",a.property="property",a.enumMember="enumMember",a.event="event",a.function="function",a.method="method",a.macro="macro",a.keyword="keyword",a.modifier="modifier",a.comment="comment",a.string="string",a.number="number",a.regexp="regexp",a.operator="operator",a.decorator="decorator"})(am||(am={})),(function(a){a.declaration="declaration",a.definition="definition",a.readonly="readonly",a.static="static",a.deprecated="deprecated",a.abstract="abstract",a.async="async",a.modification="modification",a.documentation="documentation",a.defaultLibrary="defaultLibrary"})(im||(im={})),(function(a){function i(o){const u=o;return C.objectLiteral(u)&&(u.resultId===void 0||typeof u.resultId=="string")&&Array.isArray(u.data)&&(u.data.length===0||typeof u.data[0]=="number")}s(i,"is"),a.is=i})(sm||(sm={})),(function(a){function i(u,l){return{range:u,text:l}}s(i,"create"),a.create=i;function o(u){const l=u;return l!=null&&te.is(l.range)&&C.string(l.text)}s(o,"is"),a.is=o})(om||(om={})),(function(a){function i(u,l,c){return{range:u,variableName:l,caseSensitiveLookup:c}}s(i,"create"),a.create=i;function o(u){const l=u;return l!=null&&te.is(l.range)&&C.boolean(l.caseSensitiveLookup)&&(C.string(l.variableName)||l.variableName===void 0)}s(o,"is"),a.is=o})(lm||(lm={})),(function(a){function i(u,l){return{range:u,expression:l}}s(i,"create"),a.create=i;function o(u){const l=u;return l!=null&&te.is(l.range)&&(C.string(l.expression)||l.expression===void 0)}s(o,"is"),a.is=o})(um||(um={})),(function(a){function i(u,l){return{frameId:u,stoppedLocation:l}}s(i,"create"),a.create=i;function o(u){const l=u;return C.defined(l)&&te.is(u.stoppedLocation)}s(o,"is"),a.is=o})(cm||(cm={})),(function(a){a.Type=1,a.Parameter=2;function i(o){return o===1||o===2}s(i,"is"),a.is=i})(Sc||(Sc={})),(function(a){function i(u){return{value:u}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&(l.tooltip===void 0||C.string(l.tooltip)||Ia.is(l.tooltip))&&(l.location===void 0||Wl.is(l.location))&&(l.command===void 0||pn.is(l.command))}s(o,"is"),a.is=o})(wc||(wc={})),(function(a){function i(u,l,c){const f={position:u,label:l};return c!==void 0&&(f.kind=c),f}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&oe.is(l.position)&&(C.string(l.label)||C.typedArray(l.label,wc.is))&&(l.kind===void 0||Sc.is(l.kind))&&l.textEdits===void 0||C.typedArray(l.textEdits,ar.is)&&(l.tooltip===void 0||C.string(l.tooltip)||Ia.is(l.tooltip))&&(l.paddingLeft===void 0||C.boolean(l.paddingLeft))&&(l.paddingRight===void 0||C.boolean(l.paddingRight))}s(o,"is"),a.is=o})(fm||(fm={})),(function(a){function i(o){return{kind:"snippet",value:o}}s(i,"createSnippet"),a.createSnippet=i})(dm||(dm={})),(function(a){function i(o,u,l,c){return{insertText:o,filterText:u,range:l,command:c}}s(i,"create"),a.create=i})(pm||(pm={})),(function(a){function i(o){return{items:o}}s(i,"create"),a.create=i})(mm||(mm={})),(function(a){a.Invoked=0,a.Automatic=1})(hm||(hm={})),(function(a){function i(o,u){return{range:o,text:u}}s(i,"create"),a.create=i})(ym||(ym={})),(function(a){function i(o,u){return{triggerKind:o,selectedCompletionInfo:u}}s(i,"create"),a.create=i})(gm||(gm={})),(function(a){function i(o){const u=o;return C.objectLiteral(u)&&Ac.is(u.uri)&&C.string(u.name)}s(i,"is"),a.is=i})(vm||(vm={})),x$=[` +var dk=Object.defineProperty;var pk=(t,e,r)=>e in t?dk(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Br=(t,e,r)=>pk(t,typeof e!="symbol"?e+"":e,r);import{a1 as ut}from"./index-DYMv5Ibu.js";var mk=Object.create,Du=Object.defineProperty,hk=Object.getOwnPropertyDescriptor,Th=Object.getOwnPropertyNames,yk=Object.getPrototypeOf,gk=Object.prototype.hasOwnProperty,s=(t,e)=>Du(t,"name",{value:e,configurable:!0}),vk=(t,e)=>function(){return t&&(e=(0,t[Th(t)[0]])(t=0)),e},X=(t,e)=>function(){return e||(0,t[Th(t)[0]])((e={exports:{}}).exports,e),e.exports},tn=(t,e)=>{for(var r in e)Du(t,r,{get:e[r],enumerable:!0})},$h=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Th(e))!gk.call(t,a)&&a!==r&&Du(t,a,{get:()=>e[a],enumerable:!(n=hk(e,a))||n.enumerable});return t},Of=(t,e,r)=>($h(t,e,"default"),r),Rh=(t,e,r)=>(r=t!=null?mk(yk(t)):{},$h(Du(r,"default",{value:t,enumerable:!0}),t)),Ah=t=>$h(Du({},"__esModule",{value:!0}),t),Lf={};tn(Lf,{AnnotatedTextEdit:()=>Ar,ChangeAnnotation:()=>mn,ChangeAnnotationIdentifier:()=>et,CodeAction:()=>Qp,CodeActionContext:()=>Zp,CodeActionKind:()=>Jp,CodeActionTriggerKind:()=>Xl,CodeDescription:()=>Ip,CodeLens:()=>em,Color:()=>Ec,ColorInformation:()=>Ep,ColorPresentation:()=>Cp,Command:()=>pn,CompletionItem:()=>Fp,CompletionItemKind:()=>Op,CompletionItemLabelDetails:()=>Gp,CompletionItemTag:()=>Dp,CompletionList:()=>zp,CreateFile:()=>_a,DeleteFile:()=>wa,Diagnostic:()=>Vl,DiagnosticRelatedInformation:()=>Cc,DiagnosticSeverity:()=>Sp,DiagnosticTag:()=>wp,DocumentHighlight:()=>Wp,DocumentHighlightKind:()=>Kp,DocumentLink:()=>rm,DocumentSymbol:()=>Xp,DocumentUri:()=>$p,EOL:()=>x$,FoldingRange:()=>_p,FoldingRangeKind:()=>bp,FormattingOptions:()=>tm,Hover:()=>jp,InlayHint:()=>fm,InlayHintKind:()=>Sc,InlayHintLabelPart:()=>wc,InlineCompletionContext:()=>gm,InlineCompletionItem:()=>pm,InlineCompletionList:()=>mm,InlineCompletionTriggerKind:()=>hm,InlineValueContext:()=>cm,InlineValueEvaluatableExpression:()=>um,InlineValueText:()=>om,InlineValueVariableLookup:()=>lm,InsertReplaceEdit:()=>Mp,InsertTextFormat:()=>Lp,InsertTextMode:()=>xp,Location:()=>Wl,LocationLink:()=>Ap,MarkedString:()=>Yl,MarkupContent:()=>Ia,MarkupKind:()=>_c,OptionalVersionedTextDocumentIdentifier:()=>Hl,ParameterInformation:()=>Bp,Position:()=>oe,Range:()=>te,RenameFile:()=>Sa,SelectedCompletionInfo:()=>ym,SelectionRange:()=>nm,SemanticTokenModifiers:()=>im,SemanticTokenTypes:()=>am,SemanticTokens:()=>sm,SignatureInformation:()=>Up,StringValue:()=>dm,SymbolInformation:()=>Hp,SymbolKind:()=>Vp,SymbolTag:()=>qp,TextDocument:()=>Tm,TextDocumentEdit:()=>ql,TextDocumentIdentifier:()=>Np,TextDocumentItem:()=>kp,TextEdit:()=>ar,URI:()=>Ac,VersionedTextDocumentIdentifier:()=>Pp,WorkspaceChange:()=>M$,WorkspaceEdit:()=>bc,WorkspaceFolder:()=>vm,WorkspaceSymbol:()=>Yp,integer:()=>Rp,uinteger:()=>Kl});var $p,Ac,Rp,Kl,oe,te,Wl,Ap,Ec,Ep,Cp,bp,_p,Cc,Sp,wp,Ip,Vl,pn,ar,mn,et,Ar,ql,_a,Sa,wa,bc,kl,Ud,M$,Np,Pp,Hl,kp,_c,Ia,Op,Lp,Dp,Mp,xp,Gp,Fp,zp,Yl,jp,Bp,Up,Kp,Wp,Vp,qp,Hp,Yp,Xp,Jp,Xl,Zp,Qp,em,tm,rm,nm,am,im,sm,om,lm,um,cm,Sc,wc,fm,dm,pm,mm,hm,ym,gm,vm,x$,Tm,iv,C,Mu=vk({"../../node_modules/.pnpm/vscode-languageserver-types@3.17.5/node_modules/vscode-languageserver-types/lib/esm/main.js"(){var t,e,r,n;(function(a){function i(o){return typeof o=="string"}s(i,"is"),a.is=i})($p||($p={})),(function(a){function i(o){return typeof o=="string"}s(i,"is"),a.is=i})(Ac||(Ac={})),(function(a){a.MIN_VALUE=-2147483648,a.MAX_VALUE=2147483647;function i(o){return typeof o=="number"&&a.MIN_VALUE<=o&&o<=a.MAX_VALUE}s(i,"is"),a.is=i})(Rp||(Rp={})),(function(a){a.MIN_VALUE=0,a.MAX_VALUE=2147483647;function i(o){return typeof o=="number"&&a.MIN_VALUE<=o&&o<=a.MAX_VALUE}s(i,"is"),a.is=i})(Kl||(Kl={})),(function(a){function i(u,l){return u===Number.MAX_VALUE&&(u=Kl.MAX_VALUE),l===Number.MAX_VALUE&&(l=Kl.MAX_VALUE),{line:u,character:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&C.uinteger(l.line)&&C.uinteger(l.character)}s(o,"is"),a.is=o})(oe||(oe={})),(function(a){function i(u,l,c,f){if(C.uinteger(u)&&C.uinteger(l)&&C.uinteger(c)&&C.uinteger(f))return{start:oe.create(u,l),end:oe.create(c,f)};if(oe.is(u)&&oe.is(l))return{start:u,end:l};throw new Error(`Range#create called with invalid arguments[${u}, ${l}, ${c}, ${f}]`)}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&oe.is(l.start)&&oe.is(l.end)}s(o,"is"),a.is=o})(te||(te={})),(function(a){function i(u,l){return{uri:u,range:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&te.is(l.range)&&(C.string(l.uri)||C.undefined(l.uri))}s(o,"is"),a.is=o})(Wl||(Wl={})),(function(a){function i(u,l,c,f){return{targetUri:u,targetRange:l,targetSelectionRange:c,originSelectionRange:f}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&te.is(l.targetRange)&&C.string(l.targetUri)&&te.is(l.targetSelectionRange)&&(te.is(l.originSelectionRange)||C.undefined(l.originSelectionRange))}s(o,"is"),a.is=o})(Ap||(Ap={})),(function(a){function i(u,l,c,f){return{red:u,green:l,blue:c,alpha:f}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.numberRange(l.red,0,1)&&C.numberRange(l.green,0,1)&&C.numberRange(l.blue,0,1)&&C.numberRange(l.alpha,0,1)}s(o,"is"),a.is=o})(Ec||(Ec={})),(function(a){function i(u,l){return{range:u,color:l}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&te.is(l.range)&&Ec.is(l.color)}s(o,"is"),a.is=o})(Ep||(Ep={})),(function(a){function i(u,l,c){return{label:u,textEdit:l,additionalTextEdits:c}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.string(l.label)&&(C.undefined(l.textEdit)||ar.is(l))&&(C.undefined(l.additionalTextEdits)||C.typedArray(l.additionalTextEdits,ar.is))}s(o,"is"),a.is=o})(Cp||(Cp={})),(function(a){a.Comment="comment",a.Imports="imports",a.Region="region"})(bp||(bp={})),(function(a){function i(u,l,c,f,d,p){const h={startLine:u,endLine:l};return C.defined(c)&&(h.startCharacter=c),C.defined(f)&&(h.endCharacter=f),C.defined(d)&&(h.kind=d),C.defined(p)&&(h.collapsedText=p),h}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.uinteger(l.startLine)&&C.uinteger(l.startLine)&&(C.undefined(l.startCharacter)||C.uinteger(l.startCharacter))&&(C.undefined(l.endCharacter)||C.uinteger(l.endCharacter))&&(C.undefined(l.kind)||C.string(l.kind))}s(o,"is"),a.is=o})(_p||(_p={})),(function(a){function i(u,l){return{location:u,message:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&Wl.is(l.location)&&C.string(l.message)}s(o,"is"),a.is=o})(Cc||(Cc={})),(function(a){a.Error=1,a.Warning=2,a.Information=3,a.Hint=4})(Sp||(Sp={})),(function(a){a.Unnecessary=1,a.Deprecated=2})(wp||(wp={})),(function(a){function i(o){const u=o;return C.objectLiteral(u)&&C.string(u.href)}s(i,"is"),a.is=i})(Ip||(Ip={})),(function(a){function i(u,l,c,f,d,p){let h={range:u,message:l};return C.defined(c)&&(h.severity=c),C.defined(f)&&(h.code=f),C.defined(d)&&(h.source=d),C.defined(p)&&(h.relatedInformation=p),h}s(i,"create"),a.create=i;function o(u){var l;let c=u;return C.defined(c)&&te.is(c.range)&&C.string(c.message)&&(C.number(c.severity)||C.undefined(c.severity))&&(C.integer(c.code)||C.string(c.code)||C.undefined(c.code))&&(C.undefined(c.codeDescription)||C.string((l=c.codeDescription)===null||l===void 0?void 0:l.href))&&(C.string(c.source)||C.undefined(c.source))&&(C.undefined(c.relatedInformation)||C.typedArray(c.relatedInformation,Cc.is))}s(o,"is"),a.is=o})(Vl||(Vl={})),(function(a){function i(u,l,...c){let f={title:u,command:l};return C.defined(c)&&c.length>0&&(f.arguments=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.title)&&C.string(l.command)}s(o,"is"),a.is=o})(pn||(pn={})),(function(a){function i(c,f){return{range:c,newText:f}}s(i,"replace"),a.replace=i;function o(c,f){return{range:{start:c,end:c},newText:f}}s(o,"insert"),a.insert=o;function u(c){return{range:c,newText:""}}s(u,"del"),a.del=u;function l(c){const f=c;return C.objectLiteral(f)&&C.string(f.newText)&&te.is(f.range)}s(l,"is"),a.is=l})(ar||(ar={})),(function(a){function i(u,l,c){const f={label:u};return l!==void 0&&(f.needsConfirmation=l),c!==void 0&&(f.description=c),f}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&C.string(l.label)&&(C.boolean(l.needsConfirmation)||l.needsConfirmation===void 0)&&(C.string(l.description)||l.description===void 0)}s(o,"is"),a.is=o})(mn||(mn={})),(function(a){function i(o){const u=o;return C.string(u)}s(i,"is"),a.is=i})(et||(et={})),(function(a){function i(c,f,d){return{range:c,newText:f,annotationId:d}}s(i,"replace"),a.replace=i;function o(c,f,d){return{range:{start:c,end:c},newText:f,annotationId:d}}s(o,"insert"),a.insert=o;function u(c,f){return{range:c,newText:"",annotationId:f}}s(u,"del"),a.del=u;function l(c){const f=c;return ar.is(f)&&(mn.is(f.annotationId)||et.is(f.annotationId))}s(l,"is"),a.is=l})(Ar||(Ar={})),(function(a){function i(u,l){return{textDocument:u,edits:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&Hl.is(l.textDocument)&&Array.isArray(l.edits)}s(o,"is"),a.is=o})(ql||(ql={})),(function(a){function i(u,l,c){let f={kind:"create",uri:u};return l!==void 0&&(l.overwrite!==void 0||l.ignoreIfExists!==void 0)&&(f.options=l),c!==void 0&&(f.annotationId=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return l&&l.kind==="create"&&C.string(l.uri)&&(l.options===void 0||(l.options.overwrite===void 0||C.boolean(l.options.overwrite))&&(l.options.ignoreIfExists===void 0||C.boolean(l.options.ignoreIfExists)))&&(l.annotationId===void 0||et.is(l.annotationId))}s(o,"is"),a.is=o})(_a||(_a={})),(function(a){function i(u,l,c,f){let d={kind:"rename",oldUri:u,newUri:l};return c!==void 0&&(c.overwrite!==void 0||c.ignoreIfExists!==void 0)&&(d.options=c),f!==void 0&&(d.annotationId=f),d}s(i,"create"),a.create=i;function o(u){let l=u;return l&&l.kind==="rename"&&C.string(l.oldUri)&&C.string(l.newUri)&&(l.options===void 0||(l.options.overwrite===void 0||C.boolean(l.options.overwrite))&&(l.options.ignoreIfExists===void 0||C.boolean(l.options.ignoreIfExists)))&&(l.annotationId===void 0||et.is(l.annotationId))}s(o,"is"),a.is=o})(Sa||(Sa={})),(function(a){function i(u,l,c){let f={kind:"delete",uri:u};return l!==void 0&&(l.recursive!==void 0||l.ignoreIfNotExists!==void 0)&&(f.options=l),c!==void 0&&(f.annotationId=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return l&&l.kind==="delete"&&C.string(l.uri)&&(l.options===void 0||(l.options.recursive===void 0||C.boolean(l.options.recursive))&&(l.options.ignoreIfNotExists===void 0||C.boolean(l.options.ignoreIfNotExists)))&&(l.annotationId===void 0||et.is(l.annotationId))}s(o,"is"),a.is=o})(wa||(wa={})),(function(a){function i(o){let u=o;return u&&(u.changes!==void 0||u.documentChanges!==void 0)&&(u.documentChanges===void 0||u.documentChanges.every(l=>C.string(l.kind)?_a.is(l)||Sa.is(l)||wa.is(l):ql.is(l)))}s(i,"is"),a.is=i})(bc||(bc={})),kl=(t=class{constructor(i,o){this.edits=i,this.changeAnnotations=o}insert(i,o,u){let l,c;if(u===void 0?l=ar.insert(i,o):et.is(u)?(c=u,l=Ar.insert(i,o,u)):(this.assertChangeAnnotations(this.changeAnnotations),c=this.changeAnnotations.manage(u),l=Ar.insert(i,o,c)),this.edits.push(l),c!==void 0)return c}replace(i,o,u){let l,c;if(u===void 0?l=ar.replace(i,o):et.is(u)?(c=u,l=Ar.replace(i,o,u)):(this.assertChangeAnnotations(this.changeAnnotations),c=this.changeAnnotations.manage(u),l=Ar.replace(i,o,c)),this.edits.push(l),c!==void 0)return c}delete(i,o){let u,l;if(o===void 0?u=ar.del(i):et.is(o)?(l=o,u=Ar.del(i,o)):(this.assertChangeAnnotations(this.changeAnnotations),l=this.changeAnnotations.manage(o),u=Ar.del(i,l)),this.edits.push(u),l!==void 0)return l}add(i){this.edits.push(i)}all(){return this.edits}clear(){this.edits.splice(0,this.edits.length)}assertChangeAnnotations(i){if(i===void 0)throw new Error("Text edit change is not configured to manage change annotations.")}},s(t,"TextEditChangeImpl"),t),Ud=(e=class{constructor(i){this._annotations=i===void 0?Object.create(null):i,this._counter=0,this._size=0}all(){return this._annotations}get size(){return this._size}manage(i,o){let u;if(et.is(i)?u=i:(u=this.nextId(),o=i),this._annotations[u]!==void 0)throw new Error(`Id ${u} is already in use.`);if(o===void 0)throw new Error(`No annotation provided for id ${u}`);return this._annotations[u]=o,this._size++,u}nextId(){return this._counter++,this._counter.toString()}},s(e,"ChangeAnnotations"),e),M$=(r=class{constructor(i){this._textEditChanges=Object.create(null),i!==void 0?(this._workspaceEdit=i,i.documentChanges?(this._changeAnnotations=new Ud(i.changeAnnotations),i.changeAnnotations=this._changeAnnotations.all(),i.documentChanges.forEach(o=>{if(ql.is(o)){const u=new kl(o.edits,this._changeAnnotations);this._textEditChanges[o.textDocument.uri]=u}})):i.changes&&Object.keys(i.changes).forEach(o=>{const u=new kl(i.changes[o]);this._textEditChanges[o]=u})):this._workspaceEdit={}}get edit(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit}getTextEditChange(i){if(Hl.is(i)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");const o={uri:i.uri,version:i.version};let u=this._textEditChanges[o.uri];if(!u){const l=[],c={textDocument:o,edits:l};this._workspaceEdit.documentChanges.push(c),u=new kl(l,this._changeAnnotations),this._textEditChanges[o.uri]=u}return u}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw new Error("Workspace edit is not configured for normal text edit changes.");let o=this._textEditChanges[i];if(!o){let u=[];this._workspaceEdit.changes[i]=u,o=new kl(u),this._textEditChanges[i]=o}return o}}initDocumentChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new Ud,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())}initChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))}createFile(i,o,u){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let l;mn.is(o)||et.is(o)?l=o:u=o;let c,f;if(l===void 0?c=_a.create(i,u):(f=et.is(l)?l:this._changeAnnotations.manage(l),c=_a.create(i,u,f)),this._workspaceEdit.documentChanges.push(c),f!==void 0)return f}renameFile(i,o,u,l){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let c;mn.is(u)||et.is(u)?c=u:l=u;let f,d;if(c===void 0?f=Sa.create(i,o,l):(d=et.is(c)?c:this._changeAnnotations.manage(c),f=Sa.create(i,o,l,d)),this._workspaceEdit.documentChanges.push(f),d!==void 0)return d}deleteFile(i,o,u){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let l;mn.is(o)||et.is(o)?l=o:u=o;let c,f;if(l===void 0?c=wa.create(i,u):(f=et.is(l)?l:this._changeAnnotations.manage(l),c=wa.create(i,u,f)),this._workspaceEdit.documentChanges.push(c),f!==void 0)return f}},s(r,"WorkspaceChange"),r),(function(a){function i(u){return{uri:u}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)}s(o,"is"),a.is=o})(Np||(Np={})),(function(a){function i(u,l){return{uri:u,version:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)&&C.integer(l.version)}s(o,"is"),a.is=o})(Pp||(Pp={})),(function(a){function i(u,l){return{uri:u,version:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)&&(l.version===null||C.integer(l.version))}s(o,"is"),a.is=o})(Hl||(Hl={})),(function(a){function i(u,l,c,f){return{uri:u,languageId:l,version:c,text:f}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.string(l.uri)&&C.string(l.languageId)&&C.integer(l.version)&&C.string(l.text)}s(o,"is"),a.is=o})(kp||(kp={})),(function(a){a.PlainText="plaintext",a.Markdown="markdown";function i(o){const u=o;return u===a.PlainText||u===a.Markdown}s(i,"is"),a.is=i})(_c||(_c={})),(function(a){function i(o){const u=o;return C.objectLiteral(o)&&_c.is(u.kind)&&C.string(u.value)}s(i,"is"),a.is=i})(Ia||(Ia={})),(function(a){a.Text=1,a.Method=2,a.Function=3,a.Constructor=4,a.Field=5,a.Variable=6,a.Class=7,a.Interface=8,a.Module=9,a.Property=10,a.Unit=11,a.Value=12,a.Enum=13,a.Keyword=14,a.Snippet=15,a.Color=16,a.File=17,a.Reference=18,a.Folder=19,a.EnumMember=20,a.Constant=21,a.Struct=22,a.Event=23,a.Operator=24,a.TypeParameter=25})(Op||(Op={})),(function(a){a.PlainText=1,a.Snippet=2})(Lp||(Lp={})),(function(a){a.Deprecated=1})(Dp||(Dp={})),(function(a){function i(u,l,c){return{newText:u,insert:l,replace:c}}s(i,"create"),a.create=i;function o(u){const l=u;return l&&C.string(l.newText)&&te.is(l.insert)&&te.is(l.replace)}s(o,"is"),a.is=o})(Mp||(Mp={})),(function(a){a.asIs=1,a.adjustIndentation=2})(xp||(xp={})),(function(a){function i(o){const u=o;return u&&(C.string(u.detail)||u.detail===void 0)&&(C.string(u.description)||u.description===void 0)}s(i,"is"),a.is=i})(Gp||(Gp={})),(function(a){function i(o){return{label:o}}s(i,"create"),a.create=i})(Fp||(Fp={})),(function(a){function i(o,u){return{items:o||[],isIncomplete:!!u}}s(i,"create"),a.create=i})(zp||(zp={})),(function(a){function i(u){return u.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}s(i,"fromPlainText"),a.fromPlainText=i;function o(u){const l=u;return C.string(l)||C.objectLiteral(l)&&C.string(l.language)&&C.string(l.value)}s(o,"is"),a.is=o})(Yl||(Yl={})),(function(a){function i(o){let u=o;return!!u&&C.objectLiteral(u)&&(Ia.is(u.contents)||Yl.is(u.contents)||C.typedArray(u.contents,Yl.is))&&(o.range===void 0||te.is(o.range))}s(i,"is"),a.is=i})(jp||(jp={})),(function(a){function i(o,u){return u?{label:o,documentation:u}:{label:o}}s(i,"create"),a.create=i})(Bp||(Bp={})),(function(a){function i(o,u,...l){let c={label:o};return C.defined(u)&&(c.documentation=u),C.defined(l)?c.parameters=l:c.parameters=[],c}s(i,"create"),a.create=i})(Up||(Up={})),(function(a){a.Text=1,a.Read=2,a.Write=3})(Kp||(Kp={})),(function(a){function i(o,u){let l={range:o};return C.number(u)&&(l.kind=u),l}s(i,"create"),a.create=i})(Wp||(Wp={})),(function(a){a.File=1,a.Module=2,a.Namespace=3,a.Package=4,a.Class=5,a.Method=6,a.Property=7,a.Field=8,a.Constructor=9,a.Enum=10,a.Interface=11,a.Function=12,a.Variable=13,a.Constant=14,a.String=15,a.Number=16,a.Boolean=17,a.Array=18,a.Object=19,a.Key=20,a.Null=21,a.EnumMember=22,a.Struct=23,a.Event=24,a.Operator=25,a.TypeParameter=26})(Vp||(Vp={})),(function(a){a.Deprecated=1})(qp||(qp={})),(function(a){function i(o,u,l,c,f){let d={name:o,kind:u,location:{uri:c,range:l}};return f&&(d.containerName=f),d}s(i,"create"),a.create=i})(Hp||(Hp={})),(function(a){function i(o,u,l,c){return c!==void 0?{name:o,kind:u,location:{uri:l,range:c}}:{name:o,kind:u,location:{uri:l}}}s(i,"create"),a.create=i})(Yp||(Yp={})),(function(a){function i(u,l,c,f,d,p){let h={name:u,detail:l,kind:c,range:f,selectionRange:d};return p!==void 0&&(h.children=p),h}s(i,"create"),a.create=i;function o(u){let l=u;return l&&C.string(l.name)&&C.number(l.kind)&&te.is(l.range)&&te.is(l.selectionRange)&&(l.detail===void 0||C.string(l.detail))&&(l.deprecated===void 0||C.boolean(l.deprecated))&&(l.children===void 0||Array.isArray(l.children))&&(l.tags===void 0||Array.isArray(l.tags))}s(o,"is"),a.is=o})(Xp||(Xp={})),(function(a){a.Empty="",a.QuickFix="quickfix",a.Refactor="refactor",a.RefactorExtract="refactor.extract",a.RefactorInline="refactor.inline",a.RefactorRewrite="refactor.rewrite",a.Source="source",a.SourceOrganizeImports="source.organizeImports",a.SourceFixAll="source.fixAll"})(Jp||(Jp={})),(function(a){a.Invoked=1,a.Automatic=2})(Xl||(Xl={})),(function(a){function i(u,l,c){let f={diagnostics:u};return l!=null&&(f.only=l),c!=null&&(f.triggerKind=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.typedArray(l.diagnostics,Vl.is)&&(l.only===void 0||C.typedArray(l.only,C.string))&&(l.triggerKind===void 0||l.triggerKind===Xl.Invoked||l.triggerKind===Xl.Automatic)}s(o,"is"),a.is=o})(Zp||(Zp={})),(function(a){function i(u,l,c){let f={title:u},d=!0;return typeof l=="string"?(d=!1,f.kind=l):pn.is(l)?f.command=l:f.edit=l,d&&c!==void 0&&(f.kind=c),f}s(i,"create"),a.create=i;function o(u){let l=u;return l&&C.string(l.title)&&(l.diagnostics===void 0||C.typedArray(l.diagnostics,Vl.is))&&(l.kind===void 0||C.string(l.kind))&&(l.edit!==void 0||l.command!==void 0)&&(l.command===void 0||pn.is(l.command))&&(l.isPreferred===void 0||C.boolean(l.isPreferred))&&(l.edit===void 0||bc.is(l.edit))}s(o,"is"),a.is=o})(Qp||(Qp={})),(function(a){function i(u,l){let c={range:u};return C.defined(l)&&(c.data=l),c}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&te.is(l.range)&&(C.undefined(l.command)||pn.is(l.command))}s(o,"is"),a.is=o})(em||(em={})),(function(a){function i(u,l){return{tabSize:u,insertSpaces:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&C.uinteger(l.tabSize)&&C.boolean(l.insertSpaces)}s(o,"is"),a.is=o})(tm||(tm={})),(function(a){function i(u,l,c){return{range:u,target:l,data:c}}s(i,"create"),a.create=i;function o(u){let l=u;return C.defined(l)&&te.is(l.range)&&(C.undefined(l.target)||C.string(l.target))}s(o,"is"),a.is=o})(rm||(rm={})),(function(a){function i(u,l){return{range:u,parent:l}}s(i,"create"),a.create=i;function o(u){let l=u;return C.objectLiteral(l)&&te.is(l.range)&&(l.parent===void 0||a.is(l.parent))}s(o,"is"),a.is=o})(nm||(nm={})),(function(a){a.namespace="namespace",a.type="type",a.class="class",a.enum="enum",a.interface="interface",a.struct="struct",a.typeParameter="typeParameter",a.parameter="parameter",a.variable="variable",a.property="property",a.enumMember="enumMember",a.event="event",a.function="function",a.method="method",a.macro="macro",a.keyword="keyword",a.modifier="modifier",a.comment="comment",a.string="string",a.number="number",a.regexp="regexp",a.operator="operator",a.decorator="decorator"})(am||(am={})),(function(a){a.declaration="declaration",a.definition="definition",a.readonly="readonly",a.static="static",a.deprecated="deprecated",a.abstract="abstract",a.async="async",a.modification="modification",a.documentation="documentation",a.defaultLibrary="defaultLibrary"})(im||(im={})),(function(a){function i(o){const u=o;return C.objectLiteral(u)&&(u.resultId===void 0||typeof u.resultId=="string")&&Array.isArray(u.data)&&(u.data.length===0||typeof u.data[0]=="number")}s(i,"is"),a.is=i})(sm||(sm={})),(function(a){function i(u,l){return{range:u,text:l}}s(i,"create"),a.create=i;function o(u){const l=u;return l!=null&&te.is(l.range)&&C.string(l.text)}s(o,"is"),a.is=o})(om||(om={})),(function(a){function i(u,l,c){return{range:u,variableName:l,caseSensitiveLookup:c}}s(i,"create"),a.create=i;function o(u){const l=u;return l!=null&&te.is(l.range)&&C.boolean(l.caseSensitiveLookup)&&(C.string(l.variableName)||l.variableName===void 0)}s(o,"is"),a.is=o})(lm||(lm={})),(function(a){function i(u,l){return{range:u,expression:l}}s(i,"create"),a.create=i;function o(u){const l=u;return l!=null&&te.is(l.range)&&(C.string(l.expression)||l.expression===void 0)}s(o,"is"),a.is=o})(um||(um={})),(function(a){function i(u,l){return{frameId:u,stoppedLocation:l}}s(i,"create"),a.create=i;function o(u){const l=u;return C.defined(l)&&te.is(u.stoppedLocation)}s(o,"is"),a.is=o})(cm||(cm={})),(function(a){a.Type=1,a.Parameter=2;function i(o){return o===1||o===2}s(i,"is"),a.is=i})(Sc||(Sc={})),(function(a){function i(u){return{value:u}}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&(l.tooltip===void 0||C.string(l.tooltip)||Ia.is(l.tooltip))&&(l.location===void 0||Wl.is(l.location))&&(l.command===void 0||pn.is(l.command))}s(o,"is"),a.is=o})(wc||(wc={})),(function(a){function i(u,l,c){const f={position:u,label:l};return c!==void 0&&(f.kind=c),f}s(i,"create"),a.create=i;function o(u){const l=u;return C.objectLiteral(l)&&oe.is(l.position)&&(C.string(l.label)||C.typedArray(l.label,wc.is))&&(l.kind===void 0||Sc.is(l.kind))&&l.textEdits===void 0||C.typedArray(l.textEdits,ar.is)&&(l.tooltip===void 0||C.string(l.tooltip)||Ia.is(l.tooltip))&&(l.paddingLeft===void 0||C.boolean(l.paddingLeft))&&(l.paddingRight===void 0||C.boolean(l.paddingRight))}s(o,"is"),a.is=o})(fm||(fm={})),(function(a){function i(o){return{kind:"snippet",value:o}}s(i,"createSnippet"),a.createSnippet=i})(dm||(dm={})),(function(a){function i(o,u,l,c){return{insertText:o,filterText:u,range:l,command:c}}s(i,"create"),a.create=i})(pm||(pm={})),(function(a){function i(o){return{items:o}}s(i,"create"),a.create=i})(mm||(mm={})),(function(a){a.Invoked=0,a.Automatic=1})(hm||(hm={})),(function(a){function i(o,u){return{range:o,text:u}}s(i,"create"),a.create=i})(ym||(ym={})),(function(a){function i(o,u){return{triggerKind:o,selectedCompletionInfo:u}}s(i,"create"),a.create=i})(gm||(gm={})),(function(a){function i(o){const u=o;return C.objectLiteral(u)&&Ac.is(u.uri)&&C.string(u.name)}s(i,"is"),a.is=i})(vm||(vm={})),x$=[` `,`\r `,"\r"],(function(a){function i(c,f,d,p){return new iv(c,f,d,p)}s(i,"create"),a.create=i;function o(c){let f=c;return!!(C.defined(f)&&C.string(f.uri)&&(C.undefined(f.languageId)||C.string(f.languageId))&&C.uinteger(f.lineCount)&&C.func(f.getText)&&C.func(f.positionAt)&&C.func(f.offsetAt))}s(o,"is"),a.is=o;function u(c,f){let d=c.getText(),p=l(f,(y,v)=>{let E=y.range.start.line-v.range.start.line;return E===0?y.range.start.character-v.range.start.character:E}),h=d.length;for(let y=p.length-1;y>=0;y--){let v=p[y],E=c.offsetAt(v.range.start),T=c.offsetAt(v.range.end);if(T<=h)d=d.substring(0,E)+v.newText+d.substring(T,d.length);else throw new Error("Overlapping edit");h=E}return d}s(u,"applyEdits"),a.applyEdits=u;function l(c,f){if(c.length<=1)return c;const d=c.length/2|0,p=c.slice(0,d),h=c.slice(d);l(p,f),l(h,f);let y=0,v=0,E=0;for(;y({domains:new Map,transitions:[]}),"createDefaultData"),H=rt(),St=i(()=>H.domains,"getDomains"),Mt=i(()=>H.transitions,"getTransitions"),zt=i(t=>{if(t)for(const e of t){const n=e.domain,a=(e.items??[]).map(c=>({label:c.label}));H.domains.set(n,{name:n,items:a})}},"setDomains"),Lt=i(t=>{t&&(H.transitions=t.filter(e=>e.from===e.to?(O.warn(`Cynefin: self-loop transition on domain "${e.from}" is not meaningful and will be skipped.`),!1):!0).map(e=>({from:e.from,to:e.to,label:e.label||void 0})))},"setTransitions"),Nt=i(()=>U({...Tt.cynefin,...Q().cynefin}),"getConfig"),Pt=i(()=>{At(),H=rt()},"clear"),Y={getDomains:St,getTransitions:Mt,setDomains:zt,setTransitions:Lt,getConfig:Nt,clear:Pt,setAccTitle:vt,getAccTitle:wt,setDiagramTitle:Ct,getDiagramTitle:bt,getAccDescription:$t,setAccDescription:gt},It=i(t=>{ht(t,Y),Y.setDomains(t.domains),Y.setTransitions(t.transitions)},"populate"),Wt={parse:i(async t=>{const e=await Bt("cynefin",t);O.debug(e),It(e)},"parse")};function V(t){let e=t+1831565813|0;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}i(V,"seededRandom");function it(t){let e=0;for(let n=0;n{const n=t/2,a=e/2;return{complex:{cx:n/2,cy:a/2,x:0,y:0,w:n,h:a},complicated:{cx:n+n/2,cy:a/2,x:n,y:0,w:n,h:a},chaotic:{cx:n/2,cy:a+a/2,x:0,y:a,w:n,h:a},clear:{cx:n+n/2,cy:a+a/2,x:n,y:a,w:n,h:a},confusion:{cx:n,cy:a,x:n*.7,y:a*.7,w:n*.6,h:a*.6}}},"getDomainLayouts"),_t=i(()=>{const t=ot(),e=Q();return U(t,e.themeVariables).cynefin},"getCynefinDomainColors"),q=3,Et=i((t,e,n,a)=>{const c=a.db,m=c.getDomains(),v=c.getTransitions(),W=c.getDiagramTitle(),d=c.getAccTitle(),D=c.getAccDescription(),o=c.getConfig(),p=_t();O.debug("Rendering Cynefin diagram");const s=o.width,f=o.height,b=o.padding,x=o.showDomainDescriptions,R=o.boundaryAmplitude,_=s+b*2,E=f+b*2,z={complex:p.complexBg,complicated:p.complicatedBg,clear:p.clearBg,chaotic:p.chaoticBg,confusion:p.confusionBg},k=Dt(e);kt(k,E,_,o.useMaxWidth??!0),k.attr("viewBox",`0 0 ${_} ${E}`),d&&k.append("title").text(d),D&&k.append("desc").text(D);const A=k.append("g").attr("transform",`translate(${b}, ${b})`),F=Rt(s,f),Z=st(o.seed,e),mt=A.append("g").attr("class","cynefin-backgrounds"),X=["complex","complicated","chaotic","clear"];for(const l of X){const r=F[l];mt.append("rect").attr("class","cynefinDomain").attr("x",r.x).attr("y",r.y).attr("width",r.w).attr("height",r.h).attr("fill",z[l]).attr("fill-opacity",.4).attr("stroke","none")}const j=A.append("g").attr("class","cynefin-boundaries");j.append("path").attr("class","cynefinBoundary").attr("d",ct(s,f,Z,R)).attr("fill","none"),j.append("path").attr("class","cynefinBoundary").attr("d",lt(s,f,Z+100,R)).attr("fill","none"),j.append("path").attr("class","cynefinCliff").attr("d",dt(s,f)).attr("fill","none");const pt=s*.15,yt=f*.15;A.append("path").attr("class","cynefinConfusion").attr("d",ft(s/2,f/2,pt,yt)).attr("fill",z.confusion).attr("fill-opacity",.5);const J=A.append("g").attr("class","cynefin-labels");for(const l of X){const r=F[l];J.append("text").attr("class","cynefinDomainLabel").attr("x",r.cx).attr("y",x?r.cy-30:r.cy).attr("text-anchor","middle").attr("dominant-baseline","middle").text(l.charAt(0).toUpperCase()+l.slice(1))}if(J.append("text").attr("class","cynefinDomainLabel").attr("x",s/2).attr("y",x?f/2-10:f/2).attr("text-anchor","middle").attr("dominant-baseline","middle").text("Confusion"),x){const l=A.append("g").attr("class","cynefin-subtitles");for(const r of X){const u=F[r],y=at[r];l.append("text").attr("class","cynefinSubtitle").attr("x",u.cx).attr("y",u.cy-10).attr("text-anchor","middle").attr("dominant-baseline","middle").text(y.model),l.append("text").attr("class","cynefinSubtitle").attr("x",u.cx).attr("y",u.cy+5).attr("text-anchor","middle").attr("dominant-baseline","middle").text(y.practice)}l.append("text").attr("class","cynefinSubtitle").attr("x",s/2).attr("y",f/2+8).attr("text-anchor","middle").attr("dominant-baseline","middle").text(at.confusion.practice)}const K=A.append("g").attr("class","cynefin-items"),T=26,tt=10,ut=["complex","complicated","chaotic","clear","confusion"];for(const l of ut){const r=m.get(l);if(!r||r.items.length===0)continue;const u=F[l],y=l==="confusion";let L=r.items,N=0;y&&r.items.length>q&&(N=r.items.length-q,L=r.items.slice(0,q));let B;if(y){const g=x?22:14;B=u.cy+g}else B=u.cy+(x?25:15);if([...L].forEach((g,S)=>{const C=B+S*(T+4),M=K.append("g"),P=M.append("text").attr("class","cynefinItemText").attr("x",0).attr("y",T/2).attr("text-anchor","middle").attr("dominant-baseline","central").text(g.label);let $=g.label.length*7;const h=P.node();if(h&&typeof h.getBBox=="function"){const G=h.getBBox();G.width>0&&($=G.width)}const w=$+tt*2,I=u.cx-w/2;M.attr("transform",`translate(${I}, ${C})`),M.insert("rect","text").attr("class","cynefinItem").attr("x",0).attr("y",0).attr("width",w).attr("height",T).attr("rx",4).attr("ry",4).attr("fill",z[l]).attr("fill-opacity",.95),P.attr("x",w/2).attr("y",T/2)}),N>0){const g=B+L.length*(T+4),S=`+${N} more`,C=K.append("g"),M=C.append("text").attr("class","cynefinItemText").attr("x",0).attr("y",T/2).attr("text-anchor","middle").attr("dominant-baseline","central").text(S);let P=S.length*7;const $=M.node();if($&&typeof $.getBBox=="function"){const I=$.getBBox();I.width>0&&(P=I.width)}const h=P+tt*2,w=u.cx-h/2;C.attr("transform",`translate(${w}, ${g})`),C.insert("rect","text").attr("class","cynefinItemOverflow").attr("x",0).attr("y",0).attr("width",h).attr("height",T).attr("rx",4).attr("ry",4).attr("fill",z[l]).attr("fill-opacity",.6),M.attr("x",h/2).attr("y",T/2)}}if(v.length>0){const l=k.select("defs").empty()?k.append("defs"):k.select("defs"),r=`cynefin-arrow-${e}`;l.append("marker").attr("id",r).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerWidth",6).attr("markerHeight",6).attr("orient","auto-start-reverse").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","cynefinArrowHead");const u=A.append("g").attr("class","cynefin-arrows");v.forEach(y=>{const L=F[y.from],N=F[y.to];if(!L||!N)return;if(y.from===y.to){O.warn(`Cynefin renderer: skipping self-loop on domain "${y.from}"`);return}const B=L.cx,g=L.cy,S=N.cx,C=N.cy,M=(B+S)/2,P=(g+C)/2,$=S-B,h=C-g,w=Math.sqrt($*$+h*h),I=w*.15,G=-h/w,xt=$/w,et=M+G*I,nt=P+xt*I;u.append("path").attr("class","cynefinArrowLine").attr("d",`M${B},${g} Q${et},${nt} ${S},${C}`).attr("fill","none").attr("marker-end",`url(#${r})`),y.label&&u.append("text").attr("class","cynefinArrowLabel").attr("x",et).attr("y",nt-6).attr("text-anchor","middle").attr("dominant-baseline","auto").text(y.label)})}W&&A.append("text").attr("class","cynefinTitle").attr("x",s/2).attr("y",-b/2).attr("text-anchor","middle").attr("dominant-baseline","middle").text(W)},"draw"),Ft={draw:Et},Vt=i(()=>{const t=ot(),e=Q();return U(t,e.themeVariables).cynefin},"getCynefinTheme"),Ht=i(()=>{const t=Vt();return` +import{p as ht}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{s as gt,g as $t,n as bt,m as Ct,a as wt,b as vt,_ as i,l as O,C as Dt,d as kt,o as At,z as U,x as Q,A as Tt,E as ot}from"./mermaid.core-BRmiRRt4.js";import{p as Bt}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import"./index-DYMv5Ibu.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var rt=i(()=>({domains:new Map,transitions:[]}),"createDefaultData"),H=rt(),St=i(()=>H.domains,"getDomains"),Mt=i(()=>H.transitions,"getTransitions"),zt=i(t=>{if(t)for(const e of t){const n=e.domain,a=(e.items??[]).map(c=>({label:c.label}));H.domains.set(n,{name:n,items:a})}},"setDomains"),Lt=i(t=>{t&&(H.transitions=t.filter(e=>e.from===e.to?(O.warn(`Cynefin: self-loop transition on domain "${e.from}" is not meaningful and will be skipped.`),!1):!0).map(e=>({from:e.from,to:e.to,label:e.label||void 0})))},"setTransitions"),Nt=i(()=>U({...Tt.cynefin,...Q().cynefin}),"getConfig"),Pt=i(()=>{At(),H=rt()},"clear"),Y={getDomains:St,getTransitions:Mt,setDomains:zt,setTransitions:Lt,getConfig:Nt,clear:Pt,setAccTitle:vt,getAccTitle:wt,setDiagramTitle:Ct,getDiagramTitle:bt,getAccDescription:$t,setAccDescription:gt},It=i(t=>{ht(t,Y),Y.setDomains(t.domains),Y.setTransitions(t.transitions)},"populate"),Wt={parse:i(async t=>{const e=await Bt("cynefin",t);O.debug(e),It(e)},"parse")};function V(t){let e=t+1831565813|0;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}i(V,"seededRandom");function it(t){let e=0;for(let n=0;n{const n=t/2,a=e/2;return{complex:{cx:n/2,cy:a/2,x:0,y:0,w:n,h:a},complicated:{cx:n+n/2,cy:a/2,x:n,y:0,w:n,h:a},chaotic:{cx:n/2,cy:a+a/2,x:0,y:a,w:n,h:a},clear:{cx:n+n/2,cy:a+a/2,x:n,y:a,w:n,h:a},confusion:{cx:n,cy:a,x:n*.7,y:a*.7,w:n*.6,h:a*.6}}},"getDomainLayouts"),_t=i(()=>{const t=ot(),e=Q();return U(t,e.themeVariables).cynefin},"getCynefinDomainColors"),q=3,Et=i((t,e,n,a)=>{const c=a.db,m=c.getDomains(),v=c.getTransitions(),W=c.getDiagramTitle(),d=c.getAccTitle(),D=c.getAccDescription(),o=c.getConfig(),p=_t();O.debug("Rendering Cynefin diagram");const s=o.width,f=o.height,b=o.padding,x=o.showDomainDescriptions,R=o.boundaryAmplitude,_=s+b*2,E=f+b*2,z={complex:p.complexBg,complicated:p.complicatedBg,clear:p.clearBg,chaotic:p.chaoticBg,confusion:p.confusionBg},k=Dt(e);kt(k,E,_,o.useMaxWidth??!0),k.attr("viewBox",`0 0 ${_} ${E}`),d&&k.append("title").text(d),D&&k.append("desc").text(D);const A=k.append("g").attr("transform",`translate(${b}, ${b})`),F=Rt(s,f),Z=st(o.seed,e),mt=A.append("g").attr("class","cynefin-backgrounds"),X=["complex","complicated","chaotic","clear"];for(const l of X){const r=F[l];mt.append("rect").attr("class","cynefinDomain").attr("x",r.x).attr("y",r.y).attr("width",r.w).attr("height",r.h).attr("fill",z[l]).attr("fill-opacity",.4).attr("stroke","none")}const j=A.append("g").attr("class","cynefin-boundaries");j.append("path").attr("class","cynefinBoundary").attr("d",ct(s,f,Z,R)).attr("fill","none"),j.append("path").attr("class","cynefinBoundary").attr("d",lt(s,f,Z+100,R)).attr("fill","none"),j.append("path").attr("class","cynefinCliff").attr("d",dt(s,f)).attr("fill","none");const pt=s*.15,yt=f*.15;A.append("path").attr("class","cynefinConfusion").attr("d",ft(s/2,f/2,pt,yt)).attr("fill",z.confusion).attr("fill-opacity",.5);const J=A.append("g").attr("class","cynefin-labels");for(const l of X){const r=F[l];J.append("text").attr("class","cynefinDomainLabel").attr("x",r.cx).attr("y",x?r.cy-30:r.cy).attr("text-anchor","middle").attr("dominant-baseline","middle").text(l.charAt(0).toUpperCase()+l.slice(1))}if(J.append("text").attr("class","cynefinDomainLabel").attr("x",s/2).attr("y",x?f/2-10:f/2).attr("text-anchor","middle").attr("dominant-baseline","middle").text("Confusion"),x){const l=A.append("g").attr("class","cynefin-subtitles");for(const r of X){const u=F[r],y=at[r];l.append("text").attr("class","cynefinSubtitle").attr("x",u.cx).attr("y",u.cy-10).attr("text-anchor","middle").attr("dominant-baseline","middle").text(y.model),l.append("text").attr("class","cynefinSubtitle").attr("x",u.cx).attr("y",u.cy+5).attr("text-anchor","middle").attr("dominant-baseline","middle").text(y.practice)}l.append("text").attr("class","cynefinSubtitle").attr("x",s/2).attr("y",f/2+8).attr("text-anchor","middle").attr("dominant-baseline","middle").text(at.confusion.practice)}const K=A.append("g").attr("class","cynefin-items"),T=26,tt=10,ut=["complex","complicated","chaotic","clear","confusion"];for(const l of ut){const r=m.get(l);if(!r||r.items.length===0)continue;const u=F[l],y=l==="confusion";let L=r.items,N=0;y&&r.items.length>q&&(N=r.items.length-q,L=r.items.slice(0,q));let B;if(y){const g=x?22:14;B=u.cy+g}else B=u.cy+(x?25:15);if([...L].forEach((g,S)=>{const C=B+S*(T+4),M=K.append("g"),P=M.append("text").attr("class","cynefinItemText").attr("x",0).attr("y",T/2).attr("text-anchor","middle").attr("dominant-baseline","central").text(g.label);let $=g.label.length*7;const h=P.node();if(h&&typeof h.getBBox=="function"){const G=h.getBBox();G.width>0&&($=G.width)}const w=$+tt*2,I=u.cx-w/2;M.attr("transform",`translate(${I}, ${C})`),M.insert("rect","text").attr("class","cynefinItem").attr("x",0).attr("y",0).attr("width",w).attr("height",T).attr("rx",4).attr("ry",4).attr("fill",z[l]).attr("fill-opacity",.95),P.attr("x",w/2).attr("y",T/2)}),N>0){const g=B+L.length*(T+4),S=`+${N} more`,C=K.append("g"),M=C.append("text").attr("class","cynefinItemText").attr("x",0).attr("y",T/2).attr("text-anchor","middle").attr("dominant-baseline","central").text(S);let P=S.length*7;const $=M.node();if($&&typeof $.getBBox=="function"){const I=$.getBBox();I.width>0&&(P=I.width)}const h=P+tt*2,w=u.cx-h/2;C.attr("transform",`translate(${w}, ${g})`),C.insert("rect","text").attr("class","cynefinItemOverflow").attr("x",0).attr("y",0).attr("width",h).attr("height",T).attr("rx",4).attr("ry",4).attr("fill",z[l]).attr("fill-opacity",.6),M.attr("x",h/2).attr("y",T/2)}}if(v.length>0){const l=k.select("defs").empty()?k.append("defs"):k.select("defs"),r=`cynefin-arrow-${e}`;l.append("marker").attr("id",r).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerWidth",6).attr("markerHeight",6).attr("orient","auto-start-reverse").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","cynefinArrowHead");const u=A.append("g").attr("class","cynefin-arrows");v.forEach(y=>{const L=F[y.from],N=F[y.to];if(!L||!N)return;if(y.from===y.to){O.warn(`Cynefin renderer: skipping self-loop on domain "${y.from}"`);return}const B=L.cx,g=L.cy,S=N.cx,C=N.cy,M=(B+S)/2,P=(g+C)/2,$=S-B,h=C-g,w=Math.sqrt($*$+h*h),I=w*.15,G=-h/w,xt=$/w,et=M+G*I,nt=P+xt*I;u.append("path").attr("class","cynefinArrowLine").attr("d",`M${B},${g} Q${et},${nt} ${S},${C}`).attr("fill","none").attr("marker-end",`url(#${r})`),y.label&&u.append("text").attr("class","cynefinArrowLabel").attr("x",et).attr("y",nt-6).attr("text-anchor","middle").attr("dominant-baseline","auto").text(y.label)})}W&&A.append("text").attr("class","cynefinTitle").attr("x",s/2).attr("y",-b/2).attr("text-anchor","middle").attr("dominant-baseline","middle").text(W)},"draw"),Ft={draw:Et},Vt=i(()=>{const t=ot(),e=Q();return U(t,e.themeVariables).cynefin},"getCynefinTheme"),Ht=i(()=>{const t=Vt();return` .cynefinDomain { stroke: none; } diff --git a/static/ml_canvas/assets/dagre-GXQ25YYZ-DEDHweD_.js b/static/ml_canvas/assets/dagre-GXQ25YYZ-DJLeXd5X.js similarity index 98% rename from static/ml_canvas/assets/dagre-GXQ25YYZ-DEDHweD_.js rename to static/ml_canvas/assets/dagre-GXQ25YYZ-DJLeXd5X.js index ed909c3b5..763a86e17 100644 --- a/static/ml_canvas/assets/dagre-GXQ25YYZ-DEDHweD_.js +++ b/static/ml_canvas/assets/dagre-GXQ25YYZ-DJLeXd5X.js @@ -1,4 +1,4 @@ -import{_ as m,a8 as D,c as A,S as Y,l as p,a9 as _,aa as H,ab as w,ac as J,ad as T,ae as z,af as R,ag as F,ah as j,ai as C,a3 as P,a1 as W,aj as q,ak as U}from"./mermaid.core-BCO0YdKy.js";import{l as K}from"./layout-DCa88gcB.js";import"./index-BXksgzya.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var v=m((t,e,d)=>Math.max(e,Math.min(d,t)),"clamp"),B=m((t="TB")=>{switch(t){case"BT":return"bottom";case"LR":return"right";case"RL":return"left";case"TB":default:return"top"}},"getDefaultSelfLoopSide"),Q=m(t=>t==="flowchart"||t==="flowchart-v2"||t==="stateDiagram"||t==="er"||t==="classDiagram","shouldMergeSelfLoopSegments"),V=["x","y","width","height","labelBBox","intersect","calcIntersect","diff","clusterNode"],Z=m((t,e,d,g,s)=>{const h=[],L=new Set;if(d.forEach(({start:l,end:r})=>{l!==g&&L.add(l),r!==g&&L.add(r)}),L.forEach(l=>{const r=t.node(l);typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number"&&h.push(r)}),h.length===0&&d.forEach(({edge:l})=>{(l.points??[]).forEach(r=>{typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number"&&h.push(r)})}),h.length===0)return B(s);const c=h.reduce((l,r)=>({x:l.x+r.x/h.length,y:l.y+r.y/h.length}),{x:0,y:0}),i=c.x-e.x,o=c.y-e.y;return Math.abs(i)>Math.abs(o)?i>0?"right":"left":Math.abs(o)>0?o>0?"bottom":"top":B(s)},"getSelfLoopSide"),$=m((t,e="top",d=0,g=0)=>{const s=t.x,h=t.y-d,L=t.width/2,c=t.height/2,i=Math.max(36,Math.min(100,t.width*.8)),o=v(Math.max(g,t.width*.35),36,i),l=v(Math.min(t.width,t.height)*.45,24,48);switch(e){case"bottom":{const r=h+c;return[{x:s-o/2,y:r},{x:s-o/2,y:r+l},{x:s+o/2,y:r+l},{x:s+o/2,y:r}]}case"right":{const r=s+L;return[{x:r,y:h-o/2},{x:r+l,y:h-o/2},{x:r+l,y:h+o/2},{x:r,y:h+o/2}]}case"left":{const r=s-L;return[{x:r,y:h-o/2},{x:r-l,y:h-o/2},{x:r-l,y:h+o/2},{x:r,y:h+o/2}]}case"top":default:{const r=h-c;return[{x:s-o/2,y:r},{x:s-o/2,y:r-l},{x:s+o/2,y:r-l},{x:s+o/2,y:r}]}}},"getSelfLoopPoints"),ee=m((t,e,d="top",g=0,s={})=>{const L=t.x,c=t.y-g,i=s.width??0,o=s.height??0;switch(d){case"bottom":return{x:L,y:Math.max(...e.map(l=>l.y))+o/2+4};case"right":return{x:Math.max(...e.map(l=>l.x))+i/2+4,y:c};case"left":return{x:Math.min(...e.map(l=>l.x))-i/2-4,y:c};case"top":default:return{x:L,y:Math.min(...e.map(l=>l.y))-o/2-4}}},"getSelfLoopLabelPosition"),M=m((t,e=0,{mergeSelfLoops:d=!0}={})=>{var L;const g=new Map,s=[],h=(L=t.graph())==null?void 0:L.rankdir;return t.edges().forEach(c=>{const i=t.edge(c);if(d&&i.selfLoop){const o=i.selfLoop.id;g.has(o)||g.set(o,[]),g.get(o).push({edge:i,start:c.v,end:c.w})}else s.push({edge:i,start:c.v,end:c.w})}),g.forEach(c=>{if(c.length!==3){c.forEach(b=>s.push(b));return}c.sort((b,x)=>b.edge.selfLoop.order-x.edge.selfLoop.order);const[i,o,l]=c,r=i.edge.originalEdge??o.edge.originalEdge??l.edge.originalEdge??o.edge,a=t.node(r.start);if(!a){c.forEach(b=>s.push(b));return}const E={width:o.edge.width,height:o.edge.height},y=Z(t,a,c,r.start,h),f=$(a,y,e,E.width??0),n=ee(a,f,y,e,E),u={...o.edge,...r,id:r.id,points:f,start:r.start,end:r.end,x:n.x,y:n.y,width:E.width,height:E.height,labelStyle:o.edge.labelStyle,fromCluster:i.edge.fromCluster??o.edge.fromCluster??l.edge.fromCluster,toCluster:i.edge.toCluster??o.edge.toCluster??l.edge.toCluster};delete u.selfLoop,delete u.originalEdge,s.push({edge:u,start:u.start,end:u.end})}),s},"getEdgesToRender"),k=m(async({element:t,graph:e,diagramType:d,id:g,parentCluster:s,siteConfig:h})=>{const L=e.graph().rankdir;p.trace("Dir in recursive render - dir:",L);const{clusters:c,edgePaths:i,edgeLabels:o,nodes:l,rootGroups:r}=J(t,{edgePathsClass:"edgePaths"});e.nodes()?p.info("Recursive render XXX",e.nodes()):p.info("No nodes found for",e),e.edges().length>0&&p.info("Recursive edges",e.edge(e.edges()[0]));const a=Q(d);await Promise.all(e.nodes().map(async function(f){const n=e.node(f);if(s!==void 0){const u=JSON.parse(JSON.stringify(s.clusterData));p.trace(`Setting data for parent cluster XXX +import{_ as m,a8 as D,c as A,S as Y,l as p,a9 as _,aa as H,ab as w,ac as J,ad as T,ae as z,af as R,ag as F,ah as j,ai as C,a3 as P,a1 as W,aj as q,ak as U}from"./mermaid.core-BRmiRRt4.js";import{l as K}from"./layout-CjvZl75P.js";import"./index-DYMv5Ibu.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var v=m((t,e,d)=>Math.max(e,Math.min(d,t)),"clamp"),B=m((t="TB")=>{switch(t){case"BT":return"bottom";case"LR":return"right";case"RL":return"left";case"TB":default:return"top"}},"getDefaultSelfLoopSide"),Q=m(t=>t==="flowchart"||t==="flowchart-v2"||t==="stateDiagram"||t==="er"||t==="classDiagram","shouldMergeSelfLoopSegments"),V=["x","y","width","height","labelBBox","intersect","calcIntersect","diff","clusterNode"],Z=m((t,e,d,g,s)=>{const h=[],L=new Set;if(d.forEach(({start:l,end:r})=>{l!==g&&L.add(l),r!==g&&L.add(r)}),L.forEach(l=>{const r=t.node(l);typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number"&&h.push(r)}),h.length===0&&d.forEach(({edge:l})=>{(l.points??[]).forEach(r=>{typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number"&&h.push(r)})}),h.length===0)return B(s);const c=h.reduce((l,r)=>({x:l.x+r.x/h.length,y:l.y+r.y/h.length}),{x:0,y:0}),i=c.x-e.x,o=c.y-e.y;return Math.abs(i)>Math.abs(o)?i>0?"right":"left":Math.abs(o)>0?o>0?"bottom":"top":B(s)},"getSelfLoopSide"),$=m((t,e="top",d=0,g=0)=>{const s=t.x,h=t.y-d,L=t.width/2,c=t.height/2,i=Math.max(36,Math.min(100,t.width*.8)),o=v(Math.max(g,t.width*.35),36,i),l=v(Math.min(t.width,t.height)*.45,24,48);switch(e){case"bottom":{const r=h+c;return[{x:s-o/2,y:r},{x:s-o/2,y:r+l},{x:s+o/2,y:r+l},{x:s+o/2,y:r}]}case"right":{const r=s+L;return[{x:r,y:h-o/2},{x:r+l,y:h-o/2},{x:r+l,y:h+o/2},{x:r,y:h+o/2}]}case"left":{const r=s-L;return[{x:r,y:h-o/2},{x:r-l,y:h-o/2},{x:r-l,y:h+o/2},{x:r,y:h+o/2}]}case"top":default:{const r=h-c;return[{x:s-o/2,y:r},{x:s-o/2,y:r-l},{x:s+o/2,y:r-l},{x:s+o/2,y:r}]}}},"getSelfLoopPoints"),ee=m((t,e,d="top",g=0,s={})=>{const L=t.x,c=t.y-g,i=s.width??0,o=s.height??0;switch(d){case"bottom":return{x:L,y:Math.max(...e.map(l=>l.y))+o/2+4};case"right":return{x:Math.max(...e.map(l=>l.x))+i/2+4,y:c};case"left":return{x:Math.min(...e.map(l=>l.x))-i/2-4,y:c};case"top":default:return{x:L,y:Math.min(...e.map(l=>l.y))-o/2-4}}},"getSelfLoopLabelPosition"),M=m((t,e=0,{mergeSelfLoops:d=!0}={})=>{var L;const g=new Map,s=[],h=(L=t.graph())==null?void 0:L.rankdir;return t.edges().forEach(c=>{const i=t.edge(c);if(d&&i.selfLoop){const o=i.selfLoop.id;g.has(o)||g.set(o,[]),g.get(o).push({edge:i,start:c.v,end:c.w})}else s.push({edge:i,start:c.v,end:c.w})}),g.forEach(c=>{if(c.length!==3){c.forEach(b=>s.push(b));return}c.sort((b,x)=>b.edge.selfLoop.order-x.edge.selfLoop.order);const[i,o,l]=c,r=i.edge.originalEdge??o.edge.originalEdge??l.edge.originalEdge??o.edge,a=t.node(r.start);if(!a){c.forEach(b=>s.push(b));return}const E={width:o.edge.width,height:o.edge.height},y=Z(t,a,c,r.start,h),f=$(a,y,e,E.width??0),n=ee(a,f,y,e,E),u={...o.edge,...r,id:r.id,points:f,start:r.start,end:r.end,x:n.x,y:n.y,width:E.width,height:E.height,labelStyle:o.edge.labelStyle,fromCluster:i.edge.fromCluster??o.edge.fromCluster??l.edge.fromCluster,toCluster:i.edge.toCluster??o.edge.toCluster??l.edge.toCluster};delete u.selfLoop,delete u.originalEdge,s.push({edge:u,start:u.start,end:u.end})}),s},"getEdgesToRender"),k=m(async({element:t,graph:e,diagramType:d,id:g,parentCluster:s,siteConfig:h})=>{const L=e.graph().rankdir;p.trace("Dir in recursive render - dir:",L);const{clusters:c,edgePaths:i,edgeLabels:o,nodes:l,rootGroups:r}=J(t,{edgePathsClass:"edgePaths"});e.nodes()?p.info("Recursive render XXX",e.nodes()):p.info("No nodes found for",e),e.edges().length>0&&p.info("Recursive edges",e.edge(e.edges()[0]));const a=Q(d);await Promise.all(e.nodes().map(async function(f){const n=e.node(f);if(s!==void 0){const u=JSON.parse(JSON.stringify(s.clusterData));p.trace(`Setting data for parent cluster XXX Node.id = `,f,` data=`,u.height,` Parent cluster`,s.height),e.setNode(s.id,u),e.parent(f)||(p.trace("Setting parent",f,s.id),e.setParent(f,s.id,u))}if(p.info("(Insert) Node XXX"+f+": "+JSON.stringify(e.node(f))),n!=null&&n.clusterNode){p.info("Cluster identified XBX",f,n.width,e.node(f));const{ranksep:u,nodesep:b}=e.graph();n.graph.setGraph({...n.graph.graph(),ranksep:u+25,nodesep:b});const x=await ne({element:l,graph:n.graph,diagramType:d,id:g,parentCluster:e.node(f),siteConfig:h}),S=x.elem;T(n,S),n.diff=x.diff||0,p.info("New compound node after recursive render XAX",f,"width",n.width,"height",n.height),z(S,n)}else e.children(f).length>0?(p.trace("Cluster - the non recursive path XBX",f,n.id,n,n.width,"Graph:",e),p.trace(R(n.id,e)),w.set(n.id,{id:R(n.id,e),node:n})):(p.trace("Node - the non recursive path XAX",f,l,e.node(f),L),await F(l,e.node(f),{config:h,dir:L}))})),await m(async()=>{const f=e.edges().map(async function(n){var b,x,S,X;const u=e.edge(n.v,n.w,n.name);if(p.info("Edge "+n.v+" -> "+n.w+": "+JSON.stringify(n)),p.info("Edge "+n.v+" -> "+n.w+": ",n," ",JSON.stringify(e.edge(n))),p.info("Fix",w,"ids:",n.v,n.w,"Translating: ",w.get(n.v),w.get(n.w)),a&&u.selfLoop){if(u.selfLoop.order!==1)return;const N={...u.originalEdge,...u,id:u.selfLoop.id,startLabelLeft:((b=u.originalEdge)==null?void 0:b.startLabelLeft)??u.startLabelLeft,startLabelRight:((x=u.originalEdge)==null?void 0:x.startLabelRight)??u.startLabelRight,endLabelLeft:((S=u.originalEdge)==null?void 0:S.endLabelLeft)??u.endLabelLeft,endLabelRight:((X=u.originalEdge)==null?void 0:X.endLabelRight)??u.endLabelRight};await C(o,N),u.width=N.width,u.height=N.height,u.labelStyle=N.labelStyle;return}await C(o,u)});await Promise.all(f)},"processEdges")();const{subGraphTitleTotalMargin:y}=j(h);return{elem:r,graph:e,groups:{clusters:c,edgePaths:i,edgeLabels:o,nodes:l,rootGroups:r},diagramType:d,id:g,mergeSelfLoops:a,subGraphTitleTotalMargin:y}},"measureDagreGraph"),G=m(t=>{p.info("############################################# XXX"),p.info("### Layout ### XXX"),p.info("############################################# XXX"),K(t)},"runDagreGraphLayout"),te=m((t,e,d)=>{const g=t.node(e);if(!g)return;const s={...g};return g!=null&&g.clusterNode?s.y=(g.y??0)+d:t.children(e).length>0?s.height=(g.height??0)+d:s.y=(g.y??0)+d/2,s},"normalizeDagreNode"),I=m((t,e)=>{V.forEach(d=>{e[d]!==void 0&&(t[d]=e[d])})},"applyDagreNodeLayout"),re=m((t,e,d,g)=>({...t,start:t.start??e,end:t.end??d,points:(t.points??[]).map(s=>({...s,y:typeof s.y=="number"?s.y+g:s.y}))}),"normalizeDagreEdge"),ae=m((t,e)=>{const{graph:d,mergeSelfLoops:g,subGraphTitleTotalMargin:s=0}=e,h=new Map(t.nodes.map(c=>[c.id,c]));D(d).forEach(c=>{const i=te(d,c,s);if(!i)return;I(d.node(c),i);const o=h.get(c);o&&I(o,i)});const L=s/2;return t.edges=M(d,L,{mergeSelfLoops:g}).map(({edge:c,start:i,end:o})=>re(c,i,o,L)),t},"applyDagreLayoutResult"),oe=m(async({elem:t,graph:e,groups:{clusters:d,edgePaths:g},diagramType:s,id:h,mergeSelfLoops:L,subGraphTitleTotalMargin:c})=>{let i=0;await Promise.all(D(e).map(async function(r){var E;const a=e.node(r);if(p.info("Position XBX => "+r+": ("+a.x,","+a.y,") width: ",a.width," height: ",a.height),a!=null&&a.clusterNode)a.y+=c,p.info("A tainted cluster node XBX1",r,a.id,a.width,a.height,a.x,a.y,e.parent(r)),w.get(a.id).node=a,P(a);else if(e.children(r).length>0){p.info("A pure cluster node XBX1",r,a.id,a.x,a.y,a.width,a.height,e.parent(r)),a.height+=c,e.node(a.parentId);const y=(a==null?void 0:a.padding)/2||0,f=((E=a==null?void 0:a.labelBBox)==null?void 0:E.height)||0,n=f-y||0;p.debug("OffsetY",n,"labelHeight",f,"halfPadding",y),await W(d,a),w.get(a.id).node=a}else{const y=e.node(a.parentId);a.y+=c/2,p.info("A regular node XBX1 - using the padding",a.id,"parent",a.parentId,a.width,a.height,a.x,a.y,"offsetY",a.offsetY,"parent",y,y==null?void 0:y.offsetY,a),P(a)}}));const o=c/2;return M(e,o,{mergeSelfLoops:L}).forEach(function({edge:r,start:a,end:E}){p.info("Edge "+a+" -> "+E+": "+JSON.stringify(r),r),r.points.forEach(u=>u.y+=o);const y=e.node(a),f=e.node(E),n=q(g,r,w,s,y,f,h);U(r,n)}),e.nodes().forEach(function(r){const a=e.node(r);p.info(r,a.type,a.diff),a.isGroup&&(i=a.diff)}),p.warn("Returning from recursive render XAX",t,i),{elem:t,diff:i}},"paintDagreLayoutCore"),ne=m(async t=>{const e=await k(t);return G(e.graph),await oe(e)},"renderDagreSubgraph"),O=m(t=>{var d,g,s,h,L,c;const e=new Y({multigraph:!0,compound:!0}).setGraph({rankdir:t.direction,nodesep:((d=t.config)==null?void 0:d.nodeSpacing)||t.nodeSpacing||((s=(g=t.config)==null?void 0:g.flowchart)==null?void 0:s.nodeSpacing),ranksep:((h=t.config)==null?void 0:h.rankSpacing)||t.rankSpacing||((c=(L=t.config)==null?void 0:L.flowchart)==null?void 0:c.rankSpacing),marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});return t.nodes.forEach(i=>{e.setNode(i.id,{...i}),i.parentId&&e.setParent(i.id,i.parentId)}),p.debug("Edges:",t.edges),t.edges.forEach(i=>{if(i.start===i.end){const o=i.start,l=o+"---"+o+"---1",r=o+"---"+o+"---2",a=e.node(o);e.setNode(l,{domId:l,id:l,parentId:a.parentId,labelStyle:"",label:"",padding:0,shape:"labelRect",style:"",width:10,height:10}),e.setParent(l,a.parentId),e.setNode(r,{domId:r,id:r,parentId:a.parentId,labelStyle:"",padding:0,shape:"labelRect",label:"",style:"",width:10,height:10}),e.setParent(r,a.parentId);const E=structuredClone(i),y=structuredClone(i),f=structuredClone(i),n=structuredClone(i);y.originalEdge=E,y.selfLoop={id:E.id,order:0},f.originalEdge=E,f.selfLoop={id:E.id,order:1},n.originalEdge=E,n.selfLoop={id:E.id,order:2},y.label="",y.arrowTypeEnd="none",y.endLabelLeft="",y.endLabelRight="",y.startLabelLeft="",y.id=o+"-cyclic-special-1",f.startLabelRight="",f.startLabelLeft="",f.endLabelLeft="",f.endLabelRight="",f.arrowTypeStart="none",f.arrowTypeEnd="none",f.id=o+"-cyclic-special-mid",n.label="",n.startLabelRight="",n.startLabelLeft="",n.arrowTypeStart="none",a.isGroup&&(y.fromCluster=o,n.toCluster=o),n.id=o+"-cyclic-special-2",n.arrowTypeStart="none",e.setEdge(o,l,y,o+"-cyclic-special-0"),e.setEdge(l,r,f,o+"-cyclic-special-1"),e.setEdge(r,o,n,o+"-cyclic-special-2")}else e.setEdge(i.start,i.end,{...i},i.id)}),_(e),{graph:e}},"prepareLayoutForDagre"),se=m(async(t,{element:e,preparedLayout:d})=>{const g=d??O(t),s=A(),h=await k({element:e,graph:g.graph,diagramType:t.type,id:t.diagramId,parentCluster:void 0,siteConfig:s});return g.measuredLayout=h,h},"measureDagreLayout"),ie=m((t,e)=>{var g;const d=(g=e.preparedLayout)==null?void 0:g.measuredLayout;if(!d)throw new Error("runDagreLayoutCore requires measureDagreLayout to run first");return G(d.graph),ae(t,d),d},"runDagreLayoutCore"),de=m((t,{measure:e})=>D(e.graph).map(d=>e.graph.node(d)).filter(Boolean),"getDagrePaintNodes"),le=m((t,e,{measure:d})=>t?d.graph.node(t):void 0,"getDagreEdgeNode"),ye=H({prepareLayout:O,measureLayout:se,runLayoutCore:ie,paintOptions:{clusterDb:w,getNodes:de,getEdgeNode:le,skipNode:m((t,{measure:e})=>!e.graph.hasNode(t.id),"skipNode"),isCluster:m((t,{measure:e})=>e.graph.hasNode(t.id)&&(e.graph.children(t.id)??[]).length>0,"isCluster")}});export{ae as applyDagreLayoutResult,M as getEdgesToRender,se as measureDagreLayout,O as prepareLayoutForDagre,ye as render,ie as runDagreLayoutCore}; diff --git a/static/ml_canvas/assets/diagram-S7CK7UJ4-BWyT750N.js b/static/ml_canvas/assets/diagram-S7CK7UJ4-Cau7m6k6.js similarity index 96% rename from static/ml_canvas/assets/diagram-S7CK7UJ4-BWyT750N.js rename to static/ml_canvas/assets/diagram-S7CK7UJ4-Cau7m6k6.js index 3b0f287e0..b608a522d 100644 --- a/static/ml_canvas/assets/diagram-S7CK7UJ4-BWyT750N.js +++ b/static/ml_canvas/assets/diagram-S7CK7UJ4-Cau7m6k6.js @@ -1,4 +1,4 @@ -import{I as W}from"./chunk-2Q5K7J3B-DEOZDP-3.js";import{p as X}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{m as O,b as G,s as Y,n as P,g as F,a as Z,_ as g,z as A,l as E,C as q,d as U,x as L,o as j,i as J,a4 as K,A as Q,a5 as ee}from"./mermaid.core-BCO0YdKy.js";import{p as te}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import"./index-BXksgzya.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var D=/[─━│┃└┗├┣]/,_=/[└┗├┣]/,re=/[─━]/,V=/^[\s│┃]+$/,$=/^\s*(title[\t ]|accTitle[\t ]*:|accDescr[\t ]*[:{])/,k=/^\s*%%/,ne=" ";function S(r){return r.some(t=>D.test(t))}g(S,"isBoxDrawingFormat");function M(r){for(const t of r){const e=_.exec(t);if(e!=null&&e.index&&e.index>0)return e.index}return 4}g(M,"inferSegmentWidth");function R(r,t){return r.replace(/\bline\s+(\d+)\b/gi,(e,i)=>{const s=parseInt(i,10),o=t.get(s);return o?`line ${o}`:e})}g(R,"remapErrorLines");function H(r){const t=r.split(` +import{I as W}from"./chunk-2Q5K7J3B-BAAo9EN0.js";import{p as X}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{m as O,b as G,s as Y,n as P,g as F,a as Z,_ as g,z as A,l as E,C as q,d as U,x as L,o as j,i as J,a4 as K,A as Q,a5 as ee}from"./mermaid.core-BRmiRRt4.js";import{p as te}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import"./index-DYMv5Ibu.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var D=/[─━│┃└┗├┣]/,_=/[└┗├┣]/,re=/[─━]/,V=/^[\s│┃]+$/,$=/^\s*(title[\t ]|accTitle[\t ]*:|accDescr[\t ]*[:{])/,k=/^\s*%%/,ne=" ";function S(r){return r.some(t=>D.test(t))}g(S,"isBoxDrawingFormat");function M(r){for(const t of r){const e=_.exec(t);if(e!=null&&e.index&&e.index>0)return e.index}return 4}g(M,"inferSegmentWidth");function R(r,t){return r.replace(/\bline\s+(\d+)\b/gi,(e,i)=>{const s=parseInt(i,10),o=t.get(s);return o?`line ${o}`:e})}g(R,"remapErrorLines");function H(r){const t=r.split(` `),e=new Map;let i=-1;for(const[d,l]of t.entries())if(l.trim()==="treeView-beta"){i=d;break}if(i===-1)return{text:r,lineMap:e};const s=[];for(let d=i+1;d({cnt:1,stack:[{id:0,level:-1,name:"/",nodeType:"directory",children:[]}]})),ie=g(()=>{x.reset(),j()},"clear"),oe=g(()=>x.records.stack[0],"getRoot"),se=g(()=>x.records.cnt,"getCount"),ae=Q.treeView,ce=g(()=>A(ae,L().treeView),"getConfig"),le=g((r,t,e,i,s,o)=>{for(;r<=x.records.stack[x.records.stack.length-1].level;)x.records.stack.pop();const n={id:x.records.cnt++,level:r,name:t,nodeType:e,icon:s,cssClass:i,description:o,children:[]};x.records.stack[x.records.stack.length-1].children.push(n),x.records.stack.push(n)},"addNode"),de={clear:ie,addNode:le,getRoot:oe,getCount:se,getConfig:ce,getAccTitle:Z,getAccDescription:F,getDiagramTitle:P,setAccDescription:Y,setAccTitle:G,setDiagramTitle:O},I=de,he=g(r=>{X(r,I);for(const t of r.nodes){const e=typeof t.indent=="number"?t.indent:0;let i=t.name;const s=i.endsWith("/");s&&(i=i.slice(0,-1));const o=s?"directory":"file",n=t.classAnnotation||void 0,c=t.iconAnnotation,d=c!==void 0?c||"none":void 0,l=t.descAnnotation||void 0,u=l?J(l,L()):void 0;I.addNode(e,i,o,n,d,u)}},"populate"),pe={parse:g(async r=>{const{text:t,lineMap:e}=H(r);try{const i=await te("treeView",t);E.debug(i),he(i)}catch(i){throw e.size>0&&i instanceof Error&&(i.message=R(i.message,e)),i}},"parse")},C={prefix:"mermaid-treeview",height:24,width:24,icons:{folder:{body:''},file:{body:''}}};function z(r,t){var s;const e=(s=t==null?void 0:t.filenameIcons)==null?void 0:s[r];if(e)return e;const i=r.lastIndexOf(".");if(i>0){const o=r.substring(i).toLowerCase(),n=t==null?void 0:t.extensionIcons;return(n==null?void 0:n[o])??(n==null?void 0:n[o.slice(1)])}}g(z,"detectIcon");function y(r,t){return r.includes(":")?r:r in C.icons||!t?`${C.prefix}:${r}`:`${t}:${r}`}g(y,"qualifyIcon");function T(r,t){if(r.icon!=="none"){if(r.icon)return y(r.icon,t.defaultIconPack);if(t.showIcons){if(r.nodeType==="file"){const e=z(r.name,t);if(e==="none")return;if(e)return y(e,t.defaultIconPack)}return`${C.prefix}:${r.nodeType==="directory"?"folder":"file"}`}}}g(T,"getNodeIcon");ee([{name:C.prefix,icons:C}]);var B=14,ge=4,fe=16,ue=g(async(r,t)=>{const e=[],i=g(o=>{const n=T(o,t);n&&e.push({icon:n,node:o}),o.children.forEach(i)},"collect");i(r);const s=await Promise.all(e.map(async({icon:o,node:n})=>({id:n.id,svg:await K(o,{height:B,width:B})})));return new Map(s.map(({id:o,svg:n})=>[o,n]))},"resolveNodeIcons"),me=g((r,t,e,i,s,o)=>{var b;const n=i.append("g");let c="treeView-node-label";e.nodeType==="directory"&&(c+=" treeView-node-dir"),e.cssClass&&(c+=` ${e.cssClass}`);const d=B+ge,l=T(e,s),u=l!==void 0;l&&n.append("g").attr("class","treeView-node-icon").attr("transform",`translate(${r+s.paddingX}, ${t+s.paddingY})`).html(o.get(e.id)??"");const a=n.append("text").text(e.name).attr("dominant-baseline","middle").attr("class",c),{height:p,width:h}=a.node().getBBox(),w=p+s.paddingY*2,m=r+s.paddingX+(u?d:0);a.attr("x",m),a.attr("y",t+w/2);const f=m+h,v=h+s.paddingX*2+(u?d:0);return e.BBox={x:r,y:t,width:v,height:w},(b=e.cssClass)!=null&&b.split(/\s+/).includes("highlight")&&n.insert("rect",":first-child").attr("x",r).attr("y",t+1).attr("width",0).attr("height",w-2).attr("rx",3).attr("class","treeView-highlight-bg"),{node:e,nodeGroup:n,labelRightEdge:f,centerY:t+w/2}},"positionLabel"),N=g((r,t,e,i,s,o)=>r.append("line").attr("x1",t).attr("y1",e).attr("x2",i).attr("y2",s).attr("stroke-width",o).attr("class","treeView-node-line"),"positionLine"),we=g((r,t,e,i)=>{var u;let s=0,o=0;const n=[],c=g((a,p,h,w)=>{const m=w*(h.rowIndent+h.paddingX),f=me(m,s,p,a,h,i);n.push(f);const{height:v,width:b}=p.BBox;N(a,m-h.rowIndent,s+v/2,m,s+v/2,h.lineThickness),o=Math.max(o,m+b),s+=v},"drawNode"),d=g((a,p=0)=>{c(r,a,e,p),a.children.forEach(f=>{d(f,p+1)});const{x:h,y:w,height:m}=a.BBox;if(a.children.length){const{y:f,height:v}=a.children[a.children.length-1].BBox;N(r,h+e.paddingX,w+m,h+e.paddingX,f+v/2+e.lineThickness/2,e.lineThickness)}},"processNode");d(t);const l=n.filter(a=>a.node.description);if(l.length>0){const p=Math.max(...n.map(h=>h.labelRightEdge))+fe;for(const h of l){const m=h.nodeGroup.append("text").text(h.node.description).attr("dominant-baseline","middle").attr("class","treeView-node-description").attr("x",p).attr("y",h.centerY).node().getBBox();o=Math.max(o,p+m.width+e.paddingX)}}for(const a of n)if((u=a.node.cssClass)!=null&&u.split(/\s+/).includes("highlight")){const p=a.nodeGroup.select(".treeView-highlight-bg");if(!p.empty()){const h=o-a.node.BBox.x+8;p.attr("width",h),o=Math.max(o,a.node.BBox.x+h+2)}}return{totalHeight:s,totalWidth:o}},"drawTree"),ve=g(async(r,t,e,i)=>{E.debug(`Rendering treeView diagram `+r);const s=i.db,o=s.getRoot(),n=s.getConfig(),c=q(t),d=c.append("g");d.attr("class","tree-view");const l=await ue(o,n),{totalHeight:u,totalWidth:a}=we(d,o,n,l);c.attr("viewBox",`-${n.lineThickness/2} 0 ${a} ${u}`),U(c,u,a,n.useMaxWidth)},"draw"),xe={draw:ve},be=xe,Ce={labelFontSize:"16px",labelColor:"black",lineColor:"black",iconColor:"#546e7a",descriptionColor:"#6a9955",highlightBg:"rgba(255, 193, 7, 0.15)",highlightStroke:"#ffc107"},Ie=g(({treeView:r})=>{const{labelFontSize:t,labelColor:e,lineColor:i,iconColor:s,descriptionColor:o,highlightBg:n,highlightStroke:c}=A(Ce,r);return` diff --git a/static/ml_canvas/assets/diagram-UQ7AKVKN-4ucOn3R5.js b/static/ml_canvas/assets/diagram-UQ7AKVKN-BZwlTNIF.js similarity index 95% rename from static/ml_canvas/assets/diagram-UQ7AKVKN-4ucOn3R5.js rename to static/ml_canvas/assets/diagram-UQ7AKVKN-BZwlTNIF.js index 8d2896466..e21e51e41 100644 --- a/static/ml_canvas/assets/diagram-UQ7AKVKN-4ucOn3R5.js +++ b/static/ml_canvas/assets/diagram-UQ7AKVKN-BZwlTNIF.js @@ -1,4 +1,4 @@ -import{p as I}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{s as _,g as E,n as F,m as D,a as z,b as P,_ as c,C as G,o as B,z as C,x as w,A as W,l as b,E as V,d as H}from"./mermaid.core-BCO0YdKy.js";import{p as j}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import"./index-BXksgzya.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var x={showLegend:!0,ticks:5,max:null,min:0,graticule:"circle"},y=32,A={axes:[],curves:[],options:x},m=structuredClone(A),U=W.radar,X=c(()=>C({...U,...w().radar}),"getConfig"),M=c(()=>m.axes,"getAxes"),K=c(()=>m.curves,"getCurves"),N=c(()=>m.options,"getOptions"),Y=c(a=>{m.axes=a.map(t=>({name:t.name,label:t.label??t.name}))},"setAxes"),Z=c(a=>{m.curves=a.map(t=>({name:t.name,label:t.label??t.name,entries:q(t.entries)}))},"setCurves"),q=c(a=>{if(a[0].axis==null)return a.map(e=>e.value);const t=M();if(t.length===0)throw new Error("Axes must be populated before curves for reference entries");return t.map(e=>{const r=a.find(s=>{var n;return((n=s.axis)==null?void 0:n.$refText)===e.name});if(r===void 0)throw new Error("Missing entry for axis "+e.label);return r.value})},"computeCurveEntries"),J=c(a=>{var e,r,s,n,l;const t=a.reduce((o,i)=>(o[i.name]=i,o),{});m.options={showLegend:((e=t.showLegend)==null?void 0:e.value)??x.showLegend,ticks:((r=t.ticks)==null?void 0:r.value)??x.ticks,max:((s=t.max)==null?void 0:s.value)??x.max,min:((n=t.min)==null?void 0:n.value)??x.min,graticule:((l=t.graticule)==null?void 0:l.value)??x.graticule},m.options.ticks>y&&(b.warn(`Radar diagram ticks (${m.options.ticks}) exceeds maximum allowed (${y}). Using ${y} instead.`),m.options.ticks=y)},"setOptions"),Q=c(()=>{B(),m=structuredClone(A)},"clear"),$={getAxes:M,getCurves:K,getOptions:N,setAxes:Y,setCurves:Z,setOptions:J,getConfig:X,clear:Q,setAccTitle:P,getAccTitle:z,setDiagramTitle:D,getDiagramTitle:F,getAccDescription:E,setAccDescription:_},tt=c(a=>{I(a,$);const{axes:t,curves:e,options:r}=a;$.setAxes(t),$.setCurves(e),$.setOptions(r)},"populate"),et={parse:c(async a=>{const t=await j("radar",a);b.debug(t),tt(t)},"parse")},at=c((a,t,e,r)=>{const s=r.db,n=s.getAxes(),l=s.getCurves(),o=s.getOptions(),i=s.getConfig(),d=s.getDiagramTitle(),u=G(t),p=rt(u,i),g=o.max??Math.max(...l.map(f=>Math.max(...f.entries))),h=o.min,v=Math.min(i.width,i.height)/2;st(p,n,v,o.ticks,o.graticule),nt(p,n,v,i),L(p,n,l,h,g,o.graticule,i),k(p,l,o.showLegend,i),p.append("text").attr("class","radarTitle").text(d).attr("x",0).attr("y",-i.height/2-i.marginTop)},"draw"),rt=c((a,t)=>{const e=t.width+t.marginLeft+t.marginRight,r=t.height+t.marginTop+t.marginBottom,s={x:t.marginLeft+t.width/2,y:t.marginTop+t.height/2};return H(a,r,e,t.useMaxWidth??!0),a.attr("viewBox",`0 0 ${e} ${r}`).attr("overflow","visible"),a.append("g").attr("transform",`translate(${s.x}, ${s.y})`)},"drawFrame"),st=c((a,t,e,r,s)=>{if(s==="circle")for(let n=0;n{const p=2*u*Math.PI/n-Math.PI/2,g=o*Math.cos(p),h=o*Math.sin(p);return`${g},${h}`}).join(" ");a.append("polygon").attr("points",i).attr("class","radarGraticule")}}},"drawGraticule"),nt=c((a,t,e,r)=>{const s=t.length;for(let n=0;n.01?"start":i<-.01?"end":"middle",p=d>.01?"hanging":d<-.01?"auto":"central",g=4;a.append("text").text(l).attr("x",e*r.axisLabelFactor*i+g*i).attr("y",e*r.axisLabelFactor*d+g*d).attr("text-anchor",u).attr("dominant-baseline",p).attr("class","radarAxisLabel")}},"drawAxes");function L(a,t,e,r,s,n,l){const o=t.length,i=Math.min(l.width,l.height)/2;e.forEach((d,u)=>{if(d.entries.length!==o)return;const p=d.entries.map((g,h)=>{const v=2*Math.PI*h/o-Math.PI/2,f=T(g,r,s,i),O=f*Math.cos(v),R=f*Math.sin(v);return{x:O,y:R}});n==="circle"?a.append("path").attr("d",S(p,l.curveTension)).attr("class",`radarCurve-${u}`):n==="polygon"&&a.append("polygon").attr("points",p.map(g=>`${g.x},${g.y}`).join(" ")).attr("class",`radarCurve-${u}`)})}c(L,"drawCurves");function T(a,t,e,r){const s=Math.min(Math.max(a,t),e);return r*(s-t)/(e-t)}c(T,"relativeRadius");function S(a,t){const e=a.length;let r=`M${a[0].x},${a[0].y}`;for(let s=0;s{const d=a.append("g").attr("transform",`translate(${s}, ${n+i*l})`);d.append("rect").attr("width",12).attr("height",12).attr("class",`radarLegendBox-${i}`),d.append("text").attr("x",16).attr("y",0).attr("class","radarLegendText").text(o.label)})}c(k,"drawLegend");var ot={draw:at},it=c((a,t)=>{let e="";for(let r=0;rC({...U,...w().radar}),"getConfig"),M=c(()=>m.axes,"getAxes"),K=c(()=>m.curves,"getCurves"),N=c(()=>m.options,"getOptions"),Y=c(a=>{m.axes=a.map(t=>({name:t.name,label:t.label??t.name}))},"setAxes"),Z=c(a=>{m.curves=a.map(t=>({name:t.name,label:t.label??t.name,entries:q(t.entries)}))},"setCurves"),q=c(a=>{if(a[0].axis==null)return a.map(e=>e.value);const t=M();if(t.length===0)throw new Error("Axes must be populated before curves for reference entries");return t.map(e=>{const r=a.find(s=>{var n;return((n=s.axis)==null?void 0:n.$refText)===e.name});if(r===void 0)throw new Error("Missing entry for axis "+e.label);return r.value})},"computeCurveEntries"),J=c(a=>{var e,r,s,n,l;const t=a.reduce((o,i)=>(o[i.name]=i,o),{});m.options={showLegend:((e=t.showLegend)==null?void 0:e.value)??x.showLegend,ticks:((r=t.ticks)==null?void 0:r.value)??x.ticks,max:((s=t.max)==null?void 0:s.value)??x.max,min:((n=t.min)==null?void 0:n.value)??x.min,graticule:((l=t.graticule)==null?void 0:l.value)??x.graticule},m.options.ticks>y&&(b.warn(`Radar diagram ticks (${m.options.ticks}) exceeds maximum allowed (${y}). Using ${y} instead.`),m.options.ticks=y)},"setOptions"),Q=c(()=>{B(),m=structuredClone(A)},"clear"),$={getAxes:M,getCurves:K,getOptions:N,setAxes:Y,setCurves:Z,setOptions:J,getConfig:X,clear:Q,setAccTitle:P,getAccTitle:z,setDiagramTitle:D,getDiagramTitle:F,getAccDescription:E,setAccDescription:_},tt=c(a=>{I(a,$);const{axes:t,curves:e,options:r}=a;$.setAxes(t),$.setCurves(e),$.setOptions(r)},"populate"),et={parse:c(async a=>{const t=await j("radar",a);b.debug(t),tt(t)},"parse")},at=c((a,t,e,r)=>{const s=r.db,n=s.getAxes(),l=s.getCurves(),o=s.getOptions(),i=s.getConfig(),d=s.getDiagramTitle(),u=G(t),p=rt(u,i),g=o.max??Math.max(...l.map(f=>Math.max(...f.entries))),h=o.min,v=Math.min(i.width,i.height)/2;st(p,n,v,o.ticks,o.graticule),nt(p,n,v,i),L(p,n,l,h,g,o.graticule,i),k(p,l,o.showLegend,i),p.append("text").attr("class","radarTitle").text(d).attr("x",0).attr("y",-i.height/2-i.marginTop)},"draw"),rt=c((a,t)=>{const e=t.width+t.marginLeft+t.marginRight,r=t.height+t.marginTop+t.marginBottom,s={x:t.marginLeft+t.width/2,y:t.marginTop+t.height/2};return H(a,r,e,t.useMaxWidth??!0),a.attr("viewBox",`0 0 ${e} ${r}`).attr("overflow","visible"),a.append("g").attr("transform",`translate(${s.x}, ${s.y})`)},"drawFrame"),st=c((a,t,e,r,s)=>{if(s==="circle")for(let n=0;n{const p=2*u*Math.PI/n-Math.PI/2,g=o*Math.cos(p),h=o*Math.sin(p);return`${g},${h}`}).join(" ");a.append("polygon").attr("points",i).attr("class","radarGraticule")}}},"drawGraticule"),nt=c((a,t,e,r)=>{const s=t.length;for(let n=0;n.01?"start":i<-.01?"end":"middle",p=d>.01?"hanging":d<-.01?"auto":"central",g=4;a.append("text").text(l).attr("x",e*r.axisLabelFactor*i+g*i).attr("y",e*r.axisLabelFactor*d+g*d).attr("text-anchor",u).attr("dominant-baseline",p).attr("class","radarAxisLabel")}},"drawAxes");function L(a,t,e,r,s,n,l){const o=t.length,i=Math.min(l.width,l.height)/2;e.forEach((d,u)=>{if(d.entries.length!==o)return;const p=d.entries.map((g,h)=>{const v=2*Math.PI*h/o-Math.PI/2,f=T(g,r,s,i),O=f*Math.cos(v),R=f*Math.sin(v);return{x:O,y:R}});n==="circle"?a.append("path").attr("d",S(p,l.curveTension)).attr("class",`radarCurve-${u}`):n==="polygon"&&a.append("polygon").attr("points",p.map(g=>`${g.x},${g.y}`).join(" ")).attr("class",`radarCurve-${u}`)})}c(L,"drawCurves");function T(a,t,e,r){const s=Math.min(Math.max(a,t),e);return r*(s-t)/(e-t)}c(T,"relativeRadius");function S(a,t){const e=a.length;let r=`M${a[0].x},${a[0].y}`;for(let s=0;s{const d=a.append("g").attr("transform",`translate(${s}, ${n+i*l})`);d.append("rect").attr("width",12).attr("height",12).attr("class",`radarLegendBox-${i}`),d.append("text").attr("x",16).attr("y",0).attr("class","radarLegendText").text(o.label)})}c(k,"drawLegend");var ot={draw:at},it=c((a,t)=>{let e="";for(let r=0;rge({...ke,...E().eventmodeling}),"getConfig"),A={};function W(){let e=Be;const{ast:n}=A,t=R();if(!n)throw new Error("No data for EventModel");return n.frames.forEach((i,a)=>{const r=X(i,n.dataEntities,t);e=w(e,{$kind:D,index:a,frame:i,textProps:r});let d;q(i)?(g.debug("source frame",i.sourceFrames),d=n.frames.filter(l=>i.sourceFrames.some(c=>c.$refText===l.name)),d.forEach(l=>{e=w(e,{$kind:M,index:a,frame:i,sourceFrame:l})})):e=w(e,{$kind:M,index:a,frame:i})}),e={...e,sortedSwimlanesArray:$(e.swimlanes)},e}o(W,"getState");function I(e){A.ast=e}o(I,"setAst");var s={swimlaneMinHeight:70,swimlanePadding:15,swimlaneGap:10,boxPadding:10,boxOverlap:90,boxDefaultY:0,boxMinWidth:80,boxMaxWidth:450,boxMinHeight:80,boxMaxHeight:750,contentStartX:250,textMaxWidth:430,boxTextFontWeight:"bold",boxTextPadding:10,swimlaneTextFontWeight:"bold",labelUiAutomation:"UI/Automation",labelUiAutomationPrefix:"UI/A: ",labelCommandReadModel:"Command/Read Model",labelCommandReadModelPrefix:"C/RM: ",labelEvents:"Events",labelEventsPrefix:"Stream: "};function R(){return s}o(R,"getDiagramProps");var Be={boxes:[],swimlanes:{},relations:[],maxR:0,sortedSwimlanesArray:[]};function H(e){const n=e.split(".");if(n.length===2)return n[0]}o(H,"extractNamespace");function U(e){const n=e.split(".");return n.length===2?n[1]:e}o(U,"extractName");function _(e,n){if(!(!n||n.length===0))return Object.values(e).find(t=>t.namespace===n)}o(_,"findSwimlaneByNamespace");function v(e,n,t){return Math.max(n,...Object.keys(e).filter(i=>{const a=Number.parseInt(i);return a>n&&aNumber.parseInt(i)))+1}o(v,"findNextAvailableIndex");function V(e,n){const t=H(e.entityIdentifier),i=_(n,t);switch(e.modelEntityType){case"ui":case"pcr":case"processor":return i?{index:i.index,label:i.namespace||s.labelUiAutomation}:t?{index:v(n,0,100),label:s.labelUiAutomationPrefix+t}:{index:0,label:s.labelUiAutomation};case"rmo":case"readmodel":case"cmd":case"command":return i?{index:i.index,label:i.namespace||s.labelCommandReadModel}:t?{index:v(n,100,200),label:s.labelCommandReadModelPrefix+t}:{index:100,label:s.labelCommandReadModel};case"evt":case"event":default:return i?{index:i.index,label:i.namespace||s.labelEvents}:t?{index:v(n,200,300),label:s.labelEventsPrefix+t}:{index:200,label:s.labelEvents}}}o(V,"calculateSwimlaneProps");function L(e){const{themeVariables:n}=E();switch(e.modelEntityType){case"ui":return{fill:n.emUiFill??"white",stroke:n.emUiStroke??"#dbdada"};case"pcr":case"processor":return{fill:n.emProcessorFill??"#edb3f6",stroke:n.emProcessorStroke??"#b88cbf"};case"rmo":case"readmodel":return{fill:n.emReadModelFill??"#d3f1a2",stroke:n.emReadModelStroke??"#a3b732"};case"cmd":case"command":return{fill:n.emCommandFill??"#bcd6fe",stroke:n.emCommandStroke??"#679ac3"};case"evt":case"event":return{fill:n.emEventFill??"#ffb778",stroke:n.emEventStroke??"#c19a0f"};default:return{fill:"red",stroke:"black"}}}o(L,"calculateEntityVisualProps");function X(e,n,t){const i=E(),a=P(U(e.entityIdentifier)??"",i);let r;const d={fontSize:16,fontWeight:700,fontFamily:'"trebuchet ms", verdana, arial, sans-serif',joinWith:"
"};let c=`${S(a,t.textMaxWidth,d)}`;if(e.dataInlineValue&&(r=e.dataInlineValue,r=r.substring(r.indexOf("{")+1),r=r.substring(0,r.lastIndexOf("}")-1),r=P(r,i),r=S(r,t.textMaxWidth,d),r=r.replaceAll(" "," ")),e.dataReference){const p=n.find(y=>{var b;return y.name===((b=e.dataReference)==null?void 0:b.$refText)});p&&(r=p.dataBlockValue,r=r.substring(r.indexOf(`{ +import{p as oe}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{n as se,m as de,s as le,g as ce,a as me,b as ue,_ as o,l as g,c as T,y as xe,o as fe,z as ge,x as E,A as he,i as P,w as S,a6 as pe}from"./mermaid.core-BRmiRRt4.js";import{p as be,i as ve}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import{s as we}from"./vendor-flow-bDma3vSM.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var D="position frame",N="frame positioned",M="position relation",C="relation positioned",ye=o(function(e){g.debug("options str",e)},"setOptions"),Pe=o(function(){return{}},"getOptions"),Se=o(function(){O(),fe()},"clear");function O(){A={}}o(O,"reset");var ke=he.eventmodeling,Me=o(()=>ge({...ke,...E().eventmodeling}),"getConfig"),A={};function W(){let e=Be;const{ast:n}=A,t=R();if(!n)throw new Error("No data for EventModel");return n.frames.forEach((i,a)=>{const r=X(i,n.dataEntities,t);e=w(e,{$kind:D,index:a,frame:i,textProps:r});let d;q(i)?(g.debug("source frame",i.sourceFrames),d=n.frames.filter(l=>i.sourceFrames.some(c=>c.$refText===l.name)),d.forEach(l=>{e=w(e,{$kind:M,index:a,frame:i,sourceFrame:l})})):e=w(e,{$kind:M,index:a,frame:i})}),e={...e,sortedSwimlanesArray:$(e.swimlanes)},e}o(W,"getState");function I(e){A.ast=e}o(I,"setAst");var s={swimlaneMinHeight:70,swimlanePadding:15,swimlaneGap:10,boxPadding:10,boxOverlap:90,boxDefaultY:0,boxMinWidth:80,boxMaxWidth:450,boxMinHeight:80,boxMaxHeight:750,contentStartX:250,textMaxWidth:430,boxTextFontWeight:"bold",boxTextPadding:10,swimlaneTextFontWeight:"bold",labelUiAutomation:"UI/Automation",labelUiAutomationPrefix:"UI/A: ",labelCommandReadModel:"Command/Read Model",labelCommandReadModelPrefix:"C/RM: ",labelEvents:"Events",labelEventsPrefix:"Stream: "};function R(){return s}o(R,"getDiagramProps");var Be={boxes:[],swimlanes:{},relations:[],maxR:0,sortedSwimlanesArray:[]};function H(e){const n=e.split(".");if(n.length===2)return n[0]}o(H,"extractNamespace");function U(e){const n=e.split(".");return n.length===2?n[1]:e}o(U,"extractName");function _(e,n){if(!(!n||n.length===0))return Object.values(e).find(t=>t.namespace===n)}o(_,"findSwimlaneByNamespace");function v(e,n,t){return Math.max(n,...Object.keys(e).filter(i=>{const a=Number.parseInt(i);return a>n&&aNumber.parseInt(i)))+1}o(v,"findNextAvailableIndex");function V(e,n){const t=H(e.entityIdentifier),i=_(n,t);switch(e.modelEntityType){case"ui":case"pcr":case"processor":return i?{index:i.index,label:i.namespace||s.labelUiAutomation}:t?{index:v(n,0,100),label:s.labelUiAutomationPrefix+t}:{index:0,label:s.labelUiAutomation};case"rmo":case"readmodel":case"cmd":case"command":return i?{index:i.index,label:i.namespace||s.labelCommandReadModel}:t?{index:v(n,100,200),label:s.labelCommandReadModelPrefix+t}:{index:100,label:s.labelCommandReadModel};case"evt":case"event":default:return i?{index:i.index,label:i.namespace||s.labelEvents}:t?{index:v(n,200,300),label:s.labelEventsPrefix+t}:{index:200,label:s.labelEvents}}}o(V,"calculateSwimlaneProps");function L(e){const{themeVariables:n}=E();switch(e.modelEntityType){case"ui":return{fill:n.emUiFill??"white",stroke:n.emUiStroke??"#dbdada"};case"pcr":case"processor":return{fill:n.emProcessorFill??"#edb3f6",stroke:n.emProcessorStroke??"#b88cbf"};case"rmo":case"readmodel":return{fill:n.emReadModelFill??"#d3f1a2",stroke:n.emReadModelStroke??"#a3b732"};case"cmd":case"command":return{fill:n.emCommandFill??"#bcd6fe",stroke:n.emCommandStroke??"#679ac3"};case"evt":case"event":return{fill:n.emEventFill??"#ffb778",stroke:n.emEventStroke??"#c19a0f"};default:return{fill:"red",stroke:"black"}}}o(L,"calculateEntityVisualProps");function X(e,n,t){const i=E(),a=P(U(e.entityIdentifier)??"",i);let r;const d={fontSize:16,fontWeight:700,fontFamily:'"trebuchet ms", verdana, arial, sans-serif',joinWith:"
"};let c=`${S(a,t.textMaxWidth,d)}`;if(e.dataInlineValue&&(r=e.dataInlineValue,r=r.substring(r.indexOf("{")+1),r=r.substring(0,r.lastIndexOf("}")-1),r=P(r,i),r=S(r,t.textMaxWidth,d),r=r.replaceAll(" "," ")),e.dataReference){const p=n.find(y=>{var b;return y.name===((b=e.dataReference)==null?void 0:b.$refText)});p&&(r=p.dataBlockValue,r=r.substring(r.indexOf(`{ `)+2),r=r.substring(0,r.lastIndexOf("}")-1),r=P(r,i),r=S(r,t.textMaxWidth,d),r=r.replaceAll(" "," "),r+="
")}const m=r!==void 0;m&&(c+=`

${r}`);const x={fontSize:d.fontSize,fontWeight:d.fontWeight,fontFamily:d.fontFamily},u=pe(c,x),h=m?u.width/3:u.width,f={content:c,width:h,height:u.height};return g.debug(`[${e.name}] ${e.entityIdentifier} text`,f),f}o(X,"calculateTextProps");function G(e,n){const t=n,i=L(t.frame),a={width:t.textProps.width+2*s.boxTextPadding,height:t.textProps.height+2*s.boxTextPadding};return[{$kind:N,frame:t.frame,index:t.index,visual:i,dimension:a,textProps:t.textProps}]}o(G,"decidePositionFrame");function j(e,n,t){return n===void 0?s.contentStartX:n.index===e.index&&e.r?e.r+s.boxPadding:t===void 0?s.contentStartX:t.r-s.boxOverlap+s.boxPadding}o(j,"calculateX");function Y(e,n){const t=[...e.map(i=>i.r),n];return Math.max(...t)}o(Y,"calculateMaxRight");function $(e){return Object.values(e).sort((n,t)=>n.index-t.index)}o($,"sortedSwimlanesArray");function z(e,n){const t=n,i=V(t.frame,e.swimlanes);let a;i.index in e.swimlanes?a=e.swimlanes[i.index]:a={index:i.index,label:i.label,r:0,y:i.index*s.swimlaneMinHeight+s.swimlaneGap,height:s.swimlaneMinHeight,maxHeight:s.swimlaneMinHeight};const r=e.boxes.length>0?e.boxes[e.boxes.length-1]:void 0,d=e.previousSwimlaneNumber!==void 0?e.swimlanes[e.previousSwimlaneNumber]:void 0,l={width:Math.max(s.boxMinWidth,Math.min(s.boxMaxWidth,t.dimension.width))+2*s.boxPadding,height:Math.max(s.boxMinHeight,Math.min(s.boxMaxHeight,t.dimension.height))+2*s.boxPadding},c=j(a,d,r),m=c+l.width+s.boxPadding,x=Y(Object.values(e.swimlanes),m);a.r=c+l.width,a.maxHeight=Math.max(a.maxHeight,l.height),a.height=Math.max(s.swimlaneMinHeight,a.maxHeight)+2*s.swimlanePadding;const u={x:c,y:s.swimlanePadding+a.y,r:m,dimension:l,leftSibling:!1,swimlane:a,visual:t.visual,text:t.textProps.content,frame:t.frame,index:t.index},h={...e,boxes:[...e.boxes,u],swimlanes:{...e.swimlanes,[`${a.index}`]:a},previousSwimlaneNumber:i.index,previousFrame:t.frame,maxR:x},f=$(h.swimlanes);f.length>0&&(f[0].y=0);for(let p=1;p0}o(q,"hasSourceFrame");function B(e,n){if(n!=null)return e.find(t=>t.frame.name===n.name)}o(B,"findBoxByFrame");function J(e,n,t){if(!(t<0))for(let i=t;i>=0;i--){const a=e[i];if(a.swimlane.index!==n)return a}}o(J,"findBoxByLineIndex");function Q(e,n){const t=n;if(ve(t.frame)||K(t.index,t.frame))return[];const i=B(e.boxes,t.frame);if(i===void 0)throw new Error(`Target box not found for frame ${t.frame.name}`);let a;return t.sourceFrame?a=B(e.boxes,t.sourceFrame):a=J(e.boxes,i.swimlane.index,t.index-1),a===void 0?[]:[{$kind:C,frame:t.frame,index:t.index,sourceBox:a,targetBox:i}]}o(Q,"decidePositionRelation");function Z(e,n){const t=n,i={visual:{fill:"none",stroke:"#000"},source:{x:t.sourceBox.x,y:t.sourceBox.y},target:{x:t.targetBox.x,y:t.targetBox.y},sourceBox:t.sourceBox,targetBox:t.targetBox};return{...e,relations:[...e.relations,i]}}o(Z,"evolveRelationPositioned");var Fe={[D]:G,[M]:Q},Ee={[N]:z,[C]:Z};function ee(e,n){const t=Fe[n.$kind];if(t==null)return[];const i=t(e,n);return g.debug("decided events",i),i}o(ee,"decide");function te(e,n){const t=n.reduce((i,a)=>{const r=Ee[a.$kind];return r==null?i:r(i,a)},e);return g.debug("evolve events",{state:e,newState:t,events:n}),t}o(te,"evolve");function w(e,n){const t=ee(e,n);return te(e,t)}o(w,"dispatch");var F={getConfig:Me,setOptions:ye,getOptions:Pe,clear:Se,setAccTitle:ue,getAccTitle:me,getAccDescription:ce,setAccDescription:le,setDiagramTitle:de,getDiagramTitle:se,setAst:I,getDiagramProps:R,getState:W},Ae={parse:o(async e=>{const n=await be("eventmodeling",e);g.debug(n),F.setAst(n),oe(n,F)},"parse")},k=T(),Re=k==null?void 0:k.eventmodeling;function ne(e,n){return t=>{const i=t.swimlane.y+n.swimlanePadding,a=e.append("g").attr("class","em-box");a.append("rect").attr("x",t.x).attr("y",i).attr("rx","3").attr("width",t.dimension.width).attr("height",t.dimension.height).attr("stroke",t.visual.stroke).attr("fill",t.visual.fill),a.append("foreignObject").attr("x",t.x+n.boxPadding).attr("y",i+10).attr("width",t.dimension.width-2*n.boxPadding).attr("height",t.dimension.height-2*n.boxPadding).append("xhtml:div").style("display","table").style("height","100%").style("width","100%").append("span").style("display","table-cell").style("text-align","center").style("vertical-align","middle").html(t.text)}}o(ne,"renderD3Box");function ie(e,n){return e>n}o(ie,"dirUpwards");function ae(e,n,t,i){return a=>{const r=a.sourceBox.swimlane.y+n.swimlanePadding,d=a.targetBox.swimlane.y+n.swimlanePadding,l=ie(r,d),c=a.sourceBox.x+a.sourceBox.dimension.width*2/3,m=a.targetBox.x+a.targetBox.dimension.width/3;let x,u;g.debug(`rendering relation up=${l} for `,{sourceBox:a.sourceBox,targetBox:a.targetBox}),l?(x=r,u=d+a.targetBox.dimension.height):(x=r+a.sourceBox.dimension.height,u=d);const h=i.emRelationStroke??a.visual.stroke;e.append("path").attr("class","em-relation").attr("fill",a.visual.fill).attr("stroke",h).attr("stroke-width","1").attr("marker-end",`url(#${t})`).attr("d",`M${c} ${x} L${m} ${u}`)}}o(ae,"renderD3Relation");function re(e,n,t,i){return a=>{const r=e.append("g").attr("class","em-swimlane"),d=i.emSwimlaneBackgroundOdd??"rgb(250,250,250)",l=i.emSwimlaneBackgroundStroke??"rgb(240,240,240)";r.append("rect").attr("x",0).attr("y",a.y).attr("rx","3").attr("width",n+t.swimlanePadding).attr("height",a.height).attr("fill",d).attr("stroke",l),r.append("text").attr("font-weight",t.swimlaneTextFontWeight).attr("x",30).attr("y",a.y+30).text(a.label)}}o(re,"renderD3Swimlane");var $e=o(function(e,n,t,i){if(g.debug("in eventmodeling renderer",e+` `,"id:",n,t),!Re)throw new Error("EventModeling config not found");const a=i.db,{themeVariables:r,eventmodeling:d}=T(),l=we(`[id="${n}"]`),c=a.getDiagramProps(),m=a.getState(),x=`em-arrowhead-${n}`,u=r.emArrowhead??"#000000";m.sortedSwimlanesArray.forEach(re(l,m.maxR,c,r)),m.boxes.forEach(ne(l,c)),m.relations.forEach(ae(l,c,x,r)),l.append("defs").append("marker").attr("id",x).attr("markerWidth","10").attr("markerHeight","7").attr("refX","10").attr("refY","3.5").attr("orient","auto").append("polygon").attr("points","0 0, 10 3.5, 0 7").attr("fill",u),xe(void 0,l,(d==null?void 0:d.padding)??30,d==null?void 0:d.useMaxWidth)},"draw"),Te={draw:$e},De=o(e=>"","getStyles"),Ne=De,Ve={parser:Ae,db:F,renderer:Te,styles:Ne};export{Ve as diagram}; diff --git a/static/ml_canvas/assets/diagram-VX7I27RA-CkGIU6Vi.js b/static/ml_canvas/assets/diagram-VX7I27RA-BgSJwATP.js similarity index 97% rename from static/ml_canvas/assets/diagram-VX7I27RA-CkGIU6Vi.js rename to static/ml_canvas/assets/diagram-VX7I27RA-BgSJwATP.js index aeaffbbac..6ce69b70b 100644 --- a/static/ml_canvas/assets/diagram-VX7I27RA-CkGIU6Vi.js +++ b/static/ml_canvas/assets/diagram-VX7I27RA-BgSJwATP.js @@ -1,4 +1,4 @@ -import{p as ge}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{_ as w,E as ye,x as ae,z as ee,C as Se,d as ve,l as te,at as B,b as xe,a as be,m as we,n as Ce,g as Te,s as Le,A as $e,au as Ae,o as Fe}from"./mermaid.core-BCO0YdKy.js";import{s as Ne}from"./chunk-POPQ4Y6H-BOk39pqP.js";import{p as Me}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import{s as U}from"./vendor-flow-bDma3vSM.js";import{af as O,o as Q}from"./vendor-charts-CwfdE1jD.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";function _e(t){var a=0,l=t.children,n=l&&l.length;if(!n)a=1;else for(;--n>=0;)a+=l[n].value;t.value=a}function ke(){return this.eachAfter(_e)}function ze(t,a){let l=-1;for(const n of this)t.call(a,n,++l,this);return this}function Ve(t,a){for(var l=this,n=[l],r,s,h=-1;l=n.pop();)if(t.call(a,l,++h,this),r=l.children)for(s=r.length-1;s>=0;--s)n.push(r[s]);return this}function De(t,a){for(var l=this,n=[l],r=[],s,h,d,g=-1;l=n.pop();)if(r.push(l),s=l.children)for(h=0,d=s.length;h=0;)l+=n[r].value;a.value=l})}function Ee(t){return this.eachBefore(function(a){a.children&&a.children.sort(t)})}function Re(t){for(var a=this,l=We(a,t),n=[a];a!==l;)a=a.parent,n.push(a);for(var r=n.length;t!==l;)n.splice(r,0,t),t=t.parent;return n}function We(t,a){if(t===a)return t;var l=t.ancestors(),n=a.ancestors(),r=null;for(t=l.pop(),a=n.pop();t===a;)r=t,t=l.pop(),a=n.pop();return r}function He(){for(var t=this,a=[t];t=t.parent;)a.push(t);return a}function Ie(){return Array.from(this)}function Oe(){var t=[];return this.eachBefore(function(a){a.children||t.push(a)}),t}function Ge(){var t=this,a=[];return t.each(function(l){l!==t&&a.push({source:l.parent,target:l})}),a}function*qe(){var t=this,a,l=[t],n,r,s;do for(a=l.reverse(),l=[];t=a.pop();)if(yield t,n=t.children)for(r=0,s=n.length;r=0;--d)r.push(s=h[d]=new Z(h[d])),s.parent=n,s.depth=n.depth+1;return l.eachBefore(Ze)}function Xe(){return ne(this).eachBefore(Ue)}function Ye(t){return t.children}function je(t){return Array.isArray(t)?t[1]:null}function Ue(t){t.data.value!==void 0&&(t.value=t.data.value),t.data=t.data.data}function Ze(t){var a=0;do t.height=a;while((t=t.parent)&&t.height<++a)}function Z(t){this.data=t,this.depth=this.height=0,this.parent=null}Z.prototype=ne.prototype={constructor:Z,count:ke,each:ze,eachAfter:De,eachBefore:Ve,find:Pe,sum:Be,sort:Ee,path:Re,ancestors:He,descendants:Ie,leaves:Oe,links:Ge,copy:Xe,[Symbol.iterator]:qe};function Je(t){if(typeof t!="function")throw new Error;return t}function G(){return 0}function q(t){return function(){return t}}function Ke(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function Qe(t,a,l,n,r){for(var s=t.children,h,d=-1,g=s.length,c=t.value&&(n-a)/t.value;++dN&&(N=c),M=p*p*W,$=Math.max(N/M,M/y),$>V){p-=c;break}V=$}h.push(g={value:p,dice:x1?n:1)},l})(tt);function lt(){var t=nt,a=!1,l=1,n=1,r=[0],s=G,h=G,d=G,g=G,c=G;function u(i){return i.x0=i.y0=0,i.x1=l,i.y1=n,i.eachBefore(b),r=[0],a&&i.eachBefore(Ke),i}function b(i){var x=r[i.depth],S=i.x0+x,v=i.y0+x,p=i.x1-x,y=i.y1-x;p{Ae(s)&&(n!=null&&n.textStyles?n.textStyles.push(s):n.textStyles=[s]),n!=null&&n.styles?n.styles.push(s):n.styles=[s]}),this.classes.set(a,n)}getClasses(){return this.classes}getStylesForClass(a){var l;return((l=this.classes.get(a))==null?void 0:l.styles)??[]}clear(){Fe(),this.nodes=[],this.levels=new Map,this.outerNodes=[],this.classes=new Map,this.root=void 0}},w(R,"TreeMapDB"),R);function ce(t){if(!t.length)return[];const a=[],l=[];return t.forEach(n=>{const r={name:n.name,children:n.type==="Leaf"?void 0:[]};for(r.classSelector=n==null?void 0:n.classSelector,n!=null&&n.cssCompiledStyles&&(r.cssCompiledStyles=n.cssCompiledStyles),n.type==="Leaf"&&n.value!==void 0&&(r.value=n.value);l.length>0&&l[l.length-1].level>=n.level;)l.pop();if(l.length===0)a.push(r);else{const s=l[l.length-1].node;s.children?s.children.push(r):s.children=[r]}n.type!=="Leaf"&&l.push({node:r,level:n.level})}),a}w(ce,"buildHierarchy");var rt=w((t,a)=>{ge(t,a);const l=[];for(const s of t.TreemapRows??[])s.$type==="ClassDefStatement"&&a.addClass(s.className??"",s.styleText??"");for(const s of t.TreemapRows??[]){const h=s.item;if(!h)continue;const d=s.indent?parseInt(s.indent):0,g=st(h),c=h.classSelector?a.getStylesForClass(h.classSelector):[],u=c.length>0?c:void 0,b={level:d,name:g,type:h.$type,value:h.value,classSelector:h.classSelector,cssCompiledStyles:u};l.push(b)}const n=ce(l),r=w((s,h)=>{for(const d of s)a.addNode(d,h),d.children&&d.children.length>0&&r(d.children,h+1)},"addNodesRecursively");r(n,0)},"populate"),st=w(t=>t.name?String(t.name):"","getItemName"),he={parser:{yy:void 0},parse:w(async t=>{var a;try{const n=await Me("treemap",t);te.debug("Treemap AST:",n);const r=(a=he.parser)==null?void 0:a.yy;if(!(r instanceof oe))throw new Error("parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");rt(n,r)}catch(l){throw te.error("Error parsing treemap:",l),l}},"parse")},it=10,E=10,X=25,ot=w((t,a,l,n)=>{const r=n.db,s=r.getConfig(),h=s.padding??it,d=r.getDiagramTitle(),g=r.getRoot(),{themeVariables:c}=ae();if(!g)return;const u=d?30:0,b=Se(a),i=s.nodeWidth?s.nodeWidth*E:960,x=s.nodeHeight?s.nodeHeight*E:500,S=i,v=x+u;b.attr("viewBox",`0 0 ${S} ${v}`),ve(b,v,S,s.useMaxWidth);let p;try{const e=s.valueFormat||",";if(e==="$0,0")p=w(o=>"$"+O(",")(o),"valueFormat");else if(e.startsWith("$")&&e.includes(",")){const o=/\.\d+/.exec(e),f=o?o[0]:"";p=w(C=>"$"+O(","+f)(C),"valueFormat")}else if(e.startsWith("$")){const o=e.substring(1);p=w(f=>"$"+O(o||"")(f),"valueFormat")}else p=O(e)}catch(e){te.error("Error creating format function:",e),p=O(",")}const y=Q().range(["transparent",c.cScale0,c.cScale1,c.cScale2,c.cScale3,c.cScale4,c.cScale5,c.cScale6,c.cScale7,c.cScale8,c.cScale9,c.cScale10,c.cScale11]),N=Q().range(["transparent",c.cScalePeer0,c.cScalePeer1,c.cScalePeer2,c.cScalePeer3,c.cScalePeer4,c.cScalePeer5,c.cScalePeer6,c.cScalePeer7,c.cScalePeer8,c.cScalePeer9,c.cScalePeer10,c.cScalePeer11]),$=Q().range([c.cScaleLabel0,c.cScaleLabel1,c.cScaleLabel2,c.cScaleLabel3,c.cScaleLabel4,c.cScaleLabel5,c.cScaleLabel6,c.cScaleLabel7,c.cScaleLabel8,c.cScaleLabel9,c.cScaleLabel10,c.cScaleLabel11]);d&&b.append("text").attr("x",S/2).attr("y",u/2).attr("class","treemapTitle").attr("text-anchor","middle").attr("dominant-baseline","middle").text(d);const V=b.append("g").attr("transform",`translate(0, ${u})`).attr("class","treemapContainer"),W=ne(g).sum(e=>e.value??0).sort((e,o)=>(o.value??0)-(e.value??0)),le=lt().size([i,x]).paddingTop(e=>e.children&&e.children.length>0?X+E:0).paddingInner(h).paddingLeft(e=>e.children&&e.children.length>0?E:0).paddingRight(e=>e.children&&e.children.length>0?E:0).paddingBottom(e=>e.children&&e.children.length>0?E:0).round(!0)(W),de=le.descendants().filter(e=>e.children&&e.children.length>0),H=V.selectAll(".treemapSection").data(de).enter().append("g").attr("class","treemapSection").attr("transform",e=>`translate(${e.x0},${e.y0})`);H.append("rect").attr("width",e=>e.x1-e.x0).attr("height",X).attr("class","treemapSectionHeader").attr("fill","none").attr("fill-opacity",.6).attr("stroke-width",.6).attr("style",e=>e.depth===0?"display: none;":""),H.append("clipPath").attr("id",(e,o)=>`clip-section-${a}-${o}`).append("rect").attr("width",e=>Math.max(0,e.x1-e.x0-12)).attr("height",X),H.append("rect").attr("width",e=>e.x1-e.x0).attr("height",e=>e.y1-e.y0).attr("class",(e,o)=>`treemapSection section${o}`).attr("fill",e=>y(e.data.name)).attr("fill-opacity",.6).attr("stroke",e=>N(e.data.name)).attr("stroke-width",2).attr("stroke-opacity",.4).attr("style",e=>{if(e.depth===0)return"display: none;";const o=B({cssCompiledStyles:e.data.cssCompiledStyles});return o.nodeStyles+";"+o.borderStyles.join(";")}),H.append("text").attr("class","treemapSectionLabel").attr("x",6).attr("y",X/2).attr("dominant-baseline","middle").text(e=>e.depth===0?"":e.data.name).attr("font-weight","bold").attr("clip-path",(e,o)=>`url(#clip-section-${a}-${o})`).attr("style",e=>{if(e.depth===0)return"display: none;";const o="dominant-baseline: middle; font-size: 12px; fill:"+$(e.data.name)+"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",f=B({cssCompiledStyles:e.data.cssCompiledStyles});return o+f.labelStyles.replace("color:","fill:")}).each(function(e){if(e.depth===0)return;const o=U(this),f=e.data.name;o.text(f);const C=e.x1-e.x0,L=6;let T;s.showValues!==!1&&e.value?T=C-10-30-10-L:T=C-L-6;const m=Math.max(15,T),_=o.node();if(_.getComputedTextLength()>m){let z=f;for(;z.length>0;){if(z=f.substring(0,z.length-1),z.length===0){o.text("..."),_.getComputedTextLength()>m&&o.text("");break}if(o.text(z+"..."),_.getComputedTextLength()<=m)break}}}),s.showValues!==!1&&H.append("text").attr("class","treemapSectionValue").attr("x",e=>e.x1-e.x0-10).attr("y",X/2).attr("text-anchor","end").attr("dominant-baseline","middle").text(e=>e.value?p(e.value):"").attr("font-style","italic").attr("style",e=>{if(e.depth===0)return"display: none;";const o="text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:"+$(e.data.name)+"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",f=B({cssCompiledStyles:e.data.cssCompiledStyles});return o+f.labelStyles.replace("color:","fill:")});const re=le.leaves(),A=re.length>20,ue=A?16:38,Y=A?14:28,D=A?4:8,I=A?4:6,J=A?2:4,se=A?8:10,K=A?1:2,j=V.selectAll(".treemapLeafGroup").data(re).enter().append("g").attr("class",(e,o)=>`treemapNode treemapLeafGroup leaf${o}${e.data.classSelector?` ${e.data.classSelector}`:""}x`).attr("transform",e=>`translate(${e.x0},${e.y0})`);j.append("rect").attr("width",e=>e.x1-e.x0).attr("height",e=>e.y1-e.y0).attr("class","treemapLeaf").attr("fill",e=>e.parent?y(e.parent.data.name):y(e.data.name)).attr("style",e=>B({cssCompiledStyles:e.data.cssCompiledStyles}).nodeStyles).attr("fill-opacity",.3).attr("stroke",e=>e.parent?y(e.parent.data.name):y(e.data.name)).attr("stroke-width",3),j.append("clipPath").attr("id",(e,o)=>`clip-${a}-${o}`).append("rect").attr("width",e=>Math.max(0,e.x1-e.x0-4)).attr("height",e=>Math.max(0,e.y1-e.y0-4)),j.append("text").attr("class","treemapLabel").attr("x",e=>(e.x1-e.x0)/2).attr("y",e=>(e.y1-e.y0)/2).attr("style",e=>{const o=`text-anchor: middle; dominant-baseline: middle; font-size: ${ue}px;fill:`+$(e.data.name)+";",f=B({cssCompiledStyles:e.data.cssCompiledStyles});return o+f.labelStyles.replace("color:","fill:")}).attr("clip-path",(e,o)=>`url(#clip-${a}-${o})`).text(e=>e.data.name).each(function(e){const o=U(this),f=e.x1-e.x0,C=e.y1-e.y0,L=o.node(),T=f-2*J,P=C-2*J;if(TT&&m>D;)m--,o.style("font-size",`${m}px`);let F=Math.max(I,Math.min(Y,Math.round(m*_))),k=m+K+F;for(;k>P&&m>D&&(m--,F=Math.max(I,Math.min(Y,Math.round(m*_))),!(FT||m(o.x1-o.x0)/2).attr("y",function(o){return(o.y1-o.y0)/2}).attr("style",o=>{const f=`text-anchor: middle; dominant-baseline: hanging; font-size: ${Y}px;fill:`+$(o.data.name)+";",C=B({cssCompiledStyles:o.data.cssCompiledStyles});return f+C.labelStyles.replace("color:","fill:")}).attr("clip-path",(o,f)=>`url(#clip-${a}-${f})`).text(o=>o.value?p(o.value):"").each(function(o){const f=U(this),C=this.parentNode;if(!C){f.style("display","none");return}const L=U(C).select(".treemapLabel");if(L.empty()||L.style("display")==="none"){f.style("display","none");return}const T=parseFloat(L.style("font-size")),m=Math.max(I,Math.min(Y,Math.round(T*.6)));f.style("font-size",`${m}px`);const F=(o.y1-o.y0)/2+T/2+K;f.attr("y",F);const k=o.x1-o.x0,ie=o.y1-o.y0-4,me=k-2*J;f.node().getComputedTextLength()>me||F+m>ie||m{const a=ye(),l=ae(),n=ee(a,l.themeVariables),r=ee(dt,t),s=r.titleColor??n.titleColor,h=r.labelColor??n.textColor,d=r.valueColor??n.textColor;return` +import{p as ge}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{_ as w,E as ye,x as ae,z as ee,C as Se,d as ve,l as te,at as B,b as xe,a as be,m as we,n as Ce,g as Te,s as Le,A as $e,au as Ae,o as Fe}from"./mermaid.core-BRmiRRt4.js";import{s as Ne}from"./chunk-POPQ4Y6H-BR_pO24v.js";import{p as Me}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import{s as U}from"./vendor-flow-bDma3vSM.js";import{af as O,o as Q}from"./vendor-charts-CwfdE1jD.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";function _e(t){var a=0,l=t.children,n=l&&l.length;if(!n)a=1;else for(;--n>=0;)a+=l[n].value;t.value=a}function ke(){return this.eachAfter(_e)}function ze(t,a){let l=-1;for(const n of this)t.call(a,n,++l,this);return this}function Ve(t,a){for(var l=this,n=[l],r,s,h=-1;l=n.pop();)if(t.call(a,l,++h,this),r=l.children)for(s=r.length-1;s>=0;--s)n.push(r[s]);return this}function De(t,a){for(var l=this,n=[l],r=[],s,h,d,g=-1;l=n.pop();)if(r.push(l),s=l.children)for(h=0,d=s.length;h=0;)l+=n[r].value;a.value=l})}function Ee(t){return this.eachBefore(function(a){a.children&&a.children.sort(t)})}function Re(t){for(var a=this,l=We(a,t),n=[a];a!==l;)a=a.parent,n.push(a);for(var r=n.length;t!==l;)n.splice(r,0,t),t=t.parent;return n}function We(t,a){if(t===a)return t;var l=t.ancestors(),n=a.ancestors(),r=null;for(t=l.pop(),a=n.pop();t===a;)r=t,t=l.pop(),a=n.pop();return r}function He(){for(var t=this,a=[t];t=t.parent;)a.push(t);return a}function Ie(){return Array.from(this)}function Oe(){var t=[];return this.eachBefore(function(a){a.children||t.push(a)}),t}function Ge(){var t=this,a=[];return t.each(function(l){l!==t&&a.push({source:l.parent,target:l})}),a}function*qe(){var t=this,a,l=[t],n,r,s;do for(a=l.reverse(),l=[];t=a.pop();)if(yield t,n=t.children)for(r=0,s=n.length;r=0;--d)r.push(s=h[d]=new Z(h[d])),s.parent=n,s.depth=n.depth+1;return l.eachBefore(Ze)}function Xe(){return ne(this).eachBefore(Ue)}function Ye(t){return t.children}function je(t){return Array.isArray(t)?t[1]:null}function Ue(t){t.data.value!==void 0&&(t.value=t.data.value),t.data=t.data.data}function Ze(t){var a=0;do t.height=a;while((t=t.parent)&&t.height<++a)}function Z(t){this.data=t,this.depth=this.height=0,this.parent=null}Z.prototype=ne.prototype={constructor:Z,count:ke,each:ze,eachAfter:De,eachBefore:Ve,find:Pe,sum:Be,sort:Ee,path:Re,ancestors:He,descendants:Ie,leaves:Oe,links:Ge,copy:Xe,[Symbol.iterator]:qe};function Je(t){if(typeof t!="function")throw new Error;return t}function G(){return 0}function q(t){return function(){return t}}function Ke(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function Qe(t,a,l,n,r){for(var s=t.children,h,d=-1,g=s.length,c=t.value&&(n-a)/t.value;++dN&&(N=c),M=p*p*W,$=Math.max(N/M,M/y),$>V){p-=c;break}V=$}h.push(g={value:p,dice:x1?n:1)},l})(tt);function lt(){var t=nt,a=!1,l=1,n=1,r=[0],s=G,h=G,d=G,g=G,c=G;function u(i){return i.x0=i.y0=0,i.x1=l,i.y1=n,i.eachBefore(b),r=[0],a&&i.eachBefore(Ke),i}function b(i){var x=r[i.depth],S=i.x0+x,v=i.y0+x,p=i.x1-x,y=i.y1-x;p{Ae(s)&&(n!=null&&n.textStyles?n.textStyles.push(s):n.textStyles=[s]),n!=null&&n.styles?n.styles.push(s):n.styles=[s]}),this.classes.set(a,n)}getClasses(){return this.classes}getStylesForClass(a){var l;return((l=this.classes.get(a))==null?void 0:l.styles)??[]}clear(){Fe(),this.nodes=[],this.levels=new Map,this.outerNodes=[],this.classes=new Map,this.root=void 0}},w(R,"TreeMapDB"),R);function ce(t){if(!t.length)return[];const a=[],l=[];return t.forEach(n=>{const r={name:n.name,children:n.type==="Leaf"?void 0:[]};for(r.classSelector=n==null?void 0:n.classSelector,n!=null&&n.cssCompiledStyles&&(r.cssCompiledStyles=n.cssCompiledStyles),n.type==="Leaf"&&n.value!==void 0&&(r.value=n.value);l.length>0&&l[l.length-1].level>=n.level;)l.pop();if(l.length===0)a.push(r);else{const s=l[l.length-1].node;s.children?s.children.push(r):s.children=[r]}n.type!=="Leaf"&&l.push({node:r,level:n.level})}),a}w(ce,"buildHierarchy");var rt=w((t,a)=>{ge(t,a);const l=[];for(const s of t.TreemapRows??[])s.$type==="ClassDefStatement"&&a.addClass(s.className??"",s.styleText??"");for(const s of t.TreemapRows??[]){const h=s.item;if(!h)continue;const d=s.indent?parseInt(s.indent):0,g=st(h),c=h.classSelector?a.getStylesForClass(h.classSelector):[],u=c.length>0?c:void 0,b={level:d,name:g,type:h.$type,value:h.value,classSelector:h.classSelector,cssCompiledStyles:u};l.push(b)}const n=ce(l),r=w((s,h)=>{for(const d of s)a.addNode(d,h),d.children&&d.children.length>0&&r(d.children,h+1)},"addNodesRecursively");r(n,0)},"populate"),st=w(t=>t.name?String(t.name):"","getItemName"),he={parser:{yy:void 0},parse:w(async t=>{var a;try{const n=await Me("treemap",t);te.debug("Treemap AST:",n);const r=(a=he.parser)==null?void 0:a.yy;if(!(r instanceof oe))throw new Error("parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");rt(n,r)}catch(l){throw te.error("Error parsing treemap:",l),l}},"parse")},it=10,E=10,X=25,ot=w((t,a,l,n)=>{const r=n.db,s=r.getConfig(),h=s.padding??it,d=r.getDiagramTitle(),g=r.getRoot(),{themeVariables:c}=ae();if(!g)return;const u=d?30:0,b=Se(a),i=s.nodeWidth?s.nodeWidth*E:960,x=s.nodeHeight?s.nodeHeight*E:500,S=i,v=x+u;b.attr("viewBox",`0 0 ${S} ${v}`),ve(b,v,S,s.useMaxWidth);let p;try{const e=s.valueFormat||",";if(e==="$0,0")p=w(o=>"$"+O(",")(o),"valueFormat");else if(e.startsWith("$")&&e.includes(",")){const o=/\.\d+/.exec(e),f=o?o[0]:"";p=w(C=>"$"+O(","+f)(C),"valueFormat")}else if(e.startsWith("$")){const o=e.substring(1);p=w(f=>"$"+O(o||"")(f),"valueFormat")}else p=O(e)}catch(e){te.error("Error creating format function:",e),p=O(",")}const y=Q().range(["transparent",c.cScale0,c.cScale1,c.cScale2,c.cScale3,c.cScale4,c.cScale5,c.cScale6,c.cScale7,c.cScale8,c.cScale9,c.cScale10,c.cScale11]),N=Q().range(["transparent",c.cScalePeer0,c.cScalePeer1,c.cScalePeer2,c.cScalePeer3,c.cScalePeer4,c.cScalePeer5,c.cScalePeer6,c.cScalePeer7,c.cScalePeer8,c.cScalePeer9,c.cScalePeer10,c.cScalePeer11]),$=Q().range([c.cScaleLabel0,c.cScaleLabel1,c.cScaleLabel2,c.cScaleLabel3,c.cScaleLabel4,c.cScaleLabel5,c.cScaleLabel6,c.cScaleLabel7,c.cScaleLabel8,c.cScaleLabel9,c.cScaleLabel10,c.cScaleLabel11]);d&&b.append("text").attr("x",S/2).attr("y",u/2).attr("class","treemapTitle").attr("text-anchor","middle").attr("dominant-baseline","middle").text(d);const V=b.append("g").attr("transform",`translate(0, ${u})`).attr("class","treemapContainer"),W=ne(g).sum(e=>e.value??0).sort((e,o)=>(o.value??0)-(e.value??0)),le=lt().size([i,x]).paddingTop(e=>e.children&&e.children.length>0?X+E:0).paddingInner(h).paddingLeft(e=>e.children&&e.children.length>0?E:0).paddingRight(e=>e.children&&e.children.length>0?E:0).paddingBottom(e=>e.children&&e.children.length>0?E:0).round(!0)(W),de=le.descendants().filter(e=>e.children&&e.children.length>0),H=V.selectAll(".treemapSection").data(de).enter().append("g").attr("class","treemapSection").attr("transform",e=>`translate(${e.x0},${e.y0})`);H.append("rect").attr("width",e=>e.x1-e.x0).attr("height",X).attr("class","treemapSectionHeader").attr("fill","none").attr("fill-opacity",.6).attr("stroke-width",.6).attr("style",e=>e.depth===0?"display: none;":""),H.append("clipPath").attr("id",(e,o)=>`clip-section-${a}-${o}`).append("rect").attr("width",e=>Math.max(0,e.x1-e.x0-12)).attr("height",X),H.append("rect").attr("width",e=>e.x1-e.x0).attr("height",e=>e.y1-e.y0).attr("class",(e,o)=>`treemapSection section${o}`).attr("fill",e=>y(e.data.name)).attr("fill-opacity",.6).attr("stroke",e=>N(e.data.name)).attr("stroke-width",2).attr("stroke-opacity",.4).attr("style",e=>{if(e.depth===0)return"display: none;";const o=B({cssCompiledStyles:e.data.cssCompiledStyles});return o.nodeStyles+";"+o.borderStyles.join(";")}),H.append("text").attr("class","treemapSectionLabel").attr("x",6).attr("y",X/2).attr("dominant-baseline","middle").text(e=>e.depth===0?"":e.data.name).attr("font-weight","bold").attr("clip-path",(e,o)=>`url(#clip-section-${a}-${o})`).attr("style",e=>{if(e.depth===0)return"display: none;";const o="dominant-baseline: middle; font-size: 12px; fill:"+$(e.data.name)+"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",f=B({cssCompiledStyles:e.data.cssCompiledStyles});return o+f.labelStyles.replace("color:","fill:")}).each(function(e){if(e.depth===0)return;const o=U(this),f=e.data.name;o.text(f);const C=e.x1-e.x0,L=6;let T;s.showValues!==!1&&e.value?T=C-10-30-10-L:T=C-L-6;const m=Math.max(15,T),_=o.node();if(_.getComputedTextLength()>m){let z=f;for(;z.length>0;){if(z=f.substring(0,z.length-1),z.length===0){o.text("..."),_.getComputedTextLength()>m&&o.text("");break}if(o.text(z+"..."),_.getComputedTextLength()<=m)break}}}),s.showValues!==!1&&H.append("text").attr("class","treemapSectionValue").attr("x",e=>e.x1-e.x0-10).attr("y",X/2).attr("text-anchor","end").attr("dominant-baseline","middle").text(e=>e.value?p(e.value):"").attr("font-style","italic").attr("style",e=>{if(e.depth===0)return"display: none;";const o="text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:"+$(e.data.name)+"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",f=B({cssCompiledStyles:e.data.cssCompiledStyles});return o+f.labelStyles.replace("color:","fill:")});const re=le.leaves(),A=re.length>20,ue=A?16:38,Y=A?14:28,D=A?4:8,I=A?4:6,J=A?2:4,se=A?8:10,K=A?1:2,j=V.selectAll(".treemapLeafGroup").data(re).enter().append("g").attr("class",(e,o)=>`treemapNode treemapLeafGroup leaf${o}${e.data.classSelector?` ${e.data.classSelector}`:""}x`).attr("transform",e=>`translate(${e.x0},${e.y0})`);j.append("rect").attr("width",e=>e.x1-e.x0).attr("height",e=>e.y1-e.y0).attr("class","treemapLeaf").attr("fill",e=>e.parent?y(e.parent.data.name):y(e.data.name)).attr("style",e=>B({cssCompiledStyles:e.data.cssCompiledStyles}).nodeStyles).attr("fill-opacity",.3).attr("stroke",e=>e.parent?y(e.parent.data.name):y(e.data.name)).attr("stroke-width",3),j.append("clipPath").attr("id",(e,o)=>`clip-${a}-${o}`).append("rect").attr("width",e=>Math.max(0,e.x1-e.x0-4)).attr("height",e=>Math.max(0,e.y1-e.y0-4)),j.append("text").attr("class","treemapLabel").attr("x",e=>(e.x1-e.x0)/2).attr("y",e=>(e.y1-e.y0)/2).attr("style",e=>{const o=`text-anchor: middle; dominant-baseline: middle; font-size: ${ue}px;fill:`+$(e.data.name)+";",f=B({cssCompiledStyles:e.data.cssCompiledStyles});return o+f.labelStyles.replace("color:","fill:")}).attr("clip-path",(e,o)=>`url(#clip-${a}-${o})`).text(e=>e.data.name).each(function(e){const o=U(this),f=e.x1-e.x0,C=e.y1-e.y0,L=o.node(),T=f-2*J,P=C-2*J;if(TT&&m>D;)m--,o.style("font-size",`${m}px`);let F=Math.max(I,Math.min(Y,Math.round(m*_))),k=m+K+F;for(;k>P&&m>D&&(m--,F=Math.max(I,Math.min(Y,Math.round(m*_))),!(FT||m(o.x1-o.x0)/2).attr("y",function(o){return(o.y1-o.y0)/2}).attr("style",o=>{const f=`text-anchor: middle; dominant-baseline: hanging; font-size: ${Y}px;fill:`+$(o.data.name)+";",C=B({cssCompiledStyles:o.data.cssCompiledStyles});return f+C.labelStyles.replace("color:","fill:")}).attr("clip-path",(o,f)=>`url(#clip-${a}-${f})`).text(o=>o.value?p(o.value):"").each(function(o){const f=U(this),C=this.parentNode;if(!C){f.style("display","none");return}const L=U(C).select(".treemapLabel");if(L.empty()||L.style("display")==="none"){f.style("display","none");return}const T=parseFloat(L.style("font-size")),m=Math.max(I,Math.min(Y,Math.round(T*.6)));f.style("font-size",`${m}px`);const F=(o.y1-o.y0)/2+T/2+K;f.attr("y",F);const k=o.x1-o.x0,ie=o.y1-o.y0-4,me=k-2*J;f.node().getComputedTextLength()>me||F+m>ie||m{const a=ye(),l=ae(),n=ee(a,l.themeVariables),r=ee(dt,t),s=r.titleColor??n.titleColor,h=r.labelColor??n.textColor,d=r.valueColor??n.textColor;return` .treemapNode.section { stroke: ${r.sectionStrokeColor}; stroke-width: ${r.sectionStrokeWidth}; diff --git a/static/ml_canvas/assets/diagram-Z3DM3KII-BwPVkxAQ.js b/static/ml_canvas/assets/diagram-Z3DM3KII-CcZJy4uA.js similarity index 95% rename from static/ml_canvas/assets/diagram-Z3DM3KII-BwPVkxAQ.js rename to static/ml_canvas/assets/diagram-Z3DM3KII-CcZJy4uA.js index 5b0e00d9c..390a8ff38 100644 --- a/static/ml_canvas/assets/diagram-Z3DM3KII-BwPVkxAQ.js +++ b/static/ml_canvas/assets/diagram-Z3DM3KII-CcZJy4uA.js @@ -1,4 +1,4 @@ -import{p as B}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{_ as b,z as u,C,d as S,l as w,b as D,a as T,m as z,n as P,g as A,s as E,x as F,A as W,o as _}from"./mermaid.core-BCO0YdKy.js";import{p as N}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import"./index-BXksgzya.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var L=W.packet,m,v=(m=class{constructor(){this.packet=[],this.setAccTitle=D,this.getAccTitle=T,this.setDiagramTitle=z,this.getDiagramTitle=P,this.getAccDescription=A,this.setAccDescription=E}getConfig(){const t=u({...L,...F().packet});return t.showBits&&(t.paddingY+=10),t}getPacket(){return this.packet}pushWord(t){t.length>0&&this.packet.push(t)}clear(){_(),this.packet=[]}},b(m,"PacketDB"),m),M=1e4,Y=b((e,t)=>{B(e,t);let o=-1,r=[],n=1;const{bitsPerRow:l}=t.getConfig();for(let{start:a,end:i,bits:d,label:c}of e.blocks){if(a!==void 0&&i!==void 0&&i{if(e.start===void 0)throw new Error("start should have been set during first phase");if(e.end===void 0)throw new Error("end should have been set during first phase");if(e.start>e.end)throw new Error(`Block start ${e.start} is greater than block end ${e.end}.`);if(e.end+1<=t*o)return[e,void 0];const r=t*o-1,n=t*o;return[{start:e.start,end:r,label:e.label,bits:r-e.start},{start:n,end:e.end,label:e.label,bits:e.end-n}]},"getNextFittingBlock"),x={parser:{yy:void 0},parse:b(async e=>{var r;const t=await N("packet",e),o=(r=x.parser)==null?void 0:r.yy;if(!(o instanceof v))throw new Error("parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");w.debug(t),Y(t,o)},"parse")},O=b((e,t,o,r)=>{const n=r.db,l=n.getConfig(),{rowHeight:a,paddingY:i,bitWidth:d,bitsPerRow:c}=l,p=n.getPacket(),s=n.getDiagramTitle(),h=a+i,g=h*(p.length+1)-(s?0:a),k=d*c+2,f=C(t);f.attr("viewBox",`0 0 ${k} ${g}`),S(f,g,k,l.useMaxWidth);for(const[y,$]of p.entries())j(f,$,y,l);f.append("text").text(s).attr("x",k/2).attr("y",g-h/2).attr("dominant-baseline","middle").attr("text-anchor","middle").attr("class","packetTitle")},"draw"),j=b((e,t,o,{rowHeight:r,paddingX:n,paddingY:l,bitWidth:a,bitsPerRow:i,showBits:d})=>{const c=e.append("g"),p=o*(r+l)+l;for(const s of t){const h=s.start%i*a+1,g=(s.end-s.start+1)*a-n;if(c.append("rect").attr("x",h).attr("y",p).attr("width",g).attr("height",r).attr("class","packetBlock"),c.append("text").attr("x",h+g/2).attr("y",p+r/2).attr("class","packetLabel").attr("dominant-baseline","middle").attr("text-anchor","middle").text(s.label),!d)continue;const k=s.end===s.start,f=p-2;c.append("text").attr("x",h+(k?g/2:0)).attr("y",f).attr("class","packetByte start").attr("dominant-baseline","auto").attr("text-anchor",k?"middle":"start").text(s.start),k||c.append("text").attr("x",h+g).attr("y",f).attr("class","packetByte end").attr("dominant-baseline","auto").attr("text-anchor","end").text(s.end)}},"drawWord"),G={draw:O},H={byteFontSize:"10px",startByteColor:"black",endByteColor:"black",labelColor:"black",labelFontSize:"12px",titleColor:"black",titleFontSize:"14px",blockStrokeColor:"black",blockStrokeWidth:"1",blockFillColor:"#efefef"},K=b(({packet:e}={})=>{const t=u(H,e);return` +import{p as B}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{_ as b,z as u,C,d as S,l as w,b as D,a as T,m as z,n as P,g as A,s as E,x as F,A as W,o as _}from"./mermaid.core-BRmiRRt4.js";import{p as N}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import"./index-DYMv5Ibu.js";import"./vendor-flow-bDma3vSM.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var L=W.packet,m,v=(m=class{constructor(){this.packet=[],this.setAccTitle=D,this.getAccTitle=T,this.setDiagramTitle=z,this.getDiagramTitle=P,this.getAccDescription=A,this.setAccDescription=E}getConfig(){const t=u({...L,...F().packet});return t.showBits&&(t.paddingY+=10),t}getPacket(){return this.packet}pushWord(t){t.length>0&&this.packet.push(t)}clear(){_(),this.packet=[]}},b(m,"PacketDB"),m),M=1e4,Y=b((e,t)=>{B(e,t);let o=-1,r=[],n=1;const{bitsPerRow:l}=t.getConfig();for(let{start:a,end:i,bits:d,label:c}of e.blocks){if(a!==void 0&&i!==void 0&&i{if(e.start===void 0)throw new Error("start should have been set during first phase");if(e.end===void 0)throw new Error("end should have been set during first phase");if(e.start>e.end)throw new Error(`Block start ${e.start} is greater than block end ${e.end}.`);if(e.end+1<=t*o)return[e,void 0];const r=t*o-1,n=t*o;return[{start:e.start,end:r,label:e.label,bits:r-e.start},{start:n,end:e.end,label:e.label,bits:e.end-n}]},"getNextFittingBlock"),x={parser:{yy:void 0},parse:b(async e=>{var r;const t=await N("packet",e),o=(r=x.parser)==null?void 0:r.yy;if(!(o instanceof v))throw new Error("parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");w.debug(t),Y(t,o)},"parse")},O=b((e,t,o,r)=>{const n=r.db,l=n.getConfig(),{rowHeight:a,paddingY:i,bitWidth:d,bitsPerRow:c}=l,p=n.getPacket(),s=n.getDiagramTitle(),h=a+i,g=h*(p.length+1)-(s?0:a),k=d*c+2,f=C(t);f.attr("viewBox",`0 0 ${k} ${g}`),S(f,g,k,l.useMaxWidth);for(const[y,$]of p.entries())j(f,$,y,l);f.append("text").text(s).attr("x",k/2).attr("y",g-h/2).attr("dominant-baseline","middle").attr("text-anchor","middle").attr("class","packetTitle")},"draw"),j=b((e,t,o,{rowHeight:r,paddingX:n,paddingY:l,bitWidth:a,bitsPerRow:i,showBits:d})=>{const c=e.append("g"),p=o*(r+l)+l;for(const s of t){const h=s.start%i*a+1,g=(s.end-s.start+1)*a-n;if(c.append("rect").attr("x",h).attr("y",p).attr("width",g).attr("height",r).attr("class","packetBlock"),c.append("text").attr("x",h+g/2).attr("y",p+r/2).attr("class","packetLabel").attr("dominant-baseline","middle").attr("text-anchor","middle").text(s.label),!d)continue;const k=s.end===s.start,f=p-2;c.append("text").attr("x",h+(k?g/2:0)).attr("y",f).attr("class","packetByte start").attr("dominant-baseline","auto").attr("text-anchor",k?"middle":"start").text(s.start),k||c.append("text").attr("x",h+g).attr("y",f).attr("class","packetByte end").attr("dominant-baseline","auto").attr("text-anchor","end").text(s.end)}},"drawWord"),G={draw:O},H={byteFontSize:"10px",startByteColor:"black",endByteColor:"black",labelColor:"black",labelFontSize:"12px",titleColor:"black",titleFontSize:"14px",blockStrokeColor:"black",blockStrokeWidth:"1",blockFillColor:"#efefef"},K=b(({packet:e}={})=>{const t=u(H,e);return` .packetByte { font-size: ${t.byteFontSize}; } diff --git a/static/ml_canvas/assets/ebnfDiagram-PWID7BFC-C7ZAuv-5.js b/static/ml_canvas/assets/ebnfDiagram-PWID7BFC-BcRWm148.js similarity index 84% rename from static/ml_canvas/assets/ebnfDiagram-PWID7BFC-C7ZAuv-5.js rename to static/ml_canvas/assets/ebnfDiagram-PWID7BFC-BcRWm148.js index 3afc81501..c84a13453 100644 --- a/static/ml_canvas/assets/ebnfDiagram-PWID7BFC-C7ZAuv-5.js +++ b/static/ml_canvas/assets/ebnfDiagram-PWID7BFC-BcRWm148.js @@ -1 +1 @@ -import{g as m,r as l,d as n}from"./chunk-SVP7TREG-Bg03xQLN.js";import{p}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{_ as t,l as o}from"./mermaid.core-BCO0YdKy.js";import"./vendor-flow-bDma3vSM.js";import{M as u,a as f}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var c=f().RailroadEbnf.parser.LangiumParser,s=t(e=>{const r=e.alternatives.map(E);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformChoice"),E=t(e=>{const r=e.elements.map(d);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformSequence"),i=t(e=>{switch(e.$type){case"EbnfTerminal":return{type:"terminal",value:e.value};case"EbnfNonTerminal":return{type:"nonterminal",name:e.name};case"EbnfSpecial":return{type:"special",text:e.text};case"EbnfGroup":return s(e.element);case"EbnfOptional":return{type:"optional",element:s(e.element)};case"EbnfRepetition":return{type:"repetition",element:s(e.element),min:0,max:1/0};default:throw new Error(`Unsupported EBNF primary node: ${e.$type}`)}},"transformPrimary"),b=t((e,r)=>{switch(r.$type){case"EbnfOptionalPostfix":return{type:"optional",element:e};case"EbnfZeroOrMorePostfix":return{type:"repetition",element:e,min:0,max:1/0};case"EbnfOneOrMorePostfix":return{type:"repetition",element:e,min:1,max:1/0};case"EbnfExceptionPostfix":return{type:"sequence",elements:[e,{type:"terminal",value:"-"},i(r.except)]};default:throw new Error(`Unsupported EBNF postfix node: ${r.$type}`)}},"transformPostfix"),d=t(e=>e.postfixes.reduce((r,a)=>b(r,a),i(e.base)),"transformTerm"),y=t(e=>({name:e.name,definition:s(e.definition)}),"transformRule"),v=t(e=>{p(e,n),e.title&&n.setTitle(e.title),e.rules.map(r=>n.addRule(y(r)))},"populateDb"),g={parse:t(e=>{n.clear(),o.debug("[EBNF Parser] Starting Langium parse");const r=c.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new u(r);const a=r.value;o.debug("[EBNF Parser] Parsed rules:",a.rules.length),v(a),o.debug("[EBNF Parser] Parse complete")},"parse"),parser:{yy:n}},B={parser:g,db:n,renderer:l,styles:m};export{B as diagram}; +import{g as m,r as l,d as n}from"./chunk-SVP7TREG-CbDuCHXJ.js";import{p}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{_ as t,l as o}from"./mermaid.core-BRmiRRt4.js";import"./vendor-flow-bDma3vSM.js";import{M as u,a as f}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var c=f().RailroadEbnf.parser.LangiumParser,s=t(e=>{const r=e.alternatives.map(E);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformChoice"),E=t(e=>{const r=e.elements.map(d);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformSequence"),i=t(e=>{switch(e.$type){case"EbnfTerminal":return{type:"terminal",value:e.value};case"EbnfNonTerminal":return{type:"nonterminal",name:e.name};case"EbnfSpecial":return{type:"special",text:e.text};case"EbnfGroup":return s(e.element);case"EbnfOptional":return{type:"optional",element:s(e.element)};case"EbnfRepetition":return{type:"repetition",element:s(e.element),min:0,max:1/0};default:throw new Error(`Unsupported EBNF primary node: ${e.$type}`)}},"transformPrimary"),b=t((e,r)=>{switch(r.$type){case"EbnfOptionalPostfix":return{type:"optional",element:e};case"EbnfZeroOrMorePostfix":return{type:"repetition",element:e,min:0,max:1/0};case"EbnfOneOrMorePostfix":return{type:"repetition",element:e,min:1,max:1/0};case"EbnfExceptionPostfix":return{type:"sequence",elements:[e,{type:"terminal",value:"-"},i(r.except)]};default:throw new Error(`Unsupported EBNF postfix node: ${r.$type}`)}},"transformPostfix"),d=t(e=>e.postfixes.reduce((r,a)=>b(r,a),i(e.base)),"transformTerm"),y=t(e=>({name:e.name,definition:s(e.definition)}),"transformRule"),v=t(e=>{p(e,n),e.title&&n.setTitle(e.title),e.rules.map(r=>n.addRule(y(r)))},"populateDb"),g={parse:t(e=>{n.clear(),o.debug("[EBNF Parser] Starting Langium parse");const r=c.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new u(r);const a=r.value;o.debug("[EBNF Parser] Parsed rules:",a.rules.length),v(a),o.debug("[EBNF Parser] Parse complete")},"parse"),parser:{yy:n}},B={parser:g,db:n,renderer:l,styles:m};export{B as diagram}; diff --git a/static/ml_canvas/assets/erDiagram-RLTQ6QDP-g1-M1oAm.js b/static/ml_canvas/assets/erDiagram-RLTQ6QDP-Dw35YtFf.js similarity index 98% rename from static/ml_canvas/assets/erDiagram-RLTQ6QDP-g1-M1oAm.js rename to static/ml_canvas/assets/erDiagram-RLTQ6QDP-Dw35YtFf.js index a3c9b967d..444f8af52 100644 --- a/static/ml_canvas/assets/erDiagram-RLTQ6QDP-g1-M1oAm.js +++ b/static/ml_canvas/assets/erDiagram-RLTQ6QDP-Dw35YtFf.js @@ -1,4 +1,4 @@ -import{g as Ut}from"./chunk-XXDRQBXY-CZsBIZJg.js";import{s as Kt}from"./chunk-POPQ4Y6H-BOk39pqP.js";import{_ as f,b as Zt,a as jt,s as qt,g as Wt,m as Ht,n as Qt,c as tt,l as F,j as Xt,o as Jt,p as $t,r as te,q as ee,t as se,u as ie,v as re}from"./mermaid.core-BCO0YdKy.js";import{s as ne}from"./vendor-flow-bDma3vSM.js";import{c as ae}from"./channel-Dp8JVrfa.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var Ot=(function(){var s=f(function(G,a,h,d){for(h=h||{},d=G.length;d--;h[G[d]]=a);return h},"o"),n=[6,9,21,23,25,27,34,37,38,39,40,41,43,46,47,51,53,54,55],c=[2,2],o=[1,7],r=[1,9],l=[1,10],y=[1,11],b=[1,12],k=[1,30],R=[1,23],p=[1,24],g=[1,25],C=[1,26],v=[1,27],x=[1,19],T=[1,28],I=[1,29],N=[1,20],D=[1,18],L=[1,21],w=[1,22],xt=[2,6],u=[6,9,21,23,25,27,33,34,37,38,39,40,41,43,46,47,51,53,54,55],pt=[1,36],ft=[1,37],bt=[1,38],gt=[1,39],yt=[1,40],Z=[6,9,12,14,16,19,20,21,23,25,27,33,34,37,38,39,40,41,43,46,47,50,51,53,54,55,69,70,71,72,73],V=[1,46],M=[1,47],j=[1,57],q=[43,51,53,54,55,74,75],W=[1,70],H=[1,68],B=[1,65],Q=[1,69],X=[1,71],et=[6,9,12,16,21,23,25,27,33,34,37,38,39,40,41,43,44,45,46,47,51,52,53,54,55,69,70,71,72,73],st=[1,78],it=[1,77],rt=[1,76],Nt=[69,70,71,72,73],Ct=[1,91],It=[6,9,45,50],z=[6,9,12,44,45,50,51,52],nt=[1,101],at=[1,100],ot=[1,99],J=[18,61],At=[1,110],Rt=[1,109],vt=[20,43,51,53,54,55],_t=[18,61,64,66],kt={trace:f(function(){},"trace"),yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,line:7,statement:8,NEWLINE:9,entityName:10,relSpec:11,COLON:12,role:13,STYLE_SEPARATOR:14,idList:15,BLOCK_START:16,attributes:17,BLOCK_STOP:18,SQS:19,SQE:20,title:21,title_value:22,acc_title:23,acc_title_value:24,acc_descr:25,acc_descr_value:26,acc_descr_multiline_value:27,direction:28,classDefStatement:29,classStatement:30,styleStatement:31,subgraphHeader:32,END:33,SUBGRAPH:34,separator:35,subgraphTitle:36,direction_tb:37,direction_bt:38,direction_rl:39,direction_lr:40,CLASSDEF:41,stylesOpt:42,UNICODE_TEXT:43,STYLE_TEXT:44,COMMA:45,CLASS:46,STYLE:47,style:48,styleComponent:49,SEMI:50,NUM:51,BRKT:52,ENTITY_NAME:53,DECIMAL_NUM:54,ENTITY_ONE:55,attribute:56,attributeType:57,attributeName:58,attributeKeyTypeList:59,attributeComment:60,ATTRIBUTE_WORD:61,"?":62,attributeKeyType:63,",":64,ATTRIBUTE_KEY:65,COMMENT:66,cardinality:67,relType:68,ZERO_OR_ONE:69,ZERO_OR_MORE:70,ONE_OR_MORE:71,ONLY_ONE:72,MD_PARENT:73,NON_IDENTIFYING:74,IDENTIFYING:75,WORD:76,$accept:0,$end:1},terminals_:{2:"error",4:"ER_DIAGRAM",6:"EOF",9:"NEWLINE",12:"COLON",14:"STYLE_SEPARATOR",16:"BLOCK_START",18:"BLOCK_STOP",19:"SQS",20:"SQE",21:"title",22:"title_value",23:"acc_title",24:"acc_title_value",25:"acc_descr",26:"acc_descr_value",27:"acc_descr_multiline_value",33:"END",34:"SUBGRAPH",37:"direction_tb",38:"direction_bt",39:"direction_rl",40:"direction_lr",41:"CLASSDEF",43:"UNICODE_TEXT",44:"STYLE_TEXT",45:"COMMA",46:"CLASS",47:"STYLE",50:"SEMI",51:"NUM",52:"BRKT",53:"ENTITY_NAME",54:"DECIMAL_NUM",55:"ENTITY_ONE",61:"ATTRIBUTE_WORD",62:"?",64:",",65:"ATTRIBUTE_KEY",66:"COMMENT",69:"ZERO_OR_ONE",70:"ZERO_OR_MORE",71:"ONE_OR_MORE",72:"ONLY_ONE",73:"MD_PARENT",74:"NON_IDENTIFYING",75:"IDENTIFYING",76:"WORD"},productions_:[0,[3,3],[5,0],[5,2],[7,1],[7,1],[7,1],[8,5],[8,9],[8,7],[8,7],[8,4],[8,6],[8,3],[8,5],[8,1],[8,3],[8,7],[8,9],[8,6],[8,8],[8,4],[8,6],[8,2],[8,2],[8,2],[8,1],[8,1],[8,1],[8,1],[8,1],[8,3],[32,3],[32,6],[36,1],[36,2],[28,1],[28,1],[28,1],[28,1],[29,4],[15,1],[15,1],[15,3],[15,3],[30,3],[31,4],[42,1],[42,3],[48,1],[48,2],[35,1],[35,1],[35,1],[49,1],[49,1],[49,1],[49,1],[10,1],[10,1],[10,1],[10,1],[10,1],[17,1],[17,2],[56,2],[56,3],[56,3],[56,4],[57,1],[57,2],[58,1],[59,1],[59,3],[63,1],[60,1],[11,3],[67,1],[67,1],[67,1],[67,1],[67,1],[68,1],[68,1],[13,1],[13,1],[13,1]],performAction:f(function(a,h,d,i,_,t,$){var e=t.length-1;switch(_){case 1:break;case 2:this.$=[];break;case 3:this.$=t[e-1].concat(t[e]);break;case 4:this.$=t[e];break;case 5:case 6:this.$=[];break;case 7:i.addEntity(t[e-4]),i.addEntity(t[e-2]),i.addRelationship(t[e-4],t[e],t[e-2],t[e-3]),this.$=[t[e-4],t[e-2]];break;case 8:i.addEntity(t[e-8]),i.addEntity(t[e-4]),i.addRelationship(t[e-8],t[e],t[e-4],t[e-5]),i.setClass([t[e-8]],t[e-6]),i.setClass([t[e-4]],t[e-2]),this.$=[t[e-8],t[e-4]];break;case 9:i.addEntity(t[e-6]),i.addEntity(t[e-2]),i.addRelationship(t[e-6],t[e],t[e-2],t[e-3]),i.setClass([t[e-6]],t[e-4]),this.$=[t[e-6],t[e-2]];break;case 10:i.addEntity(t[e-6]),i.addEntity(t[e-4]),i.addRelationship(t[e-6],t[e],t[e-4],t[e-5]),i.setClass([t[e-4]],t[e-2]),this.$=[t[e-6],t[e-4]];break;case 11:i.addEntity(t[e-3]),i.addAttributes(t[e-3],t[e-1]),this.$=[t[e-3]];break;case 12:i.addEntity(t[e-5]),i.addAttributes(t[e-5],t[e-1]),i.setClass([t[e-5]],t[e-3]),this.$=[t[e-5]];break;case 13:i.addEntity(t[e-2]),this.$=[t[e-2]];break;case 14:i.addEntity(t[e-4]),i.setClass([t[e-4]],t[e-2]),this.$=[t[e-4]];break;case 15:i.addEntity(t[e]),this.$=[t[e]];break;case 16:i.addEntity(t[e-2]),i.setClass([t[e-2]],t[e]),this.$=[t[e-2]];break;case 17:i.addEntity(t[e-6],t[e-4]),i.addAttributes(t[e-6],t[e-1]),this.$=[t[e-6]];break;case 18:i.addEntity(t[e-8],t[e-6]),i.addAttributes(t[e-8],t[e-1]),i.setClass([t[e-8]],t[e-3]),this.$=[t[e-8]];break;case 19:i.addEntity(t[e-5],t[e-3]),this.$=[t[e-5]];break;case 20:i.addEntity(t[e-7],t[e-5]),i.setClass([t[e-7]],t[e-2]),this.$=[t[e-7]];break;case 21:i.addEntity(t[e-3],t[e-1]);break;case 22:i.addEntity(t[e-5],t[e-3]),i.setClass([t[e-5]],t[e]);break;case 23:case 24:this.$=t[e].trim(),i.setAccTitle(this.$);break;case 25:case 26:this.$=t[e].trim(),i.setAccDescription(this.$);break;case 27:i.subgraphDepth?this.$=t[e]:(i.setDirection(t[e].value),this.$=[]);break;case 31:i.subgraphDepth=(i.subgraphDepth||1)-1,this.$=i.addSubGraph({text:t[e-2].id},t[e-1],{text:t[e-2].text});break;case 32:i.subgraphDepth=(i.subgraphDepth||0)+1,this.$={id:t[e-1],text:t[e-1]};break;case 33:i.subgraphDepth=(i.subgraphDepth||0)+1,this.$={id:t[e-4],text:t[e-2]};break;case 34:case 59:case 60:case 61:case 62:case 86:this.$=t[e];break;case 35:this.$=t[e-1]+" "+t[e];break;case 36:this.$={stmt:"dir",value:"TB"};break;case 37:this.$={stmt:"dir",value:"BT"};break;case 38:this.$={stmt:"dir",value:"RL"};break;case 39:this.$={stmt:"dir",value:"LR"};break;case 40:this.$=t[e-3],i.addClass(t[e-2],t[e-1]);break;case 41:case 42:case 63:case 72:this.$=[t[e]];break;case 43:case 44:this.$=t[e-2].concat([t[e]]);break;case 45:this.$=t[e-2],i.setClass(t[e-1],t[e]);break;case 46:this.$=t[e-3],i.addCssStyles(t[e-2],t[e-1]);break;case 47:this.$=[t[e]];break;case 48:t[e-2].push(t[e]),this.$=t[e-2];break;case 50:this.$=t[e-1]+t[e];break;case 58:case 84:case 85:this.$=t[e].replace(/"/g,"");break;case 64:t[e].push(t[e-1]),this.$=t[e];break;case 65:this.$={type:t[e-1],name:t[e]};break;case 66:this.$={type:t[e-2],name:t[e-1],keys:t[e]};break;case 67:this.$={type:t[e-2],name:t[e-1],comment:t[e]};break;case 68:this.$={type:t[e-3],name:t[e-2],keys:t[e-1],comment:t[e]};break;case 69:case 71:case 74:this.$=t[e];break;case 70:this.$=t[e-1]+t[e];break;case 73:t[e-2].push(t[e]),this.$=t[e-2];break;case 75:this.$=t[e].replace(/"/g,"");break;case 76:this.$={cardA:t[e],relType:t[e-1],cardB:t[e-2]};break;case 77:this.$=i.Cardinality.ZERO_OR_ONE;break;case 78:this.$=i.Cardinality.ZERO_OR_MORE;break;case 79:this.$=i.Cardinality.ONE_OR_MORE;break;case 80:this.$=i.Cardinality.ONLY_ONE;break;case 81:this.$=i.Cardinality.MD_PARENT;break;case 82:this.$=i.Identification.NON_IDENTIFYING;break;case 83:this.$=i.Identification.IDENTIFYING;break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},s(n,c,{5:3}),{6:[1,4],7:5,8:6,9:o,10:8,21:r,23:l,25:y,27:b,28:13,29:14,30:15,31:16,32:17,34:k,37:R,38:p,39:g,40:C,41:v,43:x,46:T,47:I,51:N,53:D,54:L,55:w},s(n,xt,{1:[2,1]}),s(u,[2,3]),s(u,[2,4]),s(u,[2,5]),s(u,[2,15],{11:31,67:35,14:[1,32],16:[1,33],19:[1,34],69:pt,70:ft,71:bt,72:gt,73:yt}),{22:[1,41]},{24:[1,42]},{26:[1,43]},s(u,[2,26]),s(u,[2,27]),s(u,[2,28]),s(u,[2,29]),s(u,[2,30]),s(u,c,{5:44}),s(Z,[2,58]),s(Z,[2,59]),s(Z,[2,60]),s(Z,[2,61]),s(Z,[2,62]),s(u,[2,36]),s(u,[2,37]),s(u,[2,38]),s(u,[2,39]),{15:45,43:V,44:M},{15:48,43:V,44:M},{15:49,43:V,44:M},{10:50,43:x,51:N,53:D,54:L,55:w},{10:51,43:x,51:N,53:D,54:L,55:w},{15:52,43:V,44:M},{17:53,18:[1,54],56:55,57:56,61:j},{10:58,43:x,51:N,53:D,54:L,55:w},{68:59,74:[1,60],75:[1,61]},s(q,[2,77]),s(q,[2,78]),s(q,[2,79]),s(q,[2,80]),s(q,[2,81]),s(u,[2,23]),s(u,[2,24]),s(u,[2,25]),{6:[1,63],7:5,8:6,9:o,10:8,21:r,23:l,25:y,27:b,28:13,29:14,30:15,31:16,32:17,33:[1,62],34:k,37:R,38:p,39:g,40:C,41:v,43:x,46:T,47:I,51:N,53:D,54:L,55:w},{12:W,42:64,44:H,45:B,48:66,49:67,51:Q,52:X},s(et,[2,41]),s(et,[2,42]),{15:72,43:V,44:M,45:B},{12:W,42:73,44:H,45:B,48:66,49:67,51:Q,52:X},{6:st,9:it,19:[1,75],35:74,50:rt},{12:[1,79],14:[1,80]},s(u,[2,16],{67:35,11:81,16:[1,82],45:B,69:pt,70:ft,71:bt,72:gt,73:yt}),{18:[1,83]},s(u,[2,13]),{17:84,18:[2,63],56:55,57:56,61:j},{58:85,61:[1,86]},{61:[2,69],62:[1,87]},{20:[1,88]},{67:89,69:pt,70:ft,71:bt,72:gt,73:yt},s(Nt,[2,82]),s(Nt,[2,83]),s(u,[2,31]),s(u,xt),{6:st,9:it,35:90,45:Ct,50:rt},{43:[1,92],44:[1,93]},s(It,[2,47],{49:94,12:W,44:H,51:Q,52:X}),s(z,[2,49]),s(z,[2,54]),s(z,[2,55]),s(z,[2,56]),s(z,[2,57]),s(u,[2,45],{45:B}),{6:st,9:it,35:95,45:Ct,50:rt},s(u,[2,32]),{10:97,36:96,43:x,51:N,53:D,54:L,55:w},s(u,[2,51]),s(u,[2,52]),s(u,[2,53]),{13:98,43:nt,53:at,76:ot},{15:102,43:V,44:M},{10:103,43:x,51:N,53:D,54:L,55:w},{17:104,18:[1,105],56:55,57:56,61:j},s(u,[2,11]),{18:[2,64]},s(J,[2,65],{59:106,60:107,63:108,65:At,66:Rt}),s([18,61,65,66],[2,71]),{61:[2,70]},s(u,[2,21],{14:[1,112],16:[1,111]}),s([43,51,53,54,55],[2,76]),s(u,[2,40]),{12:W,44:H,48:113,49:67,51:Q,52:X},s(et,[2,43]),s(et,[2,44]),s(z,[2,50]),s(u,[2,46]),{10:115,20:[1,114],43:x,51:N,53:D,54:L,55:w},s(vt,[2,34]),s(u,[2,7]),s(u,[2,84]),s(u,[2,85]),s(u,[2,86]),{12:[1,116],45:B},{12:[1,118],14:[1,117]},{18:[1,119]},s(u,[2,14]),s(J,[2,66],{60:120,64:[1,121],66:Rt}),s(J,[2,67]),s(_t,[2,72]),s(J,[2,75]),s(_t,[2,74]),{17:122,18:[1,123],56:55,57:56,61:j},{15:124,43:V,44:M},s(It,[2,48],{49:94,12:W,44:H,51:Q,52:X}),{6:st,9:it,35:125,50:rt},s(vt,[2,35]),{13:126,43:nt,53:at,76:ot},{15:127,43:V,44:M},{13:128,43:nt,53:at,76:ot},s(u,[2,12]),s(J,[2,68]),{63:129,65:At},{18:[1,130]},s(u,[2,19]),s(u,[2,22],{16:[1,131],45:B}),s(u,[2,33]),s(u,[2,10]),{12:[1,132],45:B},s(u,[2,9]),s(_t,[2,73]),s(u,[2,17]),{17:133,18:[1,134],56:55,57:56,61:j},{13:135,43:nt,53:at,76:ot},{18:[1,136]},s(u,[2,20]),s(u,[2,8]),s(u,[2,18])],defaultActions:{84:[2,64],87:[2,70]},parseError:f(function(a,h){if(h.recoverable)this.trace(a);else{var d=new Error(a);throw d.hash=h,d}},"parseError"),parse:f(function(a){var h=this,d=[0],i=[],_=[null],t=[],$=this.table,e="",lt=0,Dt=0,Ft=2,Lt=1,Yt=t.slice.call(arguments,1),m=Object.create(this.lexer),Y={yy:{}};for(var mt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,mt)&&(Y.yy[mt]=this.yy[mt]);m.setInput(a,Y.yy),Y.yy.lexer=m,Y.yy.parser=this,typeof m.yylloc>"u"&&(m.yylloc={});var Et=m.yylloc;t.push(Et);var Pt=m.options&&m.options.ranges;typeof Y.yy.parseError=="function"?this.parseError=Y.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function zt(S){d.length=d.length-2*S,_.length=_.length-S,t.length=t.length-S}f(zt,"popStack");function wt(){var S;return S=i.pop()||m.lex()||Lt,typeof S!="number"&&(S instanceof Array&&(i=S,S=i.pop()),S=h.symbols_[S]||S),S}f(wt,"lex");for(var E,P,O,St,U={},ht,A,Vt,ut;;){if(P=d[d.length-1],this.defaultActions[P]?O=this.defaultActions[P]:((E===null||typeof E>"u")&&(E=wt()),O=$[P]&&$[P][E]),typeof O>"u"||!O.length||!O[0]){var Tt="";ut=[];for(ht in $[P])this.terminals_[ht]&&ht>Ft&&ut.push("'"+this.terminals_[ht]+"'");m.showPosition?Tt="Parse error on line "+(lt+1)+`: +import{g as Ut}from"./chunk-XXDRQBXY-DdoFz10O.js";import{s as Kt}from"./chunk-POPQ4Y6H-BR_pO24v.js";import{_ as f,b as Zt,a as jt,s as qt,g as Wt,m as Ht,n as Qt,c as tt,l as F,j as Xt,o as Jt,p as $t,r as te,q as ee,t as se,u as ie,v as re}from"./mermaid.core-BRmiRRt4.js";import{s as ne}from"./vendor-flow-bDma3vSM.js";import{c as ae}from"./channel-CtKHr9fF.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var Ot=(function(){var s=f(function(G,a,h,d){for(h=h||{},d=G.length;d--;h[G[d]]=a);return h},"o"),n=[6,9,21,23,25,27,34,37,38,39,40,41,43,46,47,51,53,54,55],c=[2,2],o=[1,7],r=[1,9],l=[1,10],y=[1,11],b=[1,12],k=[1,30],R=[1,23],p=[1,24],g=[1,25],C=[1,26],v=[1,27],x=[1,19],T=[1,28],I=[1,29],N=[1,20],D=[1,18],L=[1,21],w=[1,22],xt=[2,6],u=[6,9,21,23,25,27,33,34,37,38,39,40,41,43,46,47,51,53,54,55],pt=[1,36],ft=[1,37],bt=[1,38],gt=[1,39],yt=[1,40],Z=[6,9,12,14,16,19,20,21,23,25,27,33,34,37,38,39,40,41,43,46,47,50,51,53,54,55,69,70,71,72,73],V=[1,46],M=[1,47],j=[1,57],q=[43,51,53,54,55,74,75],W=[1,70],H=[1,68],B=[1,65],Q=[1,69],X=[1,71],et=[6,9,12,16,21,23,25,27,33,34,37,38,39,40,41,43,44,45,46,47,51,52,53,54,55,69,70,71,72,73],st=[1,78],it=[1,77],rt=[1,76],Nt=[69,70,71,72,73],Ct=[1,91],It=[6,9,45,50],z=[6,9,12,44,45,50,51,52],nt=[1,101],at=[1,100],ot=[1,99],J=[18,61],At=[1,110],Rt=[1,109],vt=[20,43,51,53,54,55],_t=[18,61,64,66],kt={trace:f(function(){},"trace"),yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,line:7,statement:8,NEWLINE:9,entityName:10,relSpec:11,COLON:12,role:13,STYLE_SEPARATOR:14,idList:15,BLOCK_START:16,attributes:17,BLOCK_STOP:18,SQS:19,SQE:20,title:21,title_value:22,acc_title:23,acc_title_value:24,acc_descr:25,acc_descr_value:26,acc_descr_multiline_value:27,direction:28,classDefStatement:29,classStatement:30,styleStatement:31,subgraphHeader:32,END:33,SUBGRAPH:34,separator:35,subgraphTitle:36,direction_tb:37,direction_bt:38,direction_rl:39,direction_lr:40,CLASSDEF:41,stylesOpt:42,UNICODE_TEXT:43,STYLE_TEXT:44,COMMA:45,CLASS:46,STYLE:47,style:48,styleComponent:49,SEMI:50,NUM:51,BRKT:52,ENTITY_NAME:53,DECIMAL_NUM:54,ENTITY_ONE:55,attribute:56,attributeType:57,attributeName:58,attributeKeyTypeList:59,attributeComment:60,ATTRIBUTE_WORD:61,"?":62,attributeKeyType:63,",":64,ATTRIBUTE_KEY:65,COMMENT:66,cardinality:67,relType:68,ZERO_OR_ONE:69,ZERO_OR_MORE:70,ONE_OR_MORE:71,ONLY_ONE:72,MD_PARENT:73,NON_IDENTIFYING:74,IDENTIFYING:75,WORD:76,$accept:0,$end:1},terminals_:{2:"error",4:"ER_DIAGRAM",6:"EOF",9:"NEWLINE",12:"COLON",14:"STYLE_SEPARATOR",16:"BLOCK_START",18:"BLOCK_STOP",19:"SQS",20:"SQE",21:"title",22:"title_value",23:"acc_title",24:"acc_title_value",25:"acc_descr",26:"acc_descr_value",27:"acc_descr_multiline_value",33:"END",34:"SUBGRAPH",37:"direction_tb",38:"direction_bt",39:"direction_rl",40:"direction_lr",41:"CLASSDEF",43:"UNICODE_TEXT",44:"STYLE_TEXT",45:"COMMA",46:"CLASS",47:"STYLE",50:"SEMI",51:"NUM",52:"BRKT",53:"ENTITY_NAME",54:"DECIMAL_NUM",55:"ENTITY_ONE",61:"ATTRIBUTE_WORD",62:"?",64:",",65:"ATTRIBUTE_KEY",66:"COMMENT",69:"ZERO_OR_ONE",70:"ZERO_OR_MORE",71:"ONE_OR_MORE",72:"ONLY_ONE",73:"MD_PARENT",74:"NON_IDENTIFYING",75:"IDENTIFYING",76:"WORD"},productions_:[0,[3,3],[5,0],[5,2],[7,1],[7,1],[7,1],[8,5],[8,9],[8,7],[8,7],[8,4],[8,6],[8,3],[8,5],[8,1],[8,3],[8,7],[8,9],[8,6],[8,8],[8,4],[8,6],[8,2],[8,2],[8,2],[8,1],[8,1],[8,1],[8,1],[8,1],[8,3],[32,3],[32,6],[36,1],[36,2],[28,1],[28,1],[28,1],[28,1],[29,4],[15,1],[15,1],[15,3],[15,3],[30,3],[31,4],[42,1],[42,3],[48,1],[48,2],[35,1],[35,1],[35,1],[49,1],[49,1],[49,1],[49,1],[10,1],[10,1],[10,1],[10,1],[10,1],[17,1],[17,2],[56,2],[56,3],[56,3],[56,4],[57,1],[57,2],[58,1],[59,1],[59,3],[63,1],[60,1],[11,3],[67,1],[67,1],[67,1],[67,1],[67,1],[68,1],[68,1],[13,1],[13,1],[13,1]],performAction:f(function(a,h,d,i,_,t,$){var e=t.length-1;switch(_){case 1:break;case 2:this.$=[];break;case 3:this.$=t[e-1].concat(t[e]);break;case 4:this.$=t[e];break;case 5:case 6:this.$=[];break;case 7:i.addEntity(t[e-4]),i.addEntity(t[e-2]),i.addRelationship(t[e-4],t[e],t[e-2],t[e-3]),this.$=[t[e-4],t[e-2]];break;case 8:i.addEntity(t[e-8]),i.addEntity(t[e-4]),i.addRelationship(t[e-8],t[e],t[e-4],t[e-5]),i.setClass([t[e-8]],t[e-6]),i.setClass([t[e-4]],t[e-2]),this.$=[t[e-8],t[e-4]];break;case 9:i.addEntity(t[e-6]),i.addEntity(t[e-2]),i.addRelationship(t[e-6],t[e],t[e-2],t[e-3]),i.setClass([t[e-6]],t[e-4]),this.$=[t[e-6],t[e-2]];break;case 10:i.addEntity(t[e-6]),i.addEntity(t[e-4]),i.addRelationship(t[e-6],t[e],t[e-4],t[e-5]),i.setClass([t[e-4]],t[e-2]),this.$=[t[e-6],t[e-4]];break;case 11:i.addEntity(t[e-3]),i.addAttributes(t[e-3],t[e-1]),this.$=[t[e-3]];break;case 12:i.addEntity(t[e-5]),i.addAttributes(t[e-5],t[e-1]),i.setClass([t[e-5]],t[e-3]),this.$=[t[e-5]];break;case 13:i.addEntity(t[e-2]),this.$=[t[e-2]];break;case 14:i.addEntity(t[e-4]),i.setClass([t[e-4]],t[e-2]),this.$=[t[e-4]];break;case 15:i.addEntity(t[e]),this.$=[t[e]];break;case 16:i.addEntity(t[e-2]),i.setClass([t[e-2]],t[e]),this.$=[t[e-2]];break;case 17:i.addEntity(t[e-6],t[e-4]),i.addAttributes(t[e-6],t[e-1]),this.$=[t[e-6]];break;case 18:i.addEntity(t[e-8],t[e-6]),i.addAttributes(t[e-8],t[e-1]),i.setClass([t[e-8]],t[e-3]),this.$=[t[e-8]];break;case 19:i.addEntity(t[e-5],t[e-3]),this.$=[t[e-5]];break;case 20:i.addEntity(t[e-7],t[e-5]),i.setClass([t[e-7]],t[e-2]),this.$=[t[e-7]];break;case 21:i.addEntity(t[e-3],t[e-1]);break;case 22:i.addEntity(t[e-5],t[e-3]),i.setClass([t[e-5]],t[e]);break;case 23:case 24:this.$=t[e].trim(),i.setAccTitle(this.$);break;case 25:case 26:this.$=t[e].trim(),i.setAccDescription(this.$);break;case 27:i.subgraphDepth?this.$=t[e]:(i.setDirection(t[e].value),this.$=[]);break;case 31:i.subgraphDepth=(i.subgraphDepth||1)-1,this.$=i.addSubGraph({text:t[e-2].id},t[e-1],{text:t[e-2].text});break;case 32:i.subgraphDepth=(i.subgraphDepth||0)+1,this.$={id:t[e-1],text:t[e-1]};break;case 33:i.subgraphDepth=(i.subgraphDepth||0)+1,this.$={id:t[e-4],text:t[e-2]};break;case 34:case 59:case 60:case 61:case 62:case 86:this.$=t[e];break;case 35:this.$=t[e-1]+" "+t[e];break;case 36:this.$={stmt:"dir",value:"TB"};break;case 37:this.$={stmt:"dir",value:"BT"};break;case 38:this.$={stmt:"dir",value:"RL"};break;case 39:this.$={stmt:"dir",value:"LR"};break;case 40:this.$=t[e-3],i.addClass(t[e-2],t[e-1]);break;case 41:case 42:case 63:case 72:this.$=[t[e]];break;case 43:case 44:this.$=t[e-2].concat([t[e]]);break;case 45:this.$=t[e-2],i.setClass(t[e-1],t[e]);break;case 46:this.$=t[e-3],i.addCssStyles(t[e-2],t[e-1]);break;case 47:this.$=[t[e]];break;case 48:t[e-2].push(t[e]),this.$=t[e-2];break;case 50:this.$=t[e-1]+t[e];break;case 58:case 84:case 85:this.$=t[e].replace(/"/g,"");break;case 64:t[e].push(t[e-1]),this.$=t[e];break;case 65:this.$={type:t[e-1],name:t[e]};break;case 66:this.$={type:t[e-2],name:t[e-1],keys:t[e]};break;case 67:this.$={type:t[e-2],name:t[e-1],comment:t[e]};break;case 68:this.$={type:t[e-3],name:t[e-2],keys:t[e-1],comment:t[e]};break;case 69:case 71:case 74:this.$=t[e];break;case 70:this.$=t[e-1]+t[e];break;case 73:t[e-2].push(t[e]),this.$=t[e-2];break;case 75:this.$=t[e].replace(/"/g,"");break;case 76:this.$={cardA:t[e],relType:t[e-1],cardB:t[e-2]};break;case 77:this.$=i.Cardinality.ZERO_OR_ONE;break;case 78:this.$=i.Cardinality.ZERO_OR_MORE;break;case 79:this.$=i.Cardinality.ONE_OR_MORE;break;case 80:this.$=i.Cardinality.ONLY_ONE;break;case 81:this.$=i.Cardinality.MD_PARENT;break;case 82:this.$=i.Identification.NON_IDENTIFYING;break;case 83:this.$=i.Identification.IDENTIFYING;break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},s(n,c,{5:3}),{6:[1,4],7:5,8:6,9:o,10:8,21:r,23:l,25:y,27:b,28:13,29:14,30:15,31:16,32:17,34:k,37:R,38:p,39:g,40:C,41:v,43:x,46:T,47:I,51:N,53:D,54:L,55:w},s(n,xt,{1:[2,1]}),s(u,[2,3]),s(u,[2,4]),s(u,[2,5]),s(u,[2,15],{11:31,67:35,14:[1,32],16:[1,33],19:[1,34],69:pt,70:ft,71:bt,72:gt,73:yt}),{22:[1,41]},{24:[1,42]},{26:[1,43]},s(u,[2,26]),s(u,[2,27]),s(u,[2,28]),s(u,[2,29]),s(u,[2,30]),s(u,c,{5:44}),s(Z,[2,58]),s(Z,[2,59]),s(Z,[2,60]),s(Z,[2,61]),s(Z,[2,62]),s(u,[2,36]),s(u,[2,37]),s(u,[2,38]),s(u,[2,39]),{15:45,43:V,44:M},{15:48,43:V,44:M},{15:49,43:V,44:M},{10:50,43:x,51:N,53:D,54:L,55:w},{10:51,43:x,51:N,53:D,54:L,55:w},{15:52,43:V,44:M},{17:53,18:[1,54],56:55,57:56,61:j},{10:58,43:x,51:N,53:D,54:L,55:w},{68:59,74:[1,60],75:[1,61]},s(q,[2,77]),s(q,[2,78]),s(q,[2,79]),s(q,[2,80]),s(q,[2,81]),s(u,[2,23]),s(u,[2,24]),s(u,[2,25]),{6:[1,63],7:5,8:6,9:o,10:8,21:r,23:l,25:y,27:b,28:13,29:14,30:15,31:16,32:17,33:[1,62],34:k,37:R,38:p,39:g,40:C,41:v,43:x,46:T,47:I,51:N,53:D,54:L,55:w},{12:W,42:64,44:H,45:B,48:66,49:67,51:Q,52:X},s(et,[2,41]),s(et,[2,42]),{15:72,43:V,44:M,45:B},{12:W,42:73,44:H,45:B,48:66,49:67,51:Q,52:X},{6:st,9:it,19:[1,75],35:74,50:rt},{12:[1,79],14:[1,80]},s(u,[2,16],{67:35,11:81,16:[1,82],45:B,69:pt,70:ft,71:bt,72:gt,73:yt}),{18:[1,83]},s(u,[2,13]),{17:84,18:[2,63],56:55,57:56,61:j},{58:85,61:[1,86]},{61:[2,69],62:[1,87]},{20:[1,88]},{67:89,69:pt,70:ft,71:bt,72:gt,73:yt},s(Nt,[2,82]),s(Nt,[2,83]),s(u,[2,31]),s(u,xt),{6:st,9:it,35:90,45:Ct,50:rt},{43:[1,92],44:[1,93]},s(It,[2,47],{49:94,12:W,44:H,51:Q,52:X}),s(z,[2,49]),s(z,[2,54]),s(z,[2,55]),s(z,[2,56]),s(z,[2,57]),s(u,[2,45],{45:B}),{6:st,9:it,35:95,45:Ct,50:rt},s(u,[2,32]),{10:97,36:96,43:x,51:N,53:D,54:L,55:w},s(u,[2,51]),s(u,[2,52]),s(u,[2,53]),{13:98,43:nt,53:at,76:ot},{15:102,43:V,44:M},{10:103,43:x,51:N,53:D,54:L,55:w},{17:104,18:[1,105],56:55,57:56,61:j},s(u,[2,11]),{18:[2,64]},s(J,[2,65],{59:106,60:107,63:108,65:At,66:Rt}),s([18,61,65,66],[2,71]),{61:[2,70]},s(u,[2,21],{14:[1,112],16:[1,111]}),s([43,51,53,54,55],[2,76]),s(u,[2,40]),{12:W,44:H,48:113,49:67,51:Q,52:X},s(et,[2,43]),s(et,[2,44]),s(z,[2,50]),s(u,[2,46]),{10:115,20:[1,114],43:x,51:N,53:D,54:L,55:w},s(vt,[2,34]),s(u,[2,7]),s(u,[2,84]),s(u,[2,85]),s(u,[2,86]),{12:[1,116],45:B},{12:[1,118],14:[1,117]},{18:[1,119]},s(u,[2,14]),s(J,[2,66],{60:120,64:[1,121],66:Rt}),s(J,[2,67]),s(_t,[2,72]),s(J,[2,75]),s(_t,[2,74]),{17:122,18:[1,123],56:55,57:56,61:j},{15:124,43:V,44:M},s(It,[2,48],{49:94,12:W,44:H,51:Q,52:X}),{6:st,9:it,35:125,50:rt},s(vt,[2,35]),{13:126,43:nt,53:at,76:ot},{15:127,43:V,44:M},{13:128,43:nt,53:at,76:ot},s(u,[2,12]),s(J,[2,68]),{63:129,65:At},{18:[1,130]},s(u,[2,19]),s(u,[2,22],{16:[1,131],45:B}),s(u,[2,33]),s(u,[2,10]),{12:[1,132],45:B},s(u,[2,9]),s(_t,[2,73]),s(u,[2,17]),{17:133,18:[1,134],56:55,57:56,61:j},{13:135,43:nt,53:at,76:ot},{18:[1,136]},s(u,[2,20]),s(u,[2,8]),s(u,[2,18])],defaultActions:{84:[2,64],87:[2,70]},parseError:f(function(a,h){if(h.recoverable)this.trace(a);else{var d=new Error(a);throw d.hash=h,d}},"parseError"),parse:f(function(a){var h=this,d=[0],i=[],_=[null],t=[],$=this.table,e="",lt=0,Dt=0,Ft=2,Lt=1,Yt=t.slice.call(arguments,1),m=Object.create(this.lexer),Y={yy:{}};for(var mt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,mt)&&(Y.yy[mt]=this.yy[mt]);m.setInput(a,Y.yy),Y.yy.lexer=m,Y.yy.parser=this,typeof m.yylloc>"u"&&(m.yylloc={});var Et=m.yylloc;t.push(Et);var Pt=m.options&&m.options.ranges;typeof Y.yy.parseError=="function"?this.parseError=Y.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function zt(S){d.length=d.length-2*S,_.length=_.length-S,t.length=t.length-S}f(zt,"popStack");function wt(){var S;return S=i.pop()||m.lex()||Lt,typeof S!="number"&&(S instanceof Array&&(i=S,S=i.pop()),S=h.symbols_[S]||S),S}f(wt,"lex");for(var E,P,O,St,U={},ht,A,Vt,ut;;){if(P=d[d.length-1],this.defaultActions[P]?O=this.defaultActions[P]:((E===null||typeof E>"u")&&(E=wt()),O=$[P]&&$[P][E]),typeof O>"u"||!O.length||!O[0]){var Tt="";ut=[];for(ht in $[P])this.terminals_[ht]&&ht>Ft&&ut.push("'"+this.terminals_[ht]+"'");m.showPosition?Tt="Parse error on line "+(lt+1)+`: `+m.showPosition()+` Expecting `+ut.join(", ")+", got '"+(this.terminals_[E]||E)+"'":Tt="Parse error on line "+(lt+1)+": Unexpected "+(E==Lt?"end of input":"'"+(this.terminals_[E]||E)+"'"),this.parseError(Tt,{text:m.match,token:this.terminals_[E]||E,line:m.yylineno,loc:Et,expected:ut})}if(O[0]instanceof Array&&O.length>1)throw new Error("Parse Error: multiple actions possible at state: "+P+", token: "+E);switch(O[0]){case 1:d.push(E),_.push(m.yytext),t.push(m.yylloc),d.push(O[1]),E=null,Dt=m.yyleng,e=m.yytext,lt=m.yylineno,Et=m.yylloc;break;case 2:if(A=this.productions_[O[1]][1],U.$=_[_.length-A],U._$={first_line:t[t.length-(A||1)].first_line,last_line:t[t.length-1].last_line,first_column:t[t.length-(A||1)].first_column,last_column:t[t.length-1].last_column},Pt&&(U._$.range=[t[t.length-(A||1)].range[0],t[t.length-1].range[1]]),St=this.performAction.apply(U,[e,Dt,lt,Y.yy,O[1],_,t].concat(Yt)),typeof St<"u")return St;A&&(d=d.slice(0,-1*A*2),_=_.slice(0,-1*A),t=t.slice(0,-1*A)),d.push(this.productions_[O[1]][0]),_.push(U.$),t.push(U._$),Vt=$[d[d.length-2]][d[d.length-1]],d.push(Vt);break;case 3:return!0}}return!0},"parse")},Gt=(function(){var G={EOF:1,parseError:f(function(h,d){if(this.yy.parser)this.yy.parser.parseError(h,d);else throw new Error(h)},"parseError"),setInput:f(function(a,h){return this.yy=h||this.yy||{},this._input=a,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:f(function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var h=a.match(/(?:\r\n?|\n).*/g);return h?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},"input"),unput:f(function(a){var h=a.length,d=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-h),this.offset-=h;var i=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),d.length-1&&(this.yylineno-=d.length-1);var _=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:d?(d.length===i.length?this.yylloc.first_column:0)+i[i.length-d.length].length-d[0].length:this.yylloc.first_column-h},this.options.ranges&&(this.yylloc.range=[_[0],_[0]+this.yyleng-h]),this.yyleng=this.yytext.length,this},"unput"),more:f(function(){return this._more=!0,this},"more"),reject:f(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:f(function(a){this.unput(this.match.slice(a))},"less"),pastInput:f(function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:f(function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:f(function(){var a=this.pastInput(),h=new Array(a.length+1).join("-");return a+this.upcomingInput()+` diff --git a/static/ml_canvas/assets/flowDiagram-HODETNUW-Bb_JgsYj.js b/static/ml_canvas/assets/flowDiagram-HODETNUW-Xqmx_yL9.js similarity index 99% rename from static/ml_canvas/assets/flowDiagram-HODETNUW-Bb_JgsYj.js rename to static/ml_canvas/assets/flowDiagram-HODETNUW-Xqmx_yL9.js index 98c1fb8e1..a06679e96 100644 --- a/static/ml_canvas/assets/flowDiagram-HODETNUW-Bb_JgsYj.js +++ b/static/ml_canvas/assets/flowDiagram-HODETNUW-Xqmx_yL9.js @@ -1,4 +1,4 @@ -import{g as Xt}from"./chunk-5VM5RSS4-W4WNe2RE.js";import{g as Qt}from"./chunk-XXDRQBXY-CZsBIZJg.js";import{s as Jt}from"./chunk-POPQ4Y6H-BOk39pqP.js";import{_ as k,a0 as Zt,G as Mt,l as $,c as ke,t as $t,u as e1,v as rt,b as t1,s as s1,m as i1,a as r1,g as a1,n as n1,j as u1,I as o1,J as l1,bi as c1,p as st,O as h1,o as d1,as as p1,r as f1}from"./mermaid.core-BCO0YdKy.js";import{f as g1}from"./chunk-F27PBJKO-Dm2Us476.js";import{s as it}from"./vendor-flow-bDma3vSM.js";import{c as b1}from"./channel-Dp8JVrfa.js";var A1="flowchart-",Pe,k1=(Pe=class{constructor(){this.vertexCounter=0,this.config=ke(),this.diagramId="",this.vertices=new Map,this.edges=[],this.classes=new Map,this.subGraphs=[],this.subGraphLookup=new Map,this.tooltips=new Map,this.subCount=0,this.firstGraphFlag=!0,this.secCount=-1,this.posCrossRef=[],this.funs=[],this.setAccTitle=t1,this.setAccDescription=s1,this.setDiagramTitle=i1,this.getAccTitle=r1,this.getAccDescription=a1,this.getDiagramTitle=n1,this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen("gen-2")}sanitizeText(i){return u1.sanitizeText(i,this.config)}sanitizeNodeLabelType(i){switch(i){case"markdown":case"string":case"text":return i;default:return"markdown"}}setDiagramId(i){this.diagramId=i}lookUpDomId(i){for(const r of this.vertices.values())if(r.id===i)return this.diagramId?`${this.diagramId}-${r.domId}`:r.domId;return this.diagramId?`${this.diagramId}-${i}`:i}addVertex(i,r,a,n,l,g,h={},m){var F,c;if(!i||i.trim().length===0)return;let u;if(m!==void 0){let d;m.includes(` +import{g as Xt}from"./chunk-5VM5RSS4-CKRC1CIZ.js";import{g as Qt}from"./chunk-XXDRQBXY-DdoFz10O.js";import{s as Jt}from"./chunk-POPQ4Y6H-BR_pO24v.js";import{_ as k,a0 as Zt,G as Mt,l as $,c as ke,t as $t,u as e1,v as rt,b as t1,s as s1,m as i1,a as r1,g as a1,n as n1,j as u1,I as o1,J as l1,bi as c1,p as st,O as h1,o as d1,as as p1,r as f1}from"./mermaid.core-BRmiRRt4.js";import{f as g1}from"./chunk-F27PBJKO-B7fm5O2R.js";import{s as it}from"./vendor-flow-bDma3vSM.js";import{c as b1}from"./channel-CtKHr9fF.js";var A1="flowchart-",Pe,k1=(Pe=class{constructor(){this.vertexCounter=0,this.config=ke(),this.diagramId="",this.vertices=new Map,this.edges=[],this.classes=new Map,this.subGraphs=[],this.subGraphLookup=new Map,this.tooltips=new Map,this.subCount=0,this.firstGraphFlag=!0,this.secCount=-1,this.posCrossRef=[],this.funs=[],this.setAccTitle=t1,this.setAccDescription=s1,this.setDiagramTitle=i1,this.getAccTitle=r1,this.getAccDescription=a1,this.getDiagramTitle=n1,this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen("gen-2")}sanitizeText(i){return u1.sanitizeText(i,this.config)}sanitizeNodeLabelType(i){switch(i){case"markdown":case"string":case"text":return i;default:return"markdown"}}setDiagramId(i){this.diagramId=i}lookUpDomId(i){for(const r of this.vertices.values())if(r.id===i)return this.diagramId?`${this.diagramId}-${r.domId}`:r.domId;return this.diagramId?`${this.diagramId}-${i}`:i}addVertex(i,r,a,n,l,g,h={},m){var F,c;if(!i||i.trim().length===0)return;let u;if(m!==void 0){let d;m.includes(` `)?d=m+` `:d=`{ `+m+` diff --git a/static/ml_canvas/assets/ganttDiagram-EL5Y4UJY-CcMHMo5K.js b/static/ml_canvas/assets/ganttDiagram-EL5Y4UJY-BmyJJ4Bd.js similarity index 99% rename from static/ml_canvas/assets/ganttDiagram-EL5Y4UJY-CcMHMo5K.js rename to static/ml_canvas/assets/ganttDiagram-EL5Y4UJY-BmyJJ4Bd.js index 6df4f7f27..221a5e129 100644 --- a/static/ml_canvas/assets/ganttDiagram-EL5Y4UJY-CcMHMo5K.js +++ b/static/ml_canvas/assets/ganttDiagram-EL5Y4UJY-BmyJJ4Bd.js @@ -1,4 +1,4 @@ -import{g as Te,s as be,n as we,m as _e,a as De,b as Se,_ as l,c as dt,d as Ce,ar as U,l as ot,j as Me,H as Ee,o as Ie,v as Ye}from"./mermaid.core-BCO0YdKy.js";import{g as It}from"./vendor-utils-_6D5wMFs.js";import{s as vt}from"./vendor-flow-bDma3vSM.js";import{Z as $e,_ as Ae,$ as Fe,m as Le,a0 as Oe,a1 as Zt,a2 as Qt,a3 as We,a4 as Pe,a5 as Ve,a6 as Re,a7 as ze,a8 as Ne,a9 as He,aa as Kt,ab as Jt,ac as te,ad as ee,ae as re}from"./vendor-charts-CwfdE1jD.js";import"./index-BXksgzya.js";function Be(t){return t}var Tt=1,$t=2,Ft=3,xt=4,se=1e-6;function qe(t){return"translate("+t+",0)"}function Ge(t){return"translate(0,"+t+")"}function Xe(t){return e=>+t(e)}function je(t,e){return e=Math.max(0,t.bandwidth()-e*2)/2,t.round()&&(e=Math.round(e)),s=>+t(s)+e}function Ue(){return!this.__axis}function de(t,e){var s=[],r=null,n=null,g=6,y=6,b=3,C=typeof window<"u"&&window.devicePixelRatio>1?0:.5,L=t===Tt||t===xt?-1:1,w=t===xt||t===$t?"x":"y",P=t===Tt||t===Ft?qe:Ge;function _(D){var G=r??(e.ticks?e.ticks.apply(e,s):e.domain()),N=n??(e.tickFormat?e.tickFormat.apply(e,s):Be),k=Math.max(g,0)+b,M=e.range(),W=+M[0]+C,O=+M[M.length-1]+C,H=(e.bandwidth?je:Xe)(e.copy(),C),z=D.selection?D.selection():D,I=z.selectAll(".domain").data([null]),x=z.selectAll(".tick").data(G,e).order(),h=x.exit(),E=x.enter().append("g").attr("class","tick"),f=x.select("line"),T=x.select("text");I=I.merge(I.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),x=x.merge(E),f=f.merge(E.append("line").attr("stroke","currentColor").attr(w+"2",L*g)),T=T.merge(E.append("text").attr("fill","currentColor").attr(w,L*k).attr("dy",t===Tt?"0em":t===Ft?"0.71em":"0.32em")),D!==z&&(I=I.transition(D),x=x.transition(D),f=f.transition(D),T=T.transition(D),h=h.transition(D).attr("opacity",se).attr("transform",function(v){return isFinite(v=H(v))?P(v+C):this.getAttribute("transform")}),E.attr("opacity",se).attr("transform",function(v){var p=this.parentNode.__axis;return P((p&&isFinite(p=p(v))?p:H(v))+C)})),h.remove(),I.attr("d",t===xt||t===$t?y?"M"+L*y+","+W+"H"+C+"V"+O+"H"+L*y:"M"+C+","+W+"V"+O:y?"M"+W+","+L*y+"V"+C+"H"+O+"V"+L*y:"M"+W+","+C+"H"+O),x.attr("opacity",1).attr("transform",function(v){return P(H(v)+C)}),f.attr(w+"2",L*g),T.attr(w,L*k).text(N),z.filter(Ue).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===$t?"start":t===xt?"end":"middle"),z.each(function(){this.__axis=H})}return _.scale=function(D){return arguments.length?(e=D,_):e},_.ticks=function(){return s=Array.from(arguments),_},_.tickArguments=function(D){return arguments.length?(s=D==null?[]:Array.from(D),_):s.slice()},_.tickValues=function(D){return arguments.length?(r=D==null?null:Array.from(D),_):r&&r.slice()},_.tickFormat=function(D){return arguments.length?(n=D,_):n},_.tickSize=function(D){return arguments.length?(g=y=+D,_):g},_.tickSizeInner=function(D){return arguments.length?(g=+D,_):g},_.tickSizeOuter=function(D){return arguments.length?(y=+D,_):y},_.tickPadding=function(D){return arguments.length?(b=+D,_):b},_.offset=function(D){return arguments.length?(C=+D,_):C},_}function Ze(t){return de(Tt,t)}function Qe(t){return de(Ft,t)}var bt={exports:{}},Ke=bt.exports,ie;function Je(){return ie||(ie=1,(function(t,e){(function(s,r){t.exports=r()})(Ke,(function(){var s="day";return function(r,n,g){var y=function(L){return L.add(4-L.isoWeekday(),s)},b=n.prototype;b.isoWeekYear=function(){return y(this).year()},b.isoWeek=function(L){if(!this.$utils().u(L))return this.add(7*(L-this.isoWeek()),s);var w,P,_,D,G=y(this),N=(w=this.isoWeekYear(),P=this.$u,_=(P?g.utc:g)().year(w).startOf("year"),D=4-_.isoWeekday(),_.isoWeekday()>4&&(D+=7),_.add(D,s));return G.diff(N,"week")+1},b.isoWeekday=function(L){return this.$utils().u(L)?this.day()||7:this.day(this.day()%7?L:L-7)};var C=b.startOf;b.startOf=function(L,w){var P=this.$utils(),_=!!P.u(w)||w;return P.p(L)==="isoweek"?_?this.date(this.date()-(this.isoWeekday()-1)).startOf("day"):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf("day"):C.bind(this)(L,w)}}}))})(bt)),bt.exports}var tr=Je();const er=It(tr);var wt={exports:{}},rr=wt.exports,ne;function sr(){return ne||(ne=1,(function(t,e){(function(s,r){t.exports=r()})(rr,(function(){var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},r=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,n=/\d/,g=/\d\d/,y=/\d\d?/,b=/\d*[^-_:/,()\s\d]+/,C={},L=function(k){return(k=+k)+(k>68?1900:2e3)},w=function(k){return function(M){this[k]=+M}},P=[/[+-]\d\d:?(\d\d)?|Z/,function(k){(this.zone||(this.zone={})).offset=(function(M){if(!M||M==="Z")return 0;var W=M.match(/([+-]|\d\d)/g),O=60*W[1]+(+W[2]||0);return O===0?0:W[0]==="+"?-O:O})(k)}],_=function(k){var M=C[k];return M&&(M.indexOf?M:M.s.concat(M.f))},D=function(k,M){var W,O=C.meridiem;if(O){for(var H=1;H<=24;H+=1)if(k.indexOf(O(H,0,M))>-1){W=H>12;break}}else W=k===(M?"pm":"PM");return W},G={A:[b,function(k){this.afternoon=D(k,!1)}],a:[b,function(k){this.afternoon=D(k,!0)}],Q:[n,function(k){this.month=3*(k-1)+1}],S:[n,function(k){this.milliseconds=100*+k}],SS:[g,function(k){this.milliseconds=10*+k}],SSS:[/\d{3}/,function(k){this.milliseconds=+k}],s:[y,w("seconds")],ss:[y,w("seconds")],m:[y,w("minutes")],mm:[y,w("minutes")],H:[y,w("hours")],h:[y,w("hours")],HH:[y,w("hours")],hh:[y,w("hours")],D:[y,w("day")],DD:[g,w("day")],Do:[b,function(k){var M=C.ordinal,W=k.match(/\d+/);if(this.day=W[0],M)for(var O=1;O<=31;O+=1)M(O).replace(/\[|\]/g,"")===k&&(this.day=O)}],w:[y,w("week")],ww:[g,w("week")],M:[y,w("month")],MM:[g,w("month")],MMM:[b,function(k){var M=_("months"),W=(_("monthsShort")||M.map((function(O){return O.slice(0,3)}))).indexOf(k)+1;if(W<1)throw new Error;this.month=W%12||W}],MMMM:[b,function(k){var M=_("months").indexOf(k)+1;if(M<1)throw new Error;this.month=M%12||M}],Y:[/[+-]?\d+/,w("year")],YY:[g,function(k){this.year=L(k)}],YYYY:[/\d{4}/,w("year")],Z:P,ZZ:P};function N(k){var M,W;M=k,W=C&&C.formats;for(var O=(k=M.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(f,T,v){var p=v&&v.toUpperCase();return T||W[v]||s[v]||W[p].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(a,d,m){return d||m.slice(1)}))}))).match(r),H=O.length,z=0;z-1)return new Date((S==="X"?1e3:1)*u);var o=N(S)(u),q=o.year,c=o.month,$=o.day,A=o.hours,R=o.minutes,F=o.seconds,B=o.milliseconds,V=o.zone,st=o.week,nt=new Date,yt=$||(q||c?1:nt.getDate()),lt=q||nt.getFullYear(),X=0;q&&!c||(X=c>0?c-1:nt.getMonth());var K,Z=A||0,at=R||0,J=F||0,it=B||0;return V?new Date(Date.UTC(lt,X,yt,Z,at,J,it+60*V.offset*1e3)):i?new Date(Date.UTC(lt,X,yt,Z,at,J,it)):(K=new Date(lt,X,yt,Z,at,J,it),st&&(K=Y(K).week(st).toDate()),K)}catch{return new Date("")}})(I,E,x,W),this.init(),p&&p!==!0&&(this.$L=this.locale(p).$L),v&&I!=this.format(E)&&(this.$d=new Date("")),C={}}else if(E instanceof Array)for(var a=E.length,d=1;d<=a;d+=1){h[1]=E[d-1];var m=W.apply(this,h);if(m.isValid()){this.$d=m.$d,this.$L=m.$L,this.init();break}d===a&&(this.$d=new Date(""))}else H.call(this,z)}}}))})(wt)),wt.exports}var ir=sr();const nr=It(ir);var _t={exports:{}},ar=_t.exports,ae;function or(){return ae||(ae=1,(function(t,e){(function(s,r){t.exports=r()})(ar,(function(){return function(s,r){var n=r.prototype,g=n.format;n.format=function(y){var b=this,C=this.$locale();if(!this.isValid())return g.bind(this)(y);var L=this.$utils(),w=(y||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(P){switch(P){case"Q":return Math.ceil((b.$M+1)/3);case"Do":return C.ordinal(b.$D);case"gggg":return b.weekYear();case"GGGG":return b.isoWeekYear();case"wo":return C.ordinal(b.week(),"W");case"w":case"ww":return L.s(b.week(),P==="w"?1:2,"0");case"W":case"WW":return L.s(b.isoWeek(),P==="W"?1:2,"0");case"k":case"kk":return L.s(String(b.$H===0?24:b.$H),P==="k"?1:2,"0");case"X":return Math.floor(b.$d.getTime()/1e3);case"x":return b.$d.getTime();case"z":return"["+b.offsetName()+"]";case"zzz":return"["+b.offsetName("long")+"]";default:return P}}));return g.bind(this)(w)}}}))})(_t)),_t.exports}var cr=or();const lr=It(cr);var Dt={exports:{}},ur=Dt.exports,oe;function dr(){return oe||(oe=1,(function(t,e){(function(s,r){t.exports=r()})(ur,(function(){var s,r,n=1e3,g=6e4,y=36e5,b=864e5,C=31536e6,L=2628e6,w=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,P=/\[([^\]]+)]|YYYY|YY|Y|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS/g,_={years:C,months:L,days:b,hours:y,minutes:g,seconds:n,milliseconds:1,weeks:6048e5},D=function(I){return I instanceof H},G=function(I,x,h){return new H(I,h,x.$l)},N=function(I){return r.p(I)+"s"},k=function(I){return I<0},M=function(I){return k(I)?Math.ceil(I):Math.floor(I)},W=function(I){return Math.abs(I)},O=function(I,x){return I?k(I)?{negative:!0,format:""+W(I)+x}:{negative:!1,format:""+I+x}:{negative:!1,format:""}},H=(function(){function I(h,E,f){var T=this;if(this.$d={},this.$l=f,h===void 0&&(this.$ms=0,this.parseFromMilliseconds()),E)return G(h*_[N(E)],this);if(typeof h=="number")return this.$ms=h,this.parseFromMilliseconds(),this;if(typeof h=="object")return Object.keys(h).forEach((function(a){T.$d[N(a)]=h[a]})),this.calMilliseconds(),this;if(typeof h=="string"){var v=h.match(w);if(v){var p=v.slice(2).map((function(a){return a!=null?Number(a):0}));return this.$d.years=p[0],this.$d.months=p[1],this.$d.weeks=p[2],this.$d.days=p[3],this.$d.hours=p[4],this.$d.minutes=p[5],this.$d.seconds=p[6],this.calMilliseconds(),this}}return this}var x=I.prototype;return x.calMilliseconds=function(){var h=this;this.$ms=Object.keys(this.$d).reduce((function(E,f){return E+(h.$d[f]||0)*_[f]}),0)},x.parseFromMilliseconds=function(){var h=this.$ms;this.$d.years=M(h/C),h%=C,this.$d.months=M(h/L),h%=L,this.$d.days=M(h/b),h%=b,this.$d.hours=M(h/y),h%=y,this.$d.minutes=M(h/g),h%=g,this.$d.seconds=M(h/n),h%=n,this.$d.milliseconds=h},x.toISOString=function(){var h=O(this.$d.years,"Y"),E=O(this.$d.months,"M"),f=+this.$d.days||0;this.$d.weeks&&(f+=7*this.$d.weeks);var T=O(f,"D"),v=O(this.$d.hours,"H"),p=O(this.$d.minutes,"M"),a=this.$d.seconds||0;this.$d.milliseconds&&(a+=this.$d.milliseconds/1e3,a=Math.round(1e3*a)/1e3);var d=O(a,"S"),m=h.negative||E.negative||T.negative||v.negative||p.negative||d.negative,u=v.format||p.format||d.format?"T":"",S=(m?"-":"")+"P"+h.format+E.format+T.format+u+v.format+p.format+d.format;return S==="P"||S==="-P"?"P0D":S},x.toJSON=function(){return this.toISOString()},x.format=function(h){var E=h||"YYYY-MM-DDTHH:mm:ss",f={Y:this.$d.years,YY:r.s(this.$d.years,2,"0"),YYYY:r.s(this.$d.years,4,"0"),M:this.$d.months,MM:r.s(this.$d.months,2,"0"),D:this.$d.days,DD:r.s(this.$d.days,2,"0"),H:this.$d.hours,HH:r.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:r.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:r.s(this.$d.seconds,2,"0"),SSS:r.s(this.$d.milliseconds,3,"0")};return E.replace(P,(function(T,v){return v||String(f[T])}))},x.as=function(h){return this.$ms/_[N(h)]},x.get=function(h){var E=this.$ms,f=N(h);return f==="milliseconds"?E%=1e3:E=f==="weeks"?M(E/_[f]):this.$d[f],E||0},x.add=function(h,E,f){var T;return T=E?h*_[N(E)]:D(h)?h.$ms:G(h,this).$ms,G(this.$ms+T*(f?-1:1),this)},x.subtract=function(h,E){return this.add(h,E,!0)},x.locale=function(h){var E=this.clone();return E.$l=h,E},x.clone=function(){return G(this.$ms,this)},x.humanize=function(h){return s().add(this.$ms,"ms").locale(this.$l).fromNow(!h)},x.valueOf=function(){return this.asMilliseconds()},x.milliseconds=function(){return this.get("milliseconds")},x.asMilliseconds=function(){return this.as("milliseconds")},x.seconds=function(){return this.get("seconds")},x.asSeconds=function(){return this.as("seconds")},x.minutes=function(){return this.get("minutes")},x.asMinutes=function(){return this.as("minutes")},x.hours=function(){return this.get("hours")},x.asHours=function(){return this.as("hours")},x.days=function(){return this.get("days")},x.asDays=function(){return this.as("days")},x.weeks=function(){return this.get("weeks")},x.asWeeks=function(){return this.as("weeks")},x.months=function(){return this.get("months")},x.asMonths=function(){return this.as("months")},x.years=function(){return this.get("years")},x.asYears=function(){return this.as("years")},I})(),z=function(I,x,h){return I.add(x.years()*h,"y").add(x.months()*h,"M").add(x.days()*h,"d").add(x.hours()*h,"h").add(x.minutes()*h,"m").add(x.seconds()*h,"s").add(x.milliseconds()*h,"ms")};return function(I,x,h){s=h,r=h().$utils(),h.duration=function(T,v){var p=h.locale();return G(T,{$l:p},v)},h.isDuration=D;var E=x.prototype.add,f=x.prototype.subtract;x.prototype.add=function(T,v){return D(T)?z(this,T,1):E.bind(this)(T,v)},x.prototype.subtract=function(T,v){return D(T)?z(this,T,-1):f.bind(this)(T,v)}}}))})(Dt)),Dt.exports}var fr=dr();const hr=It(fr);var Lt=(function(){var t=l(function(p,a,d,m){for(d=d||{},m=p.length;m--;d[p[m]]=a);return d},"o"),e=[6,8,10,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,33,35,36,38,40],s=[1,26],r=[1,27],n=[1,28],g=[1,29],y=[1,30],b=[1,31],C=[1,32],L=[1,33],w=[1,34],P=[1,9],_=[1,10],D=[1,11],G=[1,12],N=[1,13],k=[1,14],M=[1,15],W=[1,16],O=[1,19],H=[1,20],z=[1,21],I=[1,22],x=[1,23],h=[1,25],E=[1,35],f={trace:l(function(){},"trace"),yy:{},symbols_:{error:2,start:3,gantt:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NL:10,weekday:11,weekday_monday:12,weekday_tuesday:13,weekday_wednesday:14,weekday_thursday:15,weekday_friday:16,weekday_saturday:17,weekday_sunday:18,weekend:19,weekend_friday:20,weekend_saturday:21,dateFormat:22,inclusiveEndDates:23,topAxis:24,axisFormat:25,tickInterval:26,excludes:27,includes:28,todayMarker:29,title:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,section:36,clickStatement:37,taskTxt:38,taskData:39,click:40,callbackname:41,callbackargs:42,href:43,clickStatementDebug:44,$accept:0,$end:1},terminals_:{2:"error",4:"gantt",6:"EOF",8:"SPACE",10:"NL",12:"weekday_monday",13:"weekday_tuesday",14:"weekday_wednesday",15:"weekday_thursday",16:"weekday_friday",17:"weekday_saturday",18:"weekday_sunday",20:"weekend_friday",21:"weekend_saturday",22:"dateFormat",23:"inclusiveEndDates",24:"topAxis",25:"axisFormat",26:"tickInterval",27:"excludes",28:"includes",29:"todayMarker",30:"title",31:"acc_title",32:"acc_title_value",33:"acc_descr",34:"acc_descr_value",35:"acc_descr_multiline_value",36:"section",38:"taskTxt",39:"taskData",40:"click",41:"callbackname",42:"callbackargs",43:"href"},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[19,1],[19,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,1],[9,2],[37,2],[37,3],[37,3],[37,4],[37,3],[37,4],[37,2],[44,2],[44,3],[44,3],[44,4],[44,3],[44,4],[44,2]],performAction:l(function(a,d,m,u,S,i,Y){var o=i.length-1;switch(S){case 1:return i[o-1];case 2:this.$=[];break;case 3:i[o-1].push(i[o]),this.$=i[o-1];break;case 4:case 5:this.$=i[o];break;case 6:case 7:this.$=[];break;case 8:u.setWeekday("monday");break;case 9:u.setWeekday("tuesday");break;case 10:u.setWeekday("wednesday");break;case 11:u.setWeekday("thursday");break;case 12:u.setWeekday("friday");break;case 13:u.setWeekday("saturday");break;case 14:u.setWeekday("sunday");break;case 15:u.setWeekend("friday");break;case 16:u.setWeekend("saturday");break;case 17:u.setDateFormat(i[o].substr(11)),this.$=i[o].substr(11);break;case 18:u.enableInclusiveEndDates(),this.$=i[o].substr(18);break;case 19:u.TopAxis(),this.$=i[o].substr(8);break;case 20:u.setAxisFormat(i[o].substr(11)),this.$=i[o].substr(11);break;case 21:u.setTickInterval(i[o].substr(13)),this.$=i[o].substr(13);break;case 22:u.setExcludes(i[o].substr(9)),this.$=i[o].substr(9);break;case 23:u.setIncludes(i[o].substr(9)),this.$=i[o].substr(9);break;case 24:u.setTodayMarker(i[o].substr(12)),this.$=i[o].substr(12);break;case 27:u.setDiagramTitle(i[o].substr(6)),this.$=i[o].substr(6);break;case 28:this.$=i[o].trim(),u.setAccTitle(this.$);break;case 29:case 30:this.$=i[o].trim(),u.setAccDescription(this.$);break;case 31:u.addSection(i[o].substr(8)),this.$=i[o].substr(8);break;case 33:u.addTask(i[o-1],i[o]),this.$="task";break;case 34:this.$=i[o-1],u.setClickEvent(i[o-1],i[o],null);break;case 35:this.$=i[o-2],u.setClickEvent(i[o-2],i[o-1],i[o]);break;case 36:this.$=i[o-2],u.setClickEvent(i[o-2],i[o-1],null),u.setLink(i[o-2],i[o]);break;case 37:this.$=i[o-3],u.setClickEvent(i[o-3],i[o-2],i[o-1]),u.setLink(i[o-3],i[o]);break;case 38:this.$=i[o-2],u.setClickEvent(i[o-2],i[o],null),u.setLink(i[o-2],i[o-1]);break;case 39:this.$=i[o-3],u.setClickEvent(i[o-3],i[o-1],i[o]),u.setLink(i[o-3],i[o-2]);break;case 40:this.$=i[o-1],u.setLink(i[o-1],i[o]);break;case 41:case 47:this.$=i[o-1]+" "+i[o];break;case 42:case 43:case 45:this.$=i[o-2]+" "+i[o-1]+" "+i[o];break;case 44:case 46:this.$=i[o-3]+" "+i[o-2]+" "+i[o-1]+" "+i[o];break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:17,12:s,13:r,14:n,15:g,16:y,17:b,18:C,19:18,20:L,21:w,22:P,23:_,24:D,25:G,26:N,27:k,28:M,29:W,30:O,31:H,33:z,35:I,36:x,37:24,38:h,40:E},t(e,[2,7],{1:[2,1]}),t(e,[2,3]),{9:36,11:17,12:s,13:r,14:n,15:g,16:y,17:b,18:C,19:18,20:L,21:w,22:P,23:_,24:D,25:G,26:N,27:k,28:M,29:W,30:O,31:H,33:z,35:I,36:x,37:24,38:h,40:E},t(e,[2,5]),t(e,[2,6]),t(e,[2,17]),t(e,[2,18]),t(e,[2,19]),t(e,[2,20]),t(e,[2,21]),t(e,[2,22]),t(e,[2,23]),t(e,[2,24]),t(e,[2,25]),t(e,[2,26]),t(e,[2,27]),{32:[1,37]},{34:[1,38]},t(e,[2,30]),t(e,[2,31]),t(e,[2,32]),{39:[1,39]},t(e,[2,8]),t(e,[2,9]),t(e,[2,10]),t(e,[2,11]),t(e,[2,12]),t(e,[2,13]),t(e,[2,14]),t(e,[2,15]),t(e,[2,16]),{41:[1,40],43:[1,41]},t(e,[2,4]),t(e,[2,28]),t(e,[2,29]),t(e,[2,33]),t(e,[2,34],{42:[1,42],43:[1,43]}),t(e,[2,40],{41:[1,44]}),t(e,[2,35],{43:[1,45]}),t(e,[2,36]),t(e,[2,38],{42:[1,46]}),t(e,[2,37]),t(e,[2,39])],defaultActions:{},parseError:l(function(a,d){if(d.recoverable)this.trace(a);else{var m=new Error(a);throw m.hash=d,m}},"parseError"),parse:l(function(a){var d=this,m=[0],u=[],S=[null],i=[],Y=this.table,o="",q=0,c=0,$=2,A=1,R=i.slice.call(arguments,1),F=Object.create(this.lexer),B={yy:{}};for(var V in this.yy)Object.prototype.hasOwnProperty.call(this.yy,V)&&(B.yy[V]=this.yy[V]);F.setInput(a,B.yy),B.yy.lexer=F,B.yy.parser=this,typeof F.yylloc>"u"&&(F.yylloc={});var st=F.yylloc;i.push(st);var nt=F.options&&F.options.ranges;typeof B.yy.parseError=="function"?this.parseError=B.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function yt(Q){m.length=m.length-2*Q,S.length=S.length-Q,i.length=i.length-Q}l(yt,"popStack");function lt(){var Q;return Q=u.pop()||F.lex()||A,typeof Q!="number"&&(Q instanceof Array&&(u=Q,Q=u.pop()),Q=d.symbols_[Q]||Q),Q}l(lt,"lex");for(var X,K,Z,at,J={},it,tt,Ut,pt;;){if(K=m[m.length-1],this.defaultActions[K]?Z=this.defaultActions[K]:((X===null||typeof X>"u")&&(X=lt()),Z=Y[K]&&Y[K][X]),typeof Z>"u"||!Z.length||!Z[0]){var Yt="";pt=[];for(it in Y[K])this.terminals_[it]&&it>$&&pt.push("'"+this.terminals_[it]+"'");F.showPosition?Yt="Parse error on line "+(q+1)+`: +import{g as Te,s as be,n as we,m as _e,a as De,b as Se,_ as l,c as dt,d as Ce,ar as U,l as ot,j as Me,H as Ee,o as Ie,v as Ye}from"./mermaid.core-BRmiRRt4.js";import{g as It}from"./vendor-utils-_6D5wMFs.js";import{s as vt}from"./vendor-flow-bDma3vSM.js";import{Z as $e,_ as Ae,$ as Fe,m as Le,a0 as Oe,a1 as Zt,a2 as Qt,a3 as We,a4 as Pe,a5 as Ve,a6 as Re,a7 as ze,a8 as Ne,a9 as He,aa as Kt,ab as Jt,ac as te,ad as ee,ae as re}from"./vendor-charts-CwfdE1jD.js";import"./index-DYMv5Ibu.js";function Be(t){return t}var Tt=1,$t=2,Ft=3,xt=4,se=1e-6;function qe(t){return"translate("+t+",0)"}function Ge(t){return"translate(0,"+t+")"}function Xe(t){return e=>+t(e)}function je(t,e){return e=Math.max(0,t.bandwidth()-e*2)/2,t.round()&&(e=Math.round(e)),s=>+t(s)+e}function Ue(){return!this.__axis}function de(t,e){var s=[],r=null,n=null,g=6,y=6,b=3,C=typeof window<"u"&&window.devicePixelRatio>1?0:.5,L=t===Tt||t===xt?-1:1,w=t===xt||t===$t?"x":"y",P=t===Tt||t===Ft?qe:Ge;function _(D){var G=r??(e.ticks?e.ticks.apply(e,s):e.domain()),N=n??(e.tickFormat?e.tickFormat.apply(e,s):Be),k=Math.max(g,0)+b,M=e.range(),W=+M[0]+C,O=+M[M.length-1]+C,H=(e.bandwidth?je:Xe)(e.copy(),C),z=D.selection?D.selection():D,I=z.selectAll(".domain").data([null]),x=z.selectAll(".tick").data(G,e).order(),h=x.exit(),E=x.enter().append("g").attr("class","tick"),f=x.select("line"),T=x.select("text");I=I.merge(I.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),x=x.merge(E),f=f.merge(E.append("line").attr("stroke","currentColor").attr(w+"2",L*g)),T=T.merge(E.append("text").attr("fill","currentColor").attr(w,L*k).attr("dy",t===Tt?"0em":t===Ft?"0.71em":"0.32em")),D!==z&&(I=I.transition(D),x=x.transition(D),f=f.transition(D),T=T.transition(D),h=h.transition(D).attr("opacity",se).attr("transform",function(v){return isFinite(v=H(v))?P(v+C):this.getAttribute("transform")}),E.attr("opacity",se).attr("transform",function(v){var p=this.parentNode.__axis;return P((p&&isFinite(p=p(v))?p:H(v))+C)})),h.remove(),I.attr("d",t===xt||t===$t?y?"M"+L*y+","+W+"H"+C+"V"+O+"H"+L*y:"M"+C+","+W+"V"+O:y?"M"+W+","+L*y+"V"+C+"H"+O+"V"+L*y:"M"+W+","+C+"H"+O),x.attr("opacity",1).attr("transform",function(v){return P(H(v)+C)}),f.attr(w+"2",L*g),T.attr(w,L*k).text(N),z.filter(Ue).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===$t?"start":t===xt?"end":"middle"),z.each(function(){this.__axis=H})}return _.scale=function(D){return arguments.length?(e=D,_):e},_.ticks=function(){return s=Array.from(arguments),_},_.tickArguments=function(D){return arguments.length?(s=D==null?[]:Array.from(D),_):s.slice()},_.tickValues=function(D){return arguments.length?(r=D==null?null:Array.from(D),_):r&&r.slice()},_.tickFormat=function(D){return arguments.length?(n=D,_):n},_.tickSize=function(D){return arguments.length?(g=y=+D,_):g},_.tickSizeInner=function(D){return arguments.length?(g=+D,_):g},_.tickSizeOuter=function(D){return arguments.length?(y=+D,_):y},_.tickPadding=function(D){return arguments.length?(b=+D,_):b},_.offset=function(D){return arguments.length?(C=+D,_):C},_}function Ze(t){return de(Tt,t)}function Qe(t){return de(Ft,t)}var bt={exports:{}},Ke=bt.exports,ie;function Je(){return ie||(ie=1,(function(t,e){(function(s,r){t.exports=r()})(Ke,(function(){var s="day";return function(r,n,g){var y=function(L){return L.add(4-L.isoWeekday(),s)},b=n.prototype;b.isoWeekYear=function(){return y(this).year()},b.isoWeek=function(L){if(!this.$utils().u(L))return this.add(7*(L-this.isoWeek()),s);var w,P,_,D,G=y(this),N=(w=this.isoWeekYear(),P=this.$u,_=(P?g.utc:g)().year(w).startOf("year"),D=4-_.isoWeekday(),_.isoWeekday()>4&&(D+=7),_.add(D,s));return G.diff(N,"week")+1},b.isoWeekday=function(L){return this.$utils().u(L)?this.day()||7:this.day(this.day()%7?L:L-7)};var C=b.startOf;b.startOf=function(L,w){var P=this.$utils(),_=!!P.u(w)||w;return P.p(L)==="isoweek"?_?this.date(this.date()-(this.isoWeekday()-1)).startOf("day"):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf("day"):C.bind(this)(L,w)}}}))})(bt)),bt.exports}var tr=Je();const er=It(tr);var wt={exports:{}},rr=wt.exports,ne;function sr(){return ne||(ne=1,(function(t,e){(function(s,r){t.exports=r()})(rr,(function(){var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},r=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,n=/\d/,g=/\d\d/,y=/\d\d?/,b=/\d*[^-_:/,()\s\d]+/,C={},L=function(k){return(k=+k)+(k>68?1900:2e3)},w=function(k){return function(M){this[k]=+M}},P=[/[+-]\d\d:?(\d\d)?|Z/,function(k){(this.zone||(this.zone={})).offset=(function(M){if(!M||M==="Z")return 0;var W=M.match(/([+-]|\d\d)/g),O=60*W[1]+(+W[2]||0);return O===0?0:W[0]==="+"?-O:O})(k)}],_=function(k){var M=C[k];return M&&(M.indexOf?M:M.s.concat(M.f))},D=function(k,M){var W,O=C.meridiem;if(O){for(var H=1;H<=24;H+=1)if(k.indexOf(O(H,0,M))>-1){W=H>12;break}}else W=k===(M?"pm":"PM");return W},G={A:[b,function(k){this.afternoon=D(k,!1)}],a:[b,function(k){this.afternoon=D(k,!0)}],Q:[n,function(k){this.month=3*(k-1)+1}],S:[n,function(k){this.milliseconds=100*+k}],SS:[g,function(k){this.milliseconds=10*+k}],SSS:[/\d{3}/,function(k){this.milliseconds=+k}],s:[y,w("seconds")],ss:[y,w("seconds")],m:[y,w("minutes")],mm:[y,w("minutes")],H:[y,w("hours")],h:[y,w("hours")],HH:[y,w("hours")],hh:[y,w("hours")],D:[y,w("day")],DD:[g,w("day")],Do:[b,function(k){var M=C.ordinal,W=k.match(/\d+/);if(this.day=W[0],M)for(var O=1;O<=31;O+=1)M(O).replace(/\[|\]/g,"")===k&&(this.day=O)}],w:[y,w("week")],ww:[g,w("week")],M:[y,w("month")],MM:[g,w("month")],MMM:[b,function(k){var M=_("months"),W=(_("monthsShort")||M.map((function(O){return O.slice(0,3)}))).indexOf(k)+1;if(W<1)throw new Error;this.month=W%12||W}],MMMM:[b,function(k){var M=_("months").indexOf(k)+1;if(M<1)throw new Error;this.month=M%12||M}],Y:[/[+-]?\d+/,w("year")],YY:[g,function(k){this.year=L(k)}],YYYY:[/\d{4}/,w("year")],Z:P,ZZ:P};function N(k){var M,W;M=k,W=C&&C.formats;for(var O=(k=M.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(f,T,v){var p=v&&v.toUpperCase();return T||W[v]||s[v]||W[p].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(a,d,m){return d||m.slice(1)}))}))).match(r),H=O.length,z=0;z-1)return new Date((S==="X"?1e3:1)*u);var o=N(S)(u),q=o.year,c=o.month,$=o.day,A=o.hours,R=o.minutes,F=o.seconds,B=o.milliseconds,V=o.zone,st=o.week,nt=new Date,yt=$||(q||c?1:nt.getDate()),lt=q||nt.getFullYear(),X=0;q&&!c||(X=c>0?c-1:nt.getMonth());var K,Z=A||0,at=R||0,J=F||0,it=B||0;return V?new Date(Date.UTC(lt,X,yt,Z,at,J,it+60*V.offset*1e3)):i?new Date(Date.UTC(lt,X,yt,Z,at,J,it)):(K=new Date(lt,X,yt,Z,at,J,it),st&&(K=Y(K).week(st).toDate()),K)}catch{return new Date("")}})(I,E,x,W),this.init(),p&&p!==!0&&(this.$L=this.locale(p).$L),v&&I!=this.format(E)&&(this.$d=new Date("")),C={}}else if(E instanceof Array)for(var a=E.length,d=1;d<=a;d+=1){h[1]=E[d-1];var m=W.apply(this,h);if(m.isValid()){this.$d=m.$d,this.$L=m.$L,this.init();break}d===a&&(this.$d=new Date(""))}else H.call(this,z)}}}))})(wt)),wt.exports}var ir=sr();const nr=It(ir);var _t={exports:{}},ar=_t.exports,ae;function or(){return ae||(ae=1,(function(t,e){(function(s,r){t.exports=r()})(ar,(function(){return function(s,r){var n=r.prototype,g=n.format;n.format=function(y){var b=this,C=this.$locale();if(!this.isValid())return g.bind(this)(y);var L=this.$utils(),w=(y||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(P){switch(P){case"Q":return Math.ceil((b.$M+1)/3);case"Do":return C.ordinal(b.$D);case"gggg":return b.weekYear();case"GGGG":return b.isoWeekYear();case"wo":return C.ordinal(b.week(),"W");case"w":case"ww":return L.s(b.week(),P==="w"?1:2,"0");case"W":case"WW":return L.s(b.isoWeek(),P==="W"?1:2,"0");case"k":case"kk":return L.s(String(b.$H===0?24:b.$H),P==="k"?1:2,"0");case"X":return Math.floor(b.$d.getTime()/1e3);case"x":return b.$d.getTime();case"z":return"["+b.offsetName()+"]";case"zzz":return"["+b.offsetName("long")+"]";default:return P}}));return g.bind(this)(w)}}}))})(_t)),_t.exports}var cr=or();const lr=It(cr);var Dt={exports:{}},ur=Dt.exports,oe;function dr(){return oe||(oe=1,(function(t,e){(function(s,r){t.exports=r()})(ur,(function(){var s,r,n=1e3,g=6e4,y=36e5,b=864e5,C=31536e6,L=2628e6,w=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,P=/\[([^\]]+)]|YYYY|YY|Y|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS/g,_={years:C,months:L,days:b,hours:y,minutes:g,seconds:n,milliseconds:1,weeks:6048e5},D=function(I){return I instanceof H},G=function(I,x,h){return new H(I,h,x.$l)},N=function(I){return r.p(I)+"s"},k=function(I){return I<0},M=function(I){return k(I)?Math.ceil(I):Math.floor(I)},W=function(I){return Math.abs(I)},O=function(I,x){return I?k(I)?{negative:!0,format:""+W(I)+x}:{negative:!1,format:""+I+x}:{negative:!1,format:""}},H=(function(){function I(h,E,f){var T=this;if(this.$d={},this.$l=f,h===void 0&&(this.$ms=0,this.parseFromMilliseconds()),E)return G(h*_[N(E)],this);if(typeof h=="number")return this.$ms=h,this.parseFromMilliseconds(),this;if(typeof h=="object")return Object.keys(h).forEach((function(a){T.$d[N(a)]=h[a]})),this.calMilliseconds(),this;if(typeof h=="string"){var v=h.match(w);if(v){var p=v.slice(2).map((function(a){return a!=null?Number(a):0}));return this.$d.years=p[0],this.$d.months=p[1],this.$d.weeks=p[2],this.$d.days=p[3],this.$d.hours=p[4],this.$d.minutes=p[5],this.$d.seconds=p[6],this.calMilliseconds(),this}}return this}var x=I.prototype;return x.calMilliseconds=function(){var h=this;this.$ms=Object.keys(this.$d).reduce((function(E,f){return E+(h.$d[f]||0)*_[f]}),0)},x.parseFromMilliseconds=function(){var h=this.$ms;this.$d.years=M(h/C),h%=C,this.$d.months=M(h/L),h%=L,this.$d.days=M(h/b),h%=b,this.$d.hours=M(h/y),h%=y,this.$d.minutes=M(h/g),h%=g,this.$d.seconds=M(h/n),h%=n,this.$d.milliseconds=h},x.toISOString=function(){var h=O(this.$d.years,"Y"),E=O(this.$d.months,"M"),f=+this.$d.days||0;this.$d.weeks&&(f+=7*this.$d.weeks);var T=O(f,"D"),v=O(this.$d.hours,"H"),p=O(this.$d.minutes,"M"),a=this.$d.seconds||0;this.$d.milliseconds&&(a+=this.$d.milliseconds/1e3,a=Math.round(1e3*a)/1e3);var d=O(a,"S"),m=h.negative||E.negative||T.negative||v.negative||p.negative||d.negative,u=v.format||p.format||d.format?"T":"",S=(m?"-":"")+"P"+h.format+E.format+T.format+u+v.format+p.format+d.format;return S==="P"||S==="-P"?"P0D":S},x.toJSON=function(){return this.toISOString()},x.format=function(h){var E=h||"YYYY-MM-DDTHH:mm:ss",f={Y:this.$d.years,YY:r.s(this.$d.years,2,"0"),YYYY:r.s(this.$d.years,4,"0"),M:this.$d.months,MM:r.s(this.$d.months,2,"0"),D:this.$d.days,DD:r.s(this.$d.days,2,"0"),H:this.$d.hours,HH:r.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:r.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:r.s(this.$d.seconds,2,"0"),SSS:r.s(this.$d.milliseconds,3,"0")};return E.replace(P,(function(T,v){return v||String(f[T])}))},x.as=function(h){return this.$ms/_[N(h)]},x.get=function(h){var E=this.$ms,f=N(h);return f==="milliseconds"?E%=1e3:E=f==="weeks"?M(E/_[f]):this.$d[f],E||0},x.add=function(h,E,f){var T;return T=E?h*_[N(E)]:D(h)?h.$ms:G(h,this).$ms,G(this.$ms+T*(f?-1:1),this)},x.subtract=function(h,E){return this.add(h,E,!0)},x.locale=function(h){var E=this.clone();return E.$l=h,E},x.clone=function(){return G(this.$ms,this)},x.humanize=function(h){return s().add(this.$ms,"ms").locale(this.$l).fromNow(!h)},x.valueOf=function(){return this.asMilliseconds()},x.milliseconds=function(){return this.get("milliseconds")},x.asMilliseconds=function(){return this.as("milliseconds")},x.seconds=function(){return this.get("seconds")},x.asSeconds=function(){return this.as("seconds")},x.minutes=function(){return this.get("minutes")},x.asMinutes=function(){return this.as("minutes")},x.hours=function(){return this.get("hours")},x.asHours=function(){return this.as("hours")},x.days=function(){return this.get("days")},x.asDays=function(){return this.as("days")},x.weeks=function(){return this.get("weeks")},x.asWeeks=function(){return this.as("weeks")},x.months=function(){return this.get("months")},x.asMonths=function(){return this.as("months")},x.years=function(){return this.get("years")},x.asYears=function(){return this.as("years")},I})(),z=function(I,x,h){return I.add(x.years()*h,"y").add(x.months()*h,"M").add(x.days()*h,"d").add(x.hours()*h,"h").add(x.minutes()*h,"m").add(x.seconds()*h,"s").add(x.milliseconds()*h,"ms")};return function(I,x,h){s=h,r=h().$utils(),h.duration=function(T,v){var p=h.locale();return G(T,{$l:p},v)},h.isDuration=D;var E=x.prototype.add,f=x.prototype.subtract;x.prototype.add=function(T,v){return D(T)?z(this,T,1):E.bind(this)(T,v)},x.prototype.subtract=function(T,v){return D(T)?z(this,T,-1):f.bind(this)(T,v)}}}))})(Dt)),Dt.exports}var fr=dr();const hr=It(fr);var Lt=(function(){var t=l(function(p,a,d,m){for(d=d||{},m=p.length;m--;d[p[m]]=a);return d},"o"),e=[6,8,10,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,33,35,36,38,40],s=[1,26],r=[1,27],n=[1,28],g=[1,29],y=[1,30],b=[1,31],C=[1,32],L=[1,33],w=[1,34],P=[1,9],_=[1,10],D=[1,11],G=[1,12],N=[1,13],k=[1,14],M=[1,15],W=[1,16],O=[1,19],H=[1,20],z=[1,21],I=[1,22],x=[1,23],h=[1,25],E=[1,35],f={trace:l(function(){},"trace"),yy:{},symbols_:{error:2,start:3,gantt:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NL:10,weekday:11,weekday_monday:12,weekday_tuesday:13,weekday_wednesday:14,weekday_thursday:15,weekday_friday:16,weekday_saturday:17,weekday_sunday:18,weekend:19,weekend_friday:20,weekend_saturday:21,dateFormat:22,inclusiveEndDates:23,topAxis:24,axisFormat:25,tickInterval:26,excludes:27,includes:28,todayMarker:29,title:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,section:36,clickStatement:37,taskTxt:38,taskData:39,click:40,callbackname:41,callbackargs:42,href:43,clickStatementDebug:44,$accept:0,$end:1},terminals_:{2:"error",4:"gantt",6:"EOF",8:"SPACE",10:"NL",12:"weekday_monday",13:"weekday_tuesday",14:"weekday_wednesday",15:"weekday_thursday",16:"weekday_friday",17:"weekday_saturday",18:"weekday_sunday",20:"weekend_friday",21:"weekend_saturday",22:"dateFormat",23:"inclusiveEndDates",24:"topAxis",25:"axisFormat",26:"tickInterval",27:"excludes",28:"includes",29:"todayMarker",30:"title",31:"acc_title",32:"acc_title_value",33:"acc_descr",34:"acc_descr_value",35:"acc_descr_multiline_value",36:"section",38:"taskTxt",39:"taskData",40:"click",41:"callbackname",42:"callbackargs",43:"href"},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[19,1],[19,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,1],[9,2],[37,2],[37,3],[37,3],[37,4],[37,3],[37,4],[37,2],[44,2],[44,3],[44,3],[44,4],[44,3],[44,4],[44,2]],performAction:l(function(a,d,m,u,S,i,Y){var o=i.length-1;switch(S){case 1:return i[o-1];case 2:this.$=[];break;case 3:i[o-1].push(i[o]),this.$=i[o-1];break;case 4:case 5:this.$=i[o];break;case 6:case 7:this.$=[];break;case 8:u.setWeekday("monday");break;case 9:u.setWeekday("tuesday");break;case 10:u.setWeekday("wednesday");break;case 11:u.setWeekday("thursday");break;case 12:u.setWeekday("friday");break;case 13:u.setWeekday("saturday");break;case 14:u.setWeekday("sunday");break;case 15:u.setWeekend("friday");break;case 16:u.setWeekend("saturday");break;case 17:u.setDateFormat(i[o].substr(11)),this.$=i[o].substr(11);break;case 18:u.enableInclusiveEndDates(),this.$=i[o].substr(18);break;case 19:u.TopAxis(),this.$=i[o].substr(8);break;case 20:u.setAxisFormat(i[o].substr(11)),this.$=i[o].substr(11);break;case 21:u.setTickInterval(i[o].substr(13)),this.$=i[o].substr(13);break;case 22:u.setExcludes(i[o].substr(9)),this.$=i[o].substr(9);break;case 23:u.setIncludes(i[o].substr(9)),this.$=i[o].substr(9);break;case 24:u.setTodayMarker(i[o].substr(12)),this.$=i[o].substr(12);break;case 27:u.setDiagramTitle(i[o].substr(6)),this.$=i[o].substr(6);break;case 28:this.$=i[o].trim(),u.setAccTitle(this.$);break;case 29:case 30:this.$=i[o].trim(),u.setAccDescription(this.$);break;case 31:u.addSection(i[o].substr(8)),this.$=i[o].substr(8);break;case 33:u.addTask(i[o-1],i[o]),this.$="task";break;case 34:this.$=i[o-1],u.setClickEvent(i[o-1],i[o],null);break;case 35:this.$=i[o-2],u.setClickEvent(i[o-2],i[o-1],i[o]);break;case 36:this.$=i[o-2],u.setClickEvent(i[o-2],i[o-1],null),u.setLink(i[o-2],i[o]);break;case 37:this.$=i[o-3],u.setClickEvent(i[o-3],i[o-2],i[o-1]),u.setLink(i[o-3],i[o]);break;case 38:this.$=i[o-2],u.setClickEvent(i[o-2],i[o],null),u.setLink(i[o-2],i[o-1]);break;case 39:this.$=i[o-3],u.setClickEvent(i[o-3],i[o-1],i[o]),u.setLink(i[o-3],i[o-2]);break;case 40:this.$=i[o-1],u.setLink(i[o-1],i[o]);break;case 41:case 47:this.$=i[o-1]+" "+i[o];break;case 42:case 43:case 45:this.$=i[o-2]+" "+i[o-1]+" "+i[o];break;case 44:case 46:this.$=i[o-3]+" "+i[o-2]+" "+i[o-1]+" "+i[o];break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:17,12:s,13:r,14:n,15:g,16:y,17:b,18:C,19:18,20:L,21:w,22:P,23:_,24:D,25:G,26:N,27:k,28:M,29:W,30:O,31:H,33:z,35:I,36:x,37:24,38:h,40:E},t(e,[2,7],{1:[2,1]}),t(e,[2,3]),{9:36,11:17,12:s,13:r,14:n,15:g,16:y,17:b,18:C,19:18,20:L,21:w,22:P,23:_,24:D,25:G,26:N,27:k,28:M,29:W,30:O,31:H,33:z,35:I,36:x,37:24,38:h,40:E},t(e,[2,5]),t(e,[2,6]),t(e,[2,17]),t(e,[2,18]),t(e,[2,19]),t(e,[2,20]),t(e,[2,21]),t(e,[2,22]),t(e,[2,23]),t(e,[2,24]),t(e,[2,25]),t(e,[2,26]),t(e,[2,27]),{32:[1,37]},{34:[1,38]},t(e,[2,30]),t(e,[2,31]),t(e,[2,32]),{39:[1,39]},t(e,[2,8]),t(e,[2,9]),t(e,[2,10]),t(e,[2,11]),t(e,[2,12]),t(e,[2,13]),t(e,[2,14]),t(e,[2,15]),t(e,[2,16]),{41:[1,40],43:[1,41]},t(e,[2,4]),t(e,[2,28]),t(e,[2,29]),t(e,[2,33]),t(e,[2,34],{42:[1,42],43:[1,43]}),t(e,[2,40],{41:[1,44]}),t(e,[2,35],{43:[1,45]}),t(e,[2,36]),t(e,[2,38],{42:[1,46]}),t(e,[2,37]),t(e,[2,39])],defaultActions:{},parseError:l(function(a,d){if(d.recoverable)this.trace(a);else{var m=new Error(a);throw m.hash=d,m}},"parseError"),parse:l(function(a){var d=this,m=[0],u=[],S=[null],i=[],Y=this.table,o="",q=0,c=0,$=2,A=1,R=i.slice.call(arguments,1),F=Object.create(this.lexer),B={yy:{}};for(var V in this.yy)Object.prototype.hasOwnProperty.call(this.yy,V)&&(B.yy[V]=this.yy[V]);F.setInput(a,B.yy),B.yy.lexer=F,B.yy.parser=this,typeof F.yylloc>"u"&&(F.yylloc={});var st=F.yylloc;i.push(st);var nt=F.options&&F.options.ranges;typeof B.yy.parseError=="function"?this.parseError=B.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function yt(Q){m.length=m.length-2*Q,S.length=S.length-Q,i.length=i.length-Q}l(yt,"popStack");function lt(){var Q;return Q=u.pop()||F.lex()||A,typeof Q!="number"&&(Q instanceof Array&&(u=Q,Q=u.pop()),Q=d.symbols_[Q]||Q),Q}l(lt,"lex");for(var X,K,Z,at,J={},it,tt,Ut,pt;;){if(K=m[m.length-1],this.defaultActions[K]?Z=this.defaultActions[K]:((X===null||typeof X>"u")&&(X=lt()),Z=Y[K]&&Y[K][X]),typeof Z>"u"||!Z.length||!Z[0]){var Yt="";pt=[];for(it in Y[K])this.terminals_[it]&&it>$&&pt.push("'"+this.terminals_[it]+"'");F.showPosition?Yt="Parse error on line "+(q+1)+`: `+F.showPosition()+` Expecting `+pt.join(", ")+", got '"+(this.terminals_[X]||X)+"'":Yt="Parse error on line "+(q+1)+": Unexpected "+(X==A?"end of input":"'"+(this.terminals_[X]||X)+"'"),this.parseError(Yt,{text:F.match,token:this.terminals_[X]||X,line:F.yylineno,loc:st,expected:pt})}if(Z[0]instanceof Array&&Z.length>1)throw new Error("Parse Error: multiple actions possible at state: "+K+", token: "+X);switch(Z[0]){case 1:m.push(X),S.push(F.yytext),i.push(F.yylloc),m.push(Z[1]),X=null,c=F.yyleng,o=F.yytext,q=F.yylineno,st=F.yylloc;break;case 2:if(tt=this.productions_[Z[1]][1],J.$=S[S.length-tt],J._$={first_line:i[i.length-(tt||1)].first_line,last_line:i[i.length-1].last_line,first_column:i[i.length-(tt||1)].first_column,last_column:i[i.length-1].last_column},nt&&(J._$.range=[i[i.length-(tt||1)].range[0],i[i.length-1].range[1]]),at=this.performAction.apply(J,[o,c,q,B.yy,Z[1],S,i].concat(R)),typeof at<"u")return at;tt&&(m=m.slice(0,-1*tt*2),S=S.slice(0,-1*tt),i=i.slice(0,-1*tt)),m.push(this.productions_[Z[1]][0]),S.push(J.$),i.push(J._$),Ut=Y[m[m.length-2]][m[m.length-1]],m.push(Ut);break;case 3:return!0}}return!0},"parse")},T=(function(){var p={EOF:1,parseError:l(function(d,m){if(this.yy.parser)this.yy.parser.parseError(d,m);else throw new Error(d)},"parseError"),setInput:l(function(a,d){return this.yy=d||this.yy||{},this._input=a,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:l(function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var d=a.match(/(?:\r\n?|\n).*/g);return d?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},"input"),unput:l(function(a){var d=a.length,m=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-d),this.offset-=d;var u=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),m.length-1&&(this.yylineno-=m.length-1);var S=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:m?(m.length===u.length?this.yylloc.first_column:0)+u[u.length-m.length].length-m[0].length:this.yylloc.first_column-d},this.options.ranges&&(this.yylloc.range=[S[0],S[0]+this.yyleng-d]),this.yyleng=this.yytext.length,this},"unput"),more:l(function(){return this._more=!0,this},"more"),reject:l(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). `+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:l(function(a){this.unput(this.match.slice(a))},"less"),pastInput:l(function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:l(function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:l(function(){var a=this.pastInput(),d=new Array(a.length+1).join("-");return a+this.upcomingInput()+` diff --git a/static/ml_canvas/assets/gitGraphDiagram-WWUBYQGX-CtsDT5Wk.js b/static/ml_canvas/assets/gitGraphDiagram-WWUBYQGX-CmGc_tMG.js similarity index 99% rename from static/ml_canvas/assets/gitGraphDiagram-WWUBYQGX-CtsDT5Wk.js rename to static/ml_canvas/assets/gitGraphDiagram-WWUBYQGX-CmGc_tMG.js index 51d35d01d..32b059353 100644 --- a/static/ml_canvas/assets/gitGraphDiagram-WWUBYQGX-CtsDT5Wk.js +++ b/static/ml_canvas/assets/gitGraphDiagram-WWUBYQGX-CmGc_tMG.js @@ -1,4 +1,4 @@ -import{I as he}from"./chunk-2Q5K7J3B-DEOZDP-3.js";import{p as $e}from"./chunk-JWPE2WC7-_bXip4eZ.js";import{n as fe,m as ge,s as ue,g as ye,a as xe,b as me,_ as $,x as Q,l as k,c as z,v as pe,y as be,o as we,j as L,z as ke,A as ve,B as Ee}from"./mermaid.core-BCO0YdKy.js";import{p as Be}from"./cynefin-OW5HDTMX-WQ4gGbOM.js";import{s as Ce}from"./vendor-flow-bDma3vSM.js";import"./index-BXksgzya.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var p={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4},Te=ve.gitGraph,D=$(()=>ke({...Te,...Q().gitGraph}),"getConfig"),i=new he(()=>{const e=D(),r=e.mainBranchName,t=e.mainBranchOrder;return{mainBranchName:r,commits:new Map,head:null,branchConfig:new Map([[r,{name:r,order:t}]]),branches:new Map([[r,null]]),currBranch:r,direction:"LR",seq:0,options:{}}});function K(){return Ee({length:7})}$(K,"getID");function ae(e,r){const t=Object.create(null);return e.reduce((o,s)=>{const d=r(s);return t[d]||(t[d]=!0,o.push(s)),o},[])}$(ae,"uniqBy");var Le=$(function(e){i.records.direction=e},"setDirection"),Me=$(function(e){k.debug("options str",e),e=e==null?void 0:e.trim(),e=e||"{}";try{i.records.options=JSON.parse(e)}catch(r){k.error("error while parsing gitGraph options",r.message)}},"setOptions"),Re=$(function(){return i.records.options},"getOptions"),Ie=$(function(e){let r=e.msg,t=e.id;const o=e.type;let s=e.tags;k.info("commit",r,t,o,s),k.debug("Entering commit:",r,t,o,s);const d=D();t=L.sanitizeText(t,d),r=L.sanitizeText(r,d),s=s==null?void 0:s.map(a=>L.sanitizeText(a,d));const n={id:t||i.records.seq+"-"+K(),message:r,seq:i.records.seq++,type:o??p.NORMAL,tags:s??[],parents:i.records.head==null?[]:[i.records.head.id],branch:i.records.currBranch};i.records.head=n,k.info("main branch",d.mainBranchName),i.records.commits.has(n.id)&&k.warn(`Commit ID ${n.id} already exists`),i.records.commits.set(n.id,n),i.records.branches.set(i.records.currBranch,n.id),k.debug("in pushCommit "+n.id)},"commit"),Oe=$(function(e){let r=e.name;const t=e.order;if(r=L.sanitizeText(r,D()),i.records.branches.has(r))throw new Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${r}")`);i.records.branches.set(r,i.records.head!=null?i.records.head.id:null),i.records.branchConfig.set(r,{name:r,order:t}),ne(r),k.debug("in createBranch")},"branch"),_e=$(e=>{let r=e.branch,t=e.id;const o=e.type,s=e.tags,d=D();r=L.sanitizeText(r,d),t&&(t=L.sanitizeText(t,d));const n=i.records.branches.get(i.records.currBranch),a=i.records.branches.get(r),l=n?i.records.commits.get(n):void 0,h=a?i.records.commits.get(a):void 0;if(l&&h&&l.branch===r)throw new Error(`Cannot merge branch '${r}' into itself.`);if(i.records.currBranch===r){const c=new Error('Incorrect usage of "merge". Cannot merge a branch to itself');throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:["branch abc"]},c}if(l===void 0||!l){const c=new Error(`Incorrect usage of "merge". Current branch (${i.records.currBranch})has no commits`);throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:["commit"]},c}if(!i.records.branches.has(r)){const c=new Error('Incorrect usage of "merge". Branch to be merged ('+r+") does not exist");throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:[`branch ${r}`]},c}if(h===void 0||!h){const c=new Error('Incorrect usage of "merge". Branch to be merged ('+r+") has no commits");throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:['"commit"']},c}if(l===h){const c=new Error('Incorrect usage of "merge". Both branches have same head');throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:["branch abc"]},c}if(t&&i.records.commits.has(t)){const c=new Error('Incorrect usage of "merge". Commit with id:'+t+" already exists, use different custom id");throw c.hash={text:`merge ${r} ${t} ${o} ${s==null?void 0:s.join(" ")}`,token:`merge ${r} ${t} ${o} ${s==null?void 0:s.join(" ")}`,expected:[`merge ${r} ${t}_UNIQUE ${o} ${s==null?void 0:s.join(" ")}`]},c}const g=a||"",f={id:t||`${i.records.seq}-${K()}`,message:`merged branch ${r} into ${i.records.currBranch}`,seq:i.records.seq++,parents:i.records.head==null?[]:[i.records.head.id,g],branch:i.records.currBranch,type:p.MERGE,customType:o,customId:!!t,tags:s??[]};i.records.head=f,i.records.commits.set(f.id,f),i.records.branches.set(i.records.currBranch,f.id),k.debug(i.records.branches),k.debug("in mergeBranch")},"merge"),Ge=$(function(e){let r=e.id,t=e.targetId,o=e.tags,s=e.parent;k.debug("Entering cherryPick:",r,t,o);const d=D();if(r=L.sanitizeText(r,d),t=L.sanitizeText(t,d),o=o==null?void 0:o.map(l=>L.sanitizeText(l,d)),s=L.sanitizeText(s,d),!r||!i.records.commits.has(r)){const l=new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');throw l.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},l}const n=i.records.commits.get(r);if(n===void 0||!n)throw new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');if(s&&!(Array.isArray(n.parents)&&n.parents.includes(s)))throw new Error("Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.");const a=n.branch;if(n.type===p.MERGE&&!s)throw new Error("Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.");if(!t||!i.records.commits.has(t)){if(a===i.records.currBranch){const f=new Error('Incorrect usage of "cherryPick". Source commit is already on current branch');throw f.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},f}const l=i.records.branches.get(i.records.currBranch);if(l===void 0||!l){const f=new Error(`Incorrect usage of "cherry-pick". Current branch (${i.records.currBranch})has no commits`);throw f.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},f}const h=i.records.commits.get(l);if(h===void 0||!h){const f=new Error(`Incorrect usage of "cherry-pick". Current branch (${i.records.currBranch})has no commits`);throw f.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},f}const g={id:i.records.seq+"-"+K(),message:`cherry-picked ${n==null?void 0:n.message} into ${i.records.currBranch}`,seq:i.records.seq++,parents:i.records.head==null?[]:[i.records.head.id,n.id],branch:i.records.currBranch,type:p.CHERRY_PICK,tags:o?o.filter(Boolean):[`cherry-pick:${n.id}${n.type===p.MERGE?`|parent:${s}`:""}`]};i.records.head=g,i.records.commits.set(g.id,g),i.records.branches.set(i.records.currBranch,g.id),k.debug(i.records.branches),k.debug("in cherryPick")}},"cherryPick"),ne=$(function(e){if(e=L.sanitizeText(e,D()),i.records.branches.has(e)){i.records.currBranch=e;const r=i.records.branches.get(i.records.currBranch);r===void 0||!r?i.records.head=null:i.records.head=i.records.commits.get(r)??null}else{const r=new Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${e}")`);throw r.hash={text:`checkout ${e}`,token:`checkout ${e}`,expected:[`branch ${e}`]},r}},"checkout");function X(e,r,t){const o=e.indexOf(r);o===-1?e.push(t):e.splice(o,1,t)}$(X,"upsert");function Z(e){const r=e.reduce((s,d)=>s.seq>d.seq?s:d,e[0]);let t="";e.forEach(function(s){s===r?t+=" *":t+=" |"});const o=[t,r.id,r.seq];for(const s in i.records.branches)i.records.branches.get(s)===r.id&&o.push(s);if(k.debug(o.join(" ")),r.parents&&r.parents.length==2&&r.parents[0]&&r.parents[1]){const s=i.records.commits.get(r.parents[0]);X(e,r,s),r.parents[1]&&e.push(i.records.commits.get(r.parents[1]))}else{if(r.parents.length==0)return;if(r.parents[0]){const s=i.records.commits.get(r.parents[0]);X(e,r,s)}}e=ae(e,s=>s.id),Z(e)}$(Z,"prettyPrintCommitHistory");var He=$(function(){k.debug(i.records.commits);const e=se()[0];Z([e])},"prettyPrint"),Ae=$(function(){i.reset(),we()},"clear"),Se=$(function(){return[...i.records.branchConfig.values()].map((r,t)=>r.order!==null&&r.order!==void 0?r:{...r,order:parseFloat(`0.${t}`)}).sort((r,t)=>(r.order??0)-(t.order??0)).map(({name:r})=>({name:r}))},"getBranchesAsObjArray"),De=$(function(){return i.records.branches},"getBranches"),Pe=$(function(){return i.records.commits},"getCommits"),se=$(function(){const e=[...i.records.commits.values()];return e.forEach(function(r){k.debug(r.id)}),e.sort((r,t)=>r.seq-t.seq),e},"getCommitsArray"),We=$(function(){return i.records.currBranch},"getCurrentBranch"),qe=$(function(){return i.records.direction},"getDirection"),Ne=$(function(){return i.records.head},"getHead"),oe={commitType:p,getConfig:D,setDirection:Le,setOptions:Me,getOptions:Re,commit:Ie,branch:Oe,merge:_e,cherryPick:Ge,checkout:ne,prettyPrint:He,clear:Ae,getBranchesAsObjArray:Se,getBranches:De,getCommits:Pe,getCommitsArray:se,getCurrentBranch:We,getDirection:qe,getHead:Ne,setAccTitle:me,getAccTitle:xe,getAccDescription:ye,setAccDescription:ue,setDiagramTitle:ge,getDiagramTitle:fe},Fe=$((e,r)=>{$e(e,r),e.dir&&r.setDirection(e.dir);for(const t of e.statements)ze(t,r)},"populate"),ze=$((e,r)=>{const o={Commit:$(s=>r.commit(Ye(s)),"Commit"),Branch:$(s=>r.branch(je(s)),"Branch"),Merge:$(s=>r.merge(Ue(s)),"Merge"),Checkout:$(s=>r.checkout(Ke(s)),"Checkout"),CherryPicking:$(s=>r.cherryPick(Ve(s)),"CherryPicking")}[e.$type];o?o(e):k.error(`Unknown statement type: ${e.$type}`)},"parseStatement"),Ye=$(e=>({id:e.id,msg:e.message??"",type:e.type!==void 0?p[e.type]:p.NORMAL,tags:e.tags??void 0}),"parseCommit"),je=$(e=>({name:e.name,order:e.order??0}),"parseBranch"),Ue=$(e=>({branch:e.branch,id:e.id??"",type:e.type!==void 0?p[e.type]:void 0,tags:e.tags??void 0}),"parseMerge"),Ke=$(e=>e.branch,"parseCheckout"),Ve=$(e=>{var t;return{id:e.id,targetId:"",tags:((t=e.tags)==null?void 0:t.length)===0?void 0:e.tags,parent:e.parent}},"parseCherryPicking"),Xe={parse:$(async e=>{const r=await Be("gitGraph",e);k.debug(r),Fe(r,oe)},"parse")},G=10,H=40,M=4,I=2,A=8,V=new Set(["redux","redux-dark","redux-color","redux-dark-color"]),J=12,ee=new Set(["redux-color","redux-dark-color"]),Je=new Set(["dark","redux-dark","redux-dark-color","neo-dark"]),S=$((e,r,t=!1)=>t&&e>0?(e-1)%(r-1)+1:e%r,"calcColorIndex"),C=new Map,T=new Map,j=30,N=new Map,U=[],O=0,y="LR",Qe=$(()=>{C.clear(),T.clear(),N.clear(),O=0,U=[],y="LR"},"clear"),ce=$(e=>{const r=document.createElementNS("http://www.w3.org/2000/svg","text");return(typeof e=="string"?e.split(/\\n|\n|/gi):e).forEach(o=>{const s=document.createElementNS("http://www.w3.org/2000/svg","tspan");s.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),s.setAttribute("dy","1em"),s.setAttribute("x","0"),s.setAttribute("class","row"),s.textContent=o.trim(),r.appendChild(s)}),r},"drawText"),ie=$(e=>{let r,t,o;return y==="BT"?(t=$((s,d)=>s<=d,"comparisonFunc"),o=1/0):(t=$((s,d)=>s>=d,"comparisonFunc"),o=0),e.forEach(s=>{var n,a;const d=y==="TB"||y=="BT"?(n=T.get(s))==null?void 0:n.y:(a=T.get(s))==null?void 0:a.x;d!==void 0&&t(d,o)&&(r=s,o=d)}),r},"findClosestParent"),Ze=$(e=>{let r="",t=1/0;return e.forEach(o=>{const s=T.get(o).y;s<=t&&(r=o,t=s)}),r||void 0},"findClosestParentBT"),er=$((e,r,t)=>{let o=t,s=t;const d=[];e.forEach(n=>{const a=r.get(n);if(!a)throw new Error(`Commit not found for key ${n}`);a.parents.length?(o=tr(a),s=Math.max(o,s)):d.push(a),ar(a,o)}),o=s,d.forEach(n=>{nr(n,o,t)}),e.forEach(n=>{const a=r.get(n);if(a!=null&&a.parents.length){const l=Ze(a.parents);o=T.get(l).y-H,o<=s&&(s=o);const h=C.get(a.branch).pos,g=o-G;T.set(a.id,{x:h,y:g})}})},"setParallelBTPos"),rr=$(e=>{var o;const r=ie(e.parents.filter(s=>s!==null));if(!r)throw new Error(`Closest parent not found for commit ${e.id}`);const t=(o=T.get(r))==null?void 0:o.y;if(t===void 0)throw new Error(`Closest parent position not found for commit ${e.id}`);return t},"findClosestParentPos"),tr=$(e=>rr(e)+H,"calculateCommitPosition"),ar=$((e,r)=>{const t=C.get(e.branch);if(!t)throw new Error(`Branch not found for commit ${e.id}`);const o=t.pos,s=r+G;return T.set(e.id,{x:o,y:s}),{x:o,y:s}},"setCommitPosition"),nr=$((e,r,t)=>{const o=C.get(e.branch);if(!o)throw new Error(`Branch not found for commit ${e.id}`);const s=r+t,d=o.pos;T.set(e.id,{x:d,y:s})},"setRootPosition"),sr=$((e,r,t,o,s,d)=>{const{theme:n}=z(),a=V.has(n??""),l=ee.has(n??""),h=Je.has(n??"");if(d===p.HIGHLIGHT)e.append("rect").attr("x",t.x-10+(a?3:0)).attr("y",t.y-10+(a?3:0)).attr("width",a?14:20).attr("height",a?14:20).attr("class",`commit ${r.id} commit-highlight${S(s,A,l)} ${o}-outer`),e.append("rect").attr("x",t.x-6+(a?2:0)).attr("y",t.y-6+(a?2:0)).attr("width",a?8:12).attr("height",a?8:12).attr("class",`commit ${r.id} commit${S(s,A,l)} ${o}-inner`);else if(d===p.CHERRY_PICK)e.append("circle").attr("cx",t.x).attr("cy",t.y).attr("r",a?7:10).attr("class",`commit ${r.id} ${o}`),e.append("circle").attr("cx",t.x-3).attr("cy",t.y+2).attr("r",a?2.5:2.75).attr("fill",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`),e.append("circle").attr("cx",t.x+3).attr("cy",t.y+2).attr("r",a?2.5:2.75).attr("fill",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`),e.append("line").attr("x1",t.x+3).attr("y1",t.y+1).attr("x2",t.x).attr("y2",t.y-5).attr("stroke",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`),e.append("line").attr("x1",t.x-3).attr("y1",t.y+1).attr("x2",t.x).attr("y2",t.y-5).attr("stroke",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`);else{const g=e.append("circle");if(g.attr("cx",t.x),g.attr("cy",t.y),g.attr("r",a?7:10),g.attr("class",`commit ${r.id} commit${S(s,A,l)}`),d===p.MERGE){const f=e.append("circle");f.attr("cx",t.x),f.attr("cy",t.y),f.attr("r",a?5:6),f.attr("class",`commit ${o} ${r.id} commit${S(s,A,l)}`)}if(d===p.REVERSE){const f=e.append("path"),c=a?4:5;f.attr("d",`M ${t.x-c},${t.y-c}L${t.x+c},${t.y+c}M${t.x-c},${t.y+c}L${t.x+c},${t.y-c}`).attr("class",`commit ${o} ${r.id} commit${S(s,A,l)}`)}}},"drawCommitBullet"),or=$((e,r,t,o,s)=>{var d;if(r.type!==p.CHERRY_PICK&&(r.customId&&r.type===p.MERGE||r.type!==p.MERGE)&&s.showCommitLabel){const n=e.append("g"),a=n.insert("rect").attr("class","commit-label-bkg"),l=n.append("text").attr("x",o).attr("y",t.y+25).attr("class","commit-label").text(r.id),h=(d=l.node())==null?void 0:d.getBBox();if(h&&(a.attr("x",t.posWithOffset-h.width/2-I).attr("y",t.y+13.5).attr("width",h.width+2*I).attr("height",h.height+2*I),y==="TB"||y==="BT"?(a.attr("x",t.x-(h.width+4*M+5)).attr("y",t.y-12),l.attr("x",t.x-(h.width+4*M)).attr("y",t.y+h.height-12)):l.attr("x",t.posWithOffset-h.width/2),s.rotateCommitLabel))if(y==="TB"||y==="BT")l.attr("transform","rotate(-45, "+t.x+", "+t.y+")"),a.attr("transform","rotate(-45, "+t.x+", "+t.y+")");else{const g=-7.5-(h.width+10)/25*9.5,f=10+h.width/25*8.5;n.attr("transform","translate("+g+", "+f+") rotate(-45, "+o+", "+t.y+")")}}},"drawCommitLabel"),cr=$((e,r,t,o)=>{var s;if(r.tags.length>0){let d=0,n=0,a=0;const l=[];for(const h of r.tags.reverse()){const g=e.insert("polygon"),f=e.append("circle"),c=e.append("text").attr("y",t.y-16-d).attr("class","tag-label").text(h),x=(s=c.node())==null?void 0:s.getBBox();if(!x)throw new Error("Tag bbox not found");n=Math.max(n,x.width),a=Math.max(a,x.height),c.attr("x",t.posWithOffset-x.width/2),l.push({tag:c,hole:f,rect:g,yOffset:d}),d+=20}for(const{tag:h,hole:g,rect:f,yOffset:c}of l){const x=a/2,u=t.y-19.2-c;if(f.attr("class","tag-label-bkg").attr("points",` +import{I as he}from"./chunk-2Q5K7J3B-BAAo9EN0.js";import{p as $e}from"./chunk-JWPE2WC7-BQCQvAYF.js";import{n as fe,m as ge,s as ue,g as ye,a as xe,b as me,_ as $,x as Q,l as k,c as z,v as pe,y as be,o as we,j as L,z as ke,A as ve,B as Ee}from"./mermaid.core-BRmiRRt4.js";import{p as Be}from"./cynefin-OW5HDTMX-DHAz5VCH.js";import{s as Ce}from"./vendor-flow-bDma3vSM.js";import"./index-DYMv5Ibu.js";import"./vendor-utils-_6D5wMFs.js";import"./vendor-charts-CwfdE1jD.js";var p={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4},Te=ve.gitGraph,D=$(()=>ke({...Te,...Q().gitGraph}),"getConfig"),i=new he(()=>{const e=D(),r=e.mainBranchName,t=e.mainBranchOrder;return{mainBranchName:r,commits:new Map,head:null,branchConfig:new Map([[r,{name:r,order:t}]]),branches:new Map([[r,null]]),currBranch:r,direction:"LR",seq:0,options:{}}});function K(){return Ee({length:7})}$(K,"getID");function ae(e,r){const t=Object.create(null);return e.reduce((o,s)=>{const d=r(s);return t[d]||(t[d]=!0,o.push(s)),o},[])}$(ae,"uniqBy");var Le=$(function(e){i.records.direction=e},"setDirection"),Me=$(function(e){k.debug("options str",e),e=e==null?void 0:e.trim(),e=e||"{}";try{i.records.options=JSON.parse(e)}catch(r){k.error("error while parsing gitGraph options",r.message)}},"setOptions"),Re=$(function(){return i.records.options},"getOptions"),Ie=$(function(e){let r=e.msg,t=e.id;const o=e.type;let s=e.tags;k.info("commit",r,t,o,s),k.debug("Entering commit:",r,t,o,s);const d=D();t=L.sanitizeText(t,d),r=L.sanitizeText(r,d),s=s==null?void 0:s.map(a=>L.sanitizeText(a,d));const n={id:t||i.records.seq+"-"+K(),message:r,seq:i.records.seq++,type:o??p.NORMAL,tags:s??[],parents:i.records.head==null?[]:[i.records.head.id],branch:i.records.currBranch};i.records.head=n,k.info("main branch",d.mainBranchName),i.records.commits.has(n.id)&&k.warn(`Commit ID ${n.id} already exists`),i.records.commits.set(n.id,n),i.records.branches.set(i.records.currBranch,n.id),k.debug("in pushCommit "+n.id)},"commit"),Oe=$(function(e){let r=e.name;const t=e.order;if(r=L.sanitizeText(r,D()),i.records.branches.has(r))throw new Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${r}")`);i.records.branches.set(r,i.records.head!=null?i.records.head.id:null),i.records.branchConfig.set(r,{name:r,order:t}),ne(r),k.debug("in createBranch")},"branch"),_e=$(e=>{let r=e.branch,t=e.id;const o=e.type,s=e.tags,d=D();r=L.sanitizeText(r,d),t&&(t=L.sanitizeText(t,d));const n=i.records.branches.get(i.records.currBranch),a=i.records.branches.get(r),l=n?i.records.commits.get(n):void 0,h=a?i.records.commits.get(a):void 0;if(l&&h&&l.branch===r)throw new Error(`Cannot merge branch '${r}' into itself.`);if(i.records.currBranch===r){const c=new Error('Incorrect usage of "merge". Cannot merge a branch to itself');throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:["branch abc"]},c}if(l===void 0||!l){const c=new Error(`Incorrect usage of "merge". Current branch (${i.records.currBranch})has no commits`);throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:["commit"]},c}if(!i.records.branches.has(r)){const c=new Error('Incorrect usage of "merge". Branch to be merged ('+r+") does not exist");throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:[`branch ${r}`]},c}if(h===void 0||!h){const c=new Error('Incorrect usage of "merge". Branch to be merged ('+r+") has no commits");throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:['"commit"']},c}if(l===h){const c=new Error('Incorrect usage of "merge". Both branches have same head');throw c.hash={text:`merge ${r}`,token:`merge ${r}`,expected:["branch abc"]},c}if(t&&i.records.commits.has(t)){const c=new Error('Incorrect usage of "merge". Commit with id:'+t+" already exists, use different custom id");throw c.hash={text:`merge ${r} ${t} ${o} ${s==null?void 0:s.join(" ")}`,token:`merge ${r} ${t} ${o} ${s==null?void 0:s.join(" ")}`,expected:[`merge ${r} ${t}_UNIQUE ${o} ${s==null?void 0:s.join(" ")}`]},c}const g=a||"",f={id:t||`${i.records.seq}-${K()}`,message:`merged branch ${r} into ${i.records.currBranch}`,seq:i.records.seq++,parents:i.records.head==null?[]:[i.records.head.id,g],branch:i.records.currBranch,type:p.MERGE,customType:o,customId:!!t,tags:s??[]};i.records.head=f,i.records.commits.set(f.id,f),i.records.branches.set(i.records.currBranch,f.id),k.debug(i.records.branches),k.debug("in mergeBranch")},"merge"),Ge=$(function(e){let r=e.id,t=e.targetId,o=e.tags,s=e.parent;k.debug("Entering cherryPick:",r,t,o);const d=D();if(r=L.sanitizeText(r,d),t=L.sanitizeText(t,d),o=o==null?void 0:o.map(l=>L.sanitizeText(l,d)),s=L.sanitizeText(s,d),!r||!i.records.commits.has(r)){const l=new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');throw l.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},l}const n=i.records.commits.get(r);if(n===void 0||!n)throw new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');if(s&&!(Array.isArray(n.parents)&&n.parents.includes(s)))throw new Error("Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.");const a=n.branch;if(n.type===p.MERGE&&!s)throw new Error("Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.");if(!t||!i.records.commits.has(t)){if(a===i.records.currBranch){const f=new Error('Incorrect usage of "cherryPick". Source commit is already on current branch');throw f.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},f}const l=i.records.branches.get(i.records.currBranch);if(l===void 0||!l){const f=new Error(`Incorrect usage of "cherry-pick". Current branch (${i.records.currBranch})has no commits`);throw f.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},f}const h=i.records.commits.get(l);if(h===void 0||!h){const f=new Error(`Incorrect usage of "cherry-pick". Current branch (${i.records.currBranch})has no commits`);throw f.hash={text:`cherryPick ${r} ${t}`,token:`cherryPick ${r} ${t}`,expected:["cherry-pick abc"]},f}const g={id:i.records.seq+"-"+K(),message:`cherry-picked ${n==null?void 0:n.message} into ${i.records.currBranch}`,seq:i.records.seq++,parents:i.records.head==null?[]:[i.records.head.id,n.id],branch:i.records.currBranch,type:p.CHERRY_PICK,tags:o?o.filter(Boolean):[`cherry-pick:${n.id}${n.type===p.MERGE?`|parent:${s}`:""}`]};i.records.head=g,i.records.commits.set(g.id,g),i.records.branches.set(i.records.currBranch,g.id),k.debug(i.records.branches),k.debug("in cherryPick")}},"cherryPick"),ne=$(function(e){if(e=L.sanitizeText(e,D()),i.records.branches.has(e)){i.records.currBranch=e;const r=i.records.branches.get(i.records.currBranch);r===void 0||!r?i.records.head=null:i.records.head=i.records.commits.get(r)??null}else{const r=new Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${e}")`);throw r.hash={text:`checkout ${e}`,token:`checkout ${e}`,expected:[`branch ${e}`]},r}},"checkout");function X(e,r,t){const o=e.indexOf(r);o===-1?e.push(t):e.splice(o,1,t)}$(X,"upsert");function Z(e){const r=e.reduce((s,d)=>s.seq>d.seq?s:d,e[0]);let t="";e.forEach(function(s){s===r?t+=" *":t+=" |"});const o=[t,r.id,r.seq];for(const s in i.records.branches)i.records.branches.get(s)===r.id&&o.push(s);if(k.debug(o.join(" ")),r.parents&&r.parents.length==2&&r.parents[0]&&r.parents[1]){const s=i.records.commits.get(r.parents[0]);X(e,r,s),r.parents[1]&&e.push(i.records.commits.get(r.parents[1]))}else{if(r.parents.length==0)return;if(r.parents[0]){const s=i.records.commits.get(r.parents[0]);X(e,r,s)}}e=ae(e,s=>s.id),Z(e)}$(Z,"prettyPrintCommitHistory");var He=$(function(){k.debug(i.records.commits);const e=se()[0];Z([e])},"prettyPrint"),Ae=$(function(){i.reset(),we()},"clear"),Se=$(function(){return[...i.records.branchConfig.values()].map((r,t)=>r.order!==null&&r.order!==void 0?r:{...r,order:parseFloat(`0.${t}`)}).sort((r,t)=>(r.order??0)-(t.order??0)).map(({name:r})=>({name:r}))},"getBranchesAsObjArray"),De=$(function(){return i.records.branches},"getBranches"),Pe=$(function(){return i.records.commits},"getCommits"),se=$(function(){const e=[...i.records.commits.values()];return e.forEach(function(r){k.debug(r.id)}),e.sort((r,t)=>r.seq-t.seq),e},"getCommitsArray"),We=$(function(){return i.records.currBranch},"getCurrentBranch"),qe=$(function(){return i.records.direction},"getDirection"),Ne=$(function(){return i.records.head},"getHead"),oe={commitType:p,getConfig:D,setDirection:Le,setOptions:Me,getOptions:Re,commit:Ie,branch:Oe,merge:_e,cherryPick:Ge,checkout:ne,prettyPrint:He,clear:Ae,getBranchesAsObjArray:Se,getBranches:De,getCommits:Pe,getCommitsArray:se,getCurrentBranch:We,getDirection:qe,getHead:Ne,setAccTitle:me,getAccTitle:xe,getAccDescription:ye,setAccDescription:ue,setDiagramTitle:ge,getDiagramTitle:fe},Fe=$((e,r)=>{$e(e,r),e.dir&&r.setDirection(e.dir);for(const t of e.statements)ze(t,r)},"populate"),ze=$((e,r)=>{const o={Commit:$(s=>r.commit(Ye(s)),"Commit"),Branch:$(s=>r.branch(je(s)),"Branch"),Merge:$(s=>r.merge(Ue(s)),"Merge"),Checkout:$(s=>r.checkout(Ke(s)),"Checkout"),CherryPicking:$(s=>r.cherryPick(Ve(s)),"CherryPicking")}[e.$type];o?o(e):k.error(`Unknown statement type: ${e.$type}`)},"parseStatement"),Ye=$(e=>({id:e.id,msg:e.message??"",type:e.type!==void 0?p[e.type]:p.NORMAL,tags:e.tags??void 0}),"parseCommit"),je=$(e=>({name:e.name,order:e.order??0}),"parseBranch"),Ue=$(e=>({branch:e.branch,id:e.id??"",type:e.type!==void 0?p[e.type]:void 0,tags:e.tags??void 0}),"parseMerge"),Ke=$(e=>e.branch,"parseCheckout"),Ve=$(e=>{var t;return{id:e.id,targetId:"",tags:((t=e.tags)==null?void 0:t.length)===0?void 0:e.tags,parent:e.parent}},"parseCherryPicking"),Xe={parse:$(async e=>{const r=await Be("gitGraph",e);k.debug(r),Fe(r,oe)},"parse")},G=10,H=40,M=4,I=2,A=8,V=new Set(["redux","redux-dark","redux-color","redux-dark-color"]),J=12,ee=new Set(["redux-color","redux-dark-color"]),Je=new Set(["dark","redux-dark","redux-dark-color","neo-dark"]),S=$((e,r,t=!1)=>t&&e>0?(e-1)%(r-1)+1:e%r,"calcColorIndex"),C=new Map,T=new Map,j=30,N=new Map,U=[],O=0,y="LR",Qe=$(()=>{C.clear(),T.clear(),N.clear(),O=0,U=[],y="LR"},"clear"),ce=$(e=>{const r=document.createElementNS("http://www.w3.org/2000/svg","text");return(typeof e=="string"?e.split(/\\n|\n|/gi):e).forEach(o=>{const s=document.createElementNS("http://www.w3.org/2000/svg","tspan");s.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),s.setAttribute("dy","1em"),s.setAttribute("x","0"),s.setAttribute("class","row"),s.textContent=o.trim(),r.appendChild(s)}),r},"drawText"),ie=$(e=>{let r,t,o;return y==="BT"?(t=$((s,d)=>s<=d,"comparisonFunc"),o=1/0):(t=$((s,d)=>s>=d,"comparisonFunc"),o=0),e.forEach(s=>{var n,a;const d=y==="TB"||y=="BT"?(n=T.get(s))==null?void 0:n.y:(a=T.get(s))==null?void 0:a.x;d!==void 0&&t(d,o)&&(r=s,o=d)}),r},"findClosestParent"),Ze=$(e=>{let r="",t=1/0;return e.forEach(o=>{const s=T.get(o).y;s<=t&&(r=o,t=s)}),r||void 0},"findClosestParentBT"),er=$((e,r,t)=>{let o=t,s=t;const d=[];e.forEach(n=>{const a=r.get(n);if(!a)throw new Error(`Commit not found for key ${n}`);a.parents.length?(o=tr(a),s=Math.max(o,s)):d.push(a),ar(a,o)}),o=s,d.forEach(n=>{nr(n,o,t)}),e.forEach(n=>{const a=r.get(n);if(a!=null&&a.parents.length){const l=Ze(a.parents);o=T.get(l).y-H,o<=s&&(s=o);const h=C.get(a.branch).pos,g=o-G;T.set(a.id,{x:h,y:g})}})},"setParallelBTPos"),rr=$(e=>{var o;const r=ie(e.parents.filter(s=>s!==null));if(!r)throw new Error(`Closest parent not found for commit ${e.id}`);const t=(o=T.get(r))==null?void 0:o.y;if(t===void 0)throw new Error(`Closest parent position not found for commit ${e.id}`);return t},"findClosestParentPos"),tr=$(e=>rr(e)+H,"calculateCommitPosition"),ar=$((e,r)=>{const t=C.get(e.branch);if(!t)throw new Error(`Branch not found for commit ${e.id}`);const o=t.pos,s=r+G;return T.set(e.id,{x:o,y:s}),{x:o,y:s}},"setCommitPosition"),nr=$((e,r,t)=>{const o=C.get(e.branch);if(!o)throw new Error(`Branch not found for commit ${e.id}`);const s=r+t,d=o.pos;T.set(e.id,{x:d,y:s})},"setRootPosition"),sr=$((e,r,t,o,s,d)=>{const{theme:n}=z(),a=V.has(n??""),l=ee.has(n??""),h=Je.has(n??"");if(d===p.HIGHLIGHT)e.append("rect").attr("x",t.x-10+(a?3:0)).attr("y",t.y-10+(a?3:0)).attr("width",a?14:20).attr("height",a?14:20).attr("class",`commit ${r.id} commit-highlight${S(s,A,l)} ${o}-outer`),e.append("rect").attr("x",t.x-6+(a?2:0)).attr("y",t.y-6+(a?2:0)).attr("width",a?8:12).attr("height",a?8:12).attr("class",`commit ${r.id} commit${S(s,A,l)} ${o}-inner`);else if(d===p.CHERRY_PICK)e.append("circle").attr("cx",t.x).attr("cy",t.y).attr("r",a?7:10).attr("class",`commit ${r.id} ${o}`),e.append("circle").attr("cx",t.x-3).attr("cy",t.y+2).attr("r",a?2.5:2.75).attr("fill",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`),e.append("circle").attr("cx",t.x+3).attr("cy",t.y+2).attr("r",a?2.5:2.75).attr("fill",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`),e.append("line").attr("x1",t.x+3).attr("y1",t.y+1).attr("x2",t.x).attr("y2",t.y-5).attr("stroke",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`),e.append("line").attr("x1",t.x-3).attr("y1",t.y+1).attr("x2",t.x).attr("y2",t.y-5).attr("stroke",h?"#000000":"#fff").attr("class",`commit ${r.id} ${o}`);else{const g=e.append("circle");if(g.attr("cx",t.x),g.attr("cy",t.y),g.attr("r",a?7:10),g.attr("class",`commit ${r.id} commit${S(s,A,l)}`),d===p.MERGE){const f=e.append("circle");f.attr("cx",t.x),f.attr("cy",t.y),f.attr("r",a?5:6),f.attr("class",`commit ${o} ${r.id} commit${S(s,A,l)}`)}if(d===p.REVERSE){const f=e.append("path"),c=a?4:5;f.attr("d",`M ${t.x-c},${t.y-c}L${t.x+c},${t.y+c}M${t.x-c},${t.y+c}L${t.x+c},${t.y-c}`).attr("class",`commit ${o} ${r.id} commit${S(s,A,l)}`)}}},"drawCommitBullet"),or=$((e,r,t,o,s)=>{var d;if(r.type!==p.CHERRY_PICK&&(r.customId&&r.type===p.MERGE||r.type!==p.MERGE)&&s.showCommitLabel){const n=e.append("g"),a=n.insert("rect").attr("class","commit-label-bkg"),l=n.append("text").attr("x",o).attr("y",t.y+25).attr("class","commit-label").text(r.id),h=(d=l.node())==null?void 0:d.getBBox();if(h&&(a.attr("x",t.posWithOffset-h.width/2-I).attr("y",t.y+13.5).attr("width",h.width+2*I).attr("height",h.height+2*I),y==="TB"||y==="BT"?(a.attr("x",t.x-(h.width+4*M+5)).attr("y",t.y-12),l.attr("x",t.x-(h.width+4*M)).attr("y",t.y+h.height-12)):l.attr("x",t.posWithOffset-h.width/2),s.rotateCommitLabel))if(y==="TB"||y==="BT")l.attr("transform","rotate(-45, "+t.x+", "+t.y+")"),a.attr("transform","rotate(-45, "+t.x+", "+t.y+")");else{const g=-7.5-(h.width+10)/25*9.5,f=10+h.width/25*8.5;n.attr("transform","translate("+g+", "+f+") rotate(-45, "+o+", "+t.y+")")}}},"drawCommitLabel"),cr=$((e,r,t,o)=>{var s;if(r.tags.length>0){let d=0,n=0,a=0;const l=[];for(const h of r.tags.reverse()){const g=e.insert("polygon"),f=e.append("circle"),c=e.append("text").attr("y",t.y-16-d).attr("class","tag-label").text(h),x=(s=c.node())==null?void 0:s.getBBox();if(!x)throw new Error("Tag bbox not found");n=Math.max(n,x.width),a=Math.max(a,x.height),c.attr("x",t.posWithOffset-x.width/2),l.push({tag:c,hole:f,rect:g,yOffset:d}),d+=20}for(const{tag:h,hole:g,rect:f,yOffset:c}of l){const x=a/2,u=t.y-19.2-c;if(f.attr("class","tag-label-bkg").attr("points",` ${o-n/2-M/2},${u+I} ${o-n/2-M/2},${u-I} ${t.posWithOffset-n/2-M},${u-x-I} diff --git a/static/ml_canvas/assets/index-BXksgzya.js b/static/ml_canvas/assets/index-DYMv5Ibu.js similarity index 90% rename from static/ml_canvas/assets/index-BXksgzya.js rename to static/ml_canvas/assets/index-DYMv5Ibu.js index 2bdad6eb8..8bbd606b9 100644 --- a/static/ml_canvas/assets/index-BXksgzya.js +++ b/static/ml_canvas/assets/index-DYMv5Ibu.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TemplatesGalleryModal-sEhNFzeh.js","assets/vendor-flow-bDma3vSM.js","assets/vendor-utils-_6D5wMFs.js","assets/vendor-charts-CwfdE1jD.js","assets/mermaid.core-BCO0YdKy.js","assets/InferencePage-CxgKkiJo.js","assets/EDAPage-BYX7As83.js","assets/FormField-BxGvOnTr.js","assets/vendor-plotly-Bx-86y5L.js","assets/EDAPage-Dgihpmma.css","assets/DataDriftPage-Dpmcy0d5.js","assets/driftThresholds-BnFBRCeO.js","assets/ModelRegistry-lyme2_ha.js","assets/DeploymentsPage-DKzmwjpY.js","assets/SlowNodesPage-aiRJX30H.js","assets/AuditLogPage-CU3Ws-p_.js","assets/BaseModelParamsEditor-CrBgCypf.js","assets/GeoDistanceSettings-q_f9JrLj.js"])))=>i.map(i=>d[i]); -var P0=Object.defineProperty;var Gd=e=>{throw TypeError(e)};var I0=(e,s,r)=>s in e?P0(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var It=(e,s,r)=>I0(e,typeof s!="symbol"?s+"":s,r),Hi=(e,s,r)=>s.has(e)||Gd("Cannot "+r);var C=(e,s,r)=>(Hi(e,s,"read from private field"),r?r.call(e):s.get(e)),le=(e,s,r)=>s.has(e)?Gd("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,r),Z=(e,s,r,a)=>(Hi(e,s,"write to private field"),a?a.call(e,r):s.set(e,r),r),he=(e,s,r)=>(Hi(e,s,"access private method"),r);var io=(e,s,r,a)=>({set _(n){Z(e,s,n,r)},get _(){return C(e,s,a)}});import{j as t,c as Mp,b as Wi,d as A0,e as $0,f as Pp,g as $n,H as _l,P as is,h as F0,k as D0,l as Ip,m as L0,E as O0,R as Ap,i as $p,B as Fp,C as Dp,n as Dt,M as z0}from"./vendor-flow-bDma3vSM.js";import{g as Lp,a as p,b as ne,al as Op,aH as B0,X as Se,a1 as Fn,f as Lt,j as Ce,ac as Ke,aI as _c,aJ as V0,aw as zp,ad as rt,ab as Dn,T as Sc,aB as ps,af as Ct,A as U0,d as Pa,aK as ai,i as H0,E as W0,aL as G0,aM as q0,O as fe,c as hs,aN as K0,C as _t,as as Sl,N as dr,e as qt,J as Bp,ag as Me,Y as Ln,a6 as Vp,a7 as Up,y as Ps,m as xs,aO as Cc,L as ni,U as J0,$ as Y0,p as Ia,aP as Q0,ah as X0,n as Z0,w as _e,l as st,aQ as Cl,aR as oi,aS as xn,aT as eb,a4 as Aa,aU as Hp,z as Ec,K as ht,ao as El,S as ur,a3 as On,aE as Wp,_ as Pe,au as tb,av as sb,R as Gp,aG as Rc,aV as fn,aW as rb,aX as Tc,aY as Mc,I as ar,aZ as ab,a_ as $a,aF as qp,a$ as nb,aq as gn,b0 as Kp,b1 as Jp,b2 as ob,b3 as ib,b4 as lb,b5 as Rl,b6 as cb,W as ii,D as li,ai as Pc,b7 as Yp,ax as Qp,v as ss,aC as Ic,b8 as db,a2 as ub,u as mb,b9 as pb,ba as hb,bb as xb,bc as Xp,bd as Zp,be as fb,bf as gb,bg as bb,bh as yb,bi as vb,Z as Tl,bj as Ac,bk as $c,am as eh,bl as ci,bm as jb,bn as wb,bo as Nb,s as di,bp as th,bq as kb,br as _b,aa as sh,bs as Sb,bt as Cb,h as Fc,bu as Eb,bv as Rb,bw as Tb,bx as Mb,H as rh,by as ah,bz as Pb,bA as nh,bB as Dc,bC as Ib,bD as qd,bE as Ab,bF as $b,bG as Fb,bH as Db}from"./vendor-utils-_6D5wMFs.js";import{aY as Lb,u as Ob,r as zn,R as Ie,B as Xt,C as Be,X as De,Y as Le,T as Ae,h as lt,aj as zb,ak as Bb,j as wa,ah as Or,aZ as Vb,ag as Ub,ai as mt,av as Hb,a_ as xr,a$ as Wb,as as ct,au as fr,at as Zr,b0 as Gi,b1 as Kd}from"./vendor-charts-CwfdE1jD.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&a(i)}).observe(document,{childList:!0,subtree:!0});function r(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(n){if(n.ep)return;n.ep=!0;const o=r(n);fetch(n.href,o)}})();var lo={},Jd;function Gb(){if(Jd)return lo;Jd=1;var e=Lb();return lo.createRoot=e.createRoot,lo.hydrateRoot=e.hydrateRoot,lo}var qb=Gb();const Kb=Lp(qb);var Fa=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},vr,qs,ca,vp,Jb=(vp=class extends Fa{constructor(){super();le(this,vr);le(this,qs);le(this,ca);Z(this,ca,s=>{if(typeof window<"u"&&window.addEventListener){const r=()=>s();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){C(this,qs)||this.setEventListener(C(this,ca))}onUnsubscribe(){var s;this.hasListeners()||((s=C(this,qs))==null||s.call(this),Z(this,qs,void 0))}setEventListener(s){var r;Z(this,ca,s),(r=C(this,qs))==null||r.call(this),Z(this,qs,s(a=>{typeof a=="boolean"?this.setFocused(a):this.onFocus()}))}setFocused(s){C(this,vr)!==s&&(Z(this,vr,s),this.onFocus())}onFocus(){const s=this.isFocused();this.listeners.forEach(r=>{r(s)})}isFocused(){var s;return typeof C(this,vr)=="boolean"?C(this,vr):((s=globalThis.document)==null?void 0:s.visibilityState)!=="hidden"}},vr=new WeakMap,qs=new WeakMap,ca=new WeakMap,vp),Lc=new Jb,Yb={setTimeout:(e,s)=>setTimeout(e,s),clearTimeout:e=>clearTimeout(e),setInterval:(e,s)=>setInterval(e,s),clearInterval:e=>clearInterval(e)},Ks,kc,jp,Qb=(jp=class{constructor(){le(this,Ks,Yb);le(this,kc,!1)}setTimeoutProvider(e){Z(this,Ks,e)}setTimeout(e,s){return C(this,Ks).setTimeout(e,s)}clearTimeout(e){C(this,Ks).clearTimeout(e)}setInterval(e,s){return C(this,Ks).setInterval(e,s)}clearInterval(e){C(this,Ks).clearInterval(e)}},Ks=new WeakMap,kc=new WeakMap,jp),br=new Qb;function Xb(e){setTimeout(e,0)}var Zb=typeof window>"u"||"Deno"in globalThis;function pt(){}function ey(e,s){return typeof e=="function"?e(s):e}function Ml(e){return typeof e=="number"&&e>=0&&e!==1/0}function oh(e,s){return Math.max(e+(s||0)-Date.now(),0)}function sr(e,s){return typeof e=="function"?e(s):e}function wt(e,s){return typeof e=="function"?e(s):e}function Yd(e,s){const{type:r="all",exact:a,fetchStatus:n,predicate:o,queryKey:i,stale:l}=e;if(i){if(a){if(s.queryHash!==Oc(i,s.options))return!1}else if(!bn(s.queryKey,i))return!1}if(r!=="all"){const c=s.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&s.isStale()!==l||n&&n!==s.state.fetchStatus||o&&!o(s))}function Qd(e,s){const{exact:r,status:a,predicate:n,mutationKey:o}=e;if(o){if(!s.options.mutationKey)return!1;if(r){if(Ir(s.options.mutationKey)!==Ir(o))return!1}else if(!bn(s.options.mutationKey,o))return!1}return!(a&&s.state.status!==a||n&&!n(s))}function Oc(e,s){return((s==null?void 0:s.queryKeyHashFn)||Ir)(e)}function Ir(e){return JSON.stringify(e,(s,r)=>Pl(r)?Object.keys(r).sort().reduce((a,n)=>(a[n]=r[n],a),{}):r)}function bn(e,s){return e===s?!0:typeof e!=typeof s?!1:e&&s&&typeof e=="object"&&typeof s=="object"?Object.keys(s).every(r=>bn(e[r],s[r])):!1}var ty=Object.prototype.hasOwnProperty;function ih(e,s,r=0){if(e===s)return e;if(r>500)return s;const a=Xd(e)&&Xd(s);if(!a&&!(Pl(e)&&Pl(s)))return s;const o=(a?e:Object.keys(e)).length,i=a?s:Object.keys(s),l=i.length,c=a?new Array(l):{};let d=0;for(let m=0;m{br.setTimeout(s,e)})}function Il(e,s,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,s):r.structuralSharing!==!1?ih(e,s):s}function ry(e,s,r=0){const a=[...e,s];return r&&a.length>r?a.slice(1):a}function ay(e,s,r=0){const a=[s,...e];return r&&a.length>r?a.slice(0,-1):a}var zc=Symbol();function lh(e,s){return!e.queryFn&&(s!=null&&s.initialPromise)?()=>s.initialPromise:!e.queryFn||e.queryFn===zc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bc(e,s){return typeof e=="function"?e(...s):!!e}function ny(e,s,r){let a=!1,n;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(n??(n=s()),a||(a=!0,n.aborted?r():n.addEventListener("abort",r,{once:!0})),n)}),e}var yn=(()=>{let e=()=>Zb;return{isServer(){return e()},setIsServer(s){e=s}}})();function Al(){let e,s;const r=new Promise((n,o)=>{e=n,s=o});r.status="pending",r.catch(()=>{});function a(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{a({status:"fulfilled",value:n}),e(n)},r.reject=n=>{a({status:"rejected",reason:n}),s(n)},r}var oy=Xb;function iy(){let e=[],s=0,r=l=>{l()},a=l=>{l()},n=oy;const o=l=>{s?e.push(l):n(()=>{r(l)})},i=()=>{const l=e;e=[],l.length&&n(()=>{a(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;s++;try{c=l()}finally{s--,s||i()}return c},batchCalls:l=>(...c)=>{o(()=>{l(...c)})},schedule:o,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{a=l},setScheduler:l=>{n=l}}}var et=iy(),da,Js,ua,wp,ly=(wp=class extends Fa{constructor(){super();le(this,da,!0);le(this,Js);le(this,ua);Z(this,ua,s=>{if(typeof window<"u"&&window.addEventListener){const r=()=>s(!0),a=()=>s(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",a,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",a)}}})}onSubscribe(){C(this,Js)||this.setEventListener(C(this,ua))}onUnsubscribe(){var s;this.hasListeners()||((s=C(this,Js))==null||s.call(this),Z(this,Js,void 0))}setEventListener(s){var r;Z(this,ua,s),(r=C(this,Js))==null||r.call(this),Z(this,Js,s(this.setOnline.bind(this)))}setOnline(s){C(this,da)!==s&&(Z(this,da,s),this.listeners.forEach(a=>{a(s)}))}isOnline(){return C(this,da)}},da=new WeakMap,Js=new WeakMap,ua=new WeakMap,wp),Oo=new ly;function cy(e){return Math.min(1e3*2**e,3e4)}function ch(e){return(e??"online")==="online"?Oo.isOnline():!0}var $l=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function dh(e){let s=!1,r=0,a;const n=Al(),o=()=>n.status!=="pending",i=f=>{var y;if(!o()){const b=new $l(f);h(b),(y=e.onCancel)==null||y.call(e,b)}},l=()=>{s=!0},c=()=>{s=!1},d=()=>Lc.isFocused()&&(e.networkMode==="always"||Oo.isOnline())&&e.canRun(),m=()=>ch(e.networkMode)&&e.canRun(),u=f=>{o()||(a==null||a(),n.resolve(f))},h=f=>{o()||(a==null||a(),n.reject(f))},x=()=>new Promise(f=>{var y;a=b=>{(o()||d())&&f(b)},(y=e.onPause)==null||y.call(e)}).then(()=>{var f;a=void 0,o()||(f=e.onContinue)==null||f.call(e)}),g=()=>{if(o())return;let f;const y=r===0?e.initialPromise:void 0;try{f=y??e.fn()}catch(b){f=Promise.reject(b)}Promise.resolve(f).then(u).catch(b=>{var k;if(o())return;const v=e.retry??(yn.isServer()?0:3),j=e.retryDelay??cy,w=typeof j=="function"?j(r,b):j,N=v===!0||typeof v=="number"&&rd()?void 0:x()).then(()=>{s?h(b):g()})})};return{promise:n,status:()=>n.status,cancel:i,continue:()=>(a==null||a(),n),cancelRetry:l,continueRetry:c,canStart:m,start:()=>(m()?g():x().then(g),n)}}var jr,Np,uh=(Np=class{constructor(){le(this,jr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ml(this.gcTime)&&Z(this,jr,br.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(yn.isServer()?1/0:300*1e3))}clearGcTimeout(){C(this,jr)!==void 0&&(br.clearTimeout(C(this,jr)),Z(this,jr,void 0))}},jr=new WeakMap,Np);function dy(e){return{onFetch:(s,r)=>{var m,u,h,x,g;const a=s.options,n=(h=(u=(m=s.fetchOptions)==null?void 0:m.meta)==null?void 0:u.fetchMore)==null?void 0:h.direction,o=((x=s.state.data)==null?void 0:x.pages)||[],i=((g=s.state.data)==null?void 0:g.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const d=async()=>{let f=!1;const y=j=>{ny(j,()=>s.signal,()=>f=!0)},b=lh(s.options,s.fetchOptions),v=async(j,w,N)=>{if(f)return Promise.reject(s.signal.reason);if(w==null&&j.pages.length)return Promise.resolve(j);const _=(()=>{const M={client:s.client,queryKey:s.queryKey,pageParam:w,direction:N?"backward":"forward",meta:s.options.meta};return y(M),M})(),R=await b(_),{maxPages:P}=s.options,E=N?ay:ry;return{pages:E(j.pages,R,P),pageParams:E(j.pageParams,w,P)}};if(n&&o.length){const j=n==="backward",w=j?mh:Fl,N={pages:o,pageParams:i},k=w(a,N);l=await v(N,k,j)}else{const j=e??o.length;do{const w=c===0?i[0]??a.initialPageParam:Fl(a,l);if(c>0&&w==null)break;l=await v(l,w),c++}while(c{var f,y;return(y=(f=s.options).persister)==null?void 0:y.call(f,d,{client:s.client,queryKey:s.queryKey,meta:s.options.meta,signal:s.signal},r)}:s.fetchFn=d}}}function Fl(e,{pages:s,pageParams:r}){const a=s.length-1;return s.length>0?e.getNextPageParam(s[a],s,r[a],r):void 0}function mh(e,{pages:s,pageParams:r}){var a;return s.length>0?(a=e.getPreviousPageParam)==null?void 0:a.call(e,s[0],s,r[0],r):void 0}function H6(e,s){return s?Fl(e,s)!=null:!1}function W6(e,s){return!s||!e.getPreviousPageParam?!1:mh(e,s)!=null}var ma,wr,pa,$t,Nr,tt,Tn,kr,jt,ph,Ns,kp,uy=(kp=class extends uh{constructor(s){super();le(this,jt);le(this,ma);le(this,wr);le(this,pa);le(this,$t);le(this,Nr);le(this,tt);le(this,Tn);le(this,kr);Z(this,kr,!1),Z(this,Tn,s.defaultOptions),this.setOptions(s.options),this.observers=[],Z(this,Nr,s.client),Z(this,$t,C(this,Nr).getQueryCache()),this.queryKey=s.queryKey,this.queryHash=s.queryHash,Z(this,wr,tu(this.options)),this.state=s.state??C(this,wr),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return C(this,ma)}get promise(){var s;return(s=C(this,tt))==null?void 0:s.promise}setOptions(s){if(this.options={...C(this,Tn),...s},s!=null&&s._type&&Z(this,ma,s._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=tu(this.options);r.data!==void 0&&(this.setState(eu(r.data,r.dataUpdatedAt)),Z(this,wr,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&C(this,$t).remove(this)}setData(s,r){const a=Il(this.state.data,s,this.options);return he(this,jt,Ns).call(this,{data:a,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),a}setState(s){he(this,jt,Ns).call(this,{type:"setState",state:s})}cancel(s){var a,n;const r=(a=C(this,tt))==null?void 0:a.promise;return(n=C(this,tt))==null||n.cancel(s),r?r.then(pt).catch(pt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return C(this,wr)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(s=>wt(s.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===zc||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(s=>sr(s.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(s=>s.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(s=0){return this.state.data===void 0?!0:s==="static"?!1:this.state.isInvalidated?!0:!oh(this.state.dataUpdatedAt,s)}onFocus(){var r;const s=this.observers.find(a=>a.shouldFetchOnWindowFocus());s==null||s.refetch({cancelRefetch:!1}),(r=C(this,tt))==null||r.continue()}onOnline(){var r;const s=this.observers.find(a=>a.shouldFetchOnReconnect());s==null||s.refetch({cancelRefetch:!1}),(r=C(this,tt))==null||r.continue()}addObserver(s){this.observers.includes(s)||(this.observers.push(s),this.clearGcTimeout(),C(this,$t).notify({type:"observerAdded",query:this,observer:s}))}removeObserver(s){this.observers.includes(s)&&(this.observers=this.observers.filter(r=>r!==s),this.observers.length||(C(this,tt)&&(C(this,kr)||he(this,jt,ph).call(this)?C(this,tt).cancel({revert:!0}):C(this,tt).cancelRetry()),this.scheduleGc()),C(this,$t).notify({type:"observerRemoved",query:this,observer:s}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||he(this,jt,Ns).call(this,{type:"invalidate"})}async fetch(s,r){var d,m,u,h,x,g,f,y,b,v,j;if(this.state.fetchStatus!=="idle"&&((d=C(this,tt))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(C(this,tt))return C(this,tt).continueRetry(),C(this,tt).promise}if(s&&this.setOptions(s),!this.options.queryFn){const w=this.observers.find(N=>N.options.queryFn);w&&this.setOptions(w.options)}const a=new AbortController,n=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(Z(this,kr,!0),a.signal)})},o=()=>{const w=lh(this.options,r),k=(()=>{const _={client:C(this,Nr),queryKey:this.queryKey,meta:this.meta};return n(_),_})();return Z(this,kr,!1),this.options.persister?this.options.persister(w,k,this):w(k)},l=(()=>{const w={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:C(this,Nr),state:this.state,fetchFn:o};return n(w),w})(),c=C(this,ma)==="infinite"?dy(this.options.pages):this.options.behavior;c==null||c.onFetch(l,this),Z(this,pa,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&he(this,jt,Ns).call(this,{type:"fetch",meta:(u=l.fetchOptions)==null?void 0:u.meta}),Z(this,tt,dh({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:w=>{w instanceof $l&&w.revert&&this.setState({...C(this,pa),fetchStatus:"idle"}),a.abort()},onFail:(w,N)=>{he(this,jt,Ns).call(this,{type:"failed",failureCount:w,error:N})},onPause:()=>{he(this,jt,Ns).call(this,{type:"pause"})},onContinue:()=>{he(this,jt,Ns).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const w=await C(this,tt).start();if(w===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(w),(x=(h=C(this,$t).config).onSuccess)==null||x.call(h,w,this),(f=(g=C(this,$t).config).onSettled)==null||f.call(g,w,this.state.error,this),w}catch(w){if(w instanceof $l){if(w.silent)return C(this,tt).promise;if(w.revert){if(this.state.data===void 0)throw w;return this.state.data}}throw he(this,jt,Ns).call(this,{type:"error",error:w}),(b=(y=C(this,$t).config).onError)==null||b.call(y,w,this),(j=(v=C(this,$t).config).onSettled)==null||j.call(v,this.state.data,w,this),w}finally{this.scheduleGc()}}},ma=new WeakMap,wr=new WeakMap,pa=new WeakMap,$t=new WeakMap,Nr=new WeakMap,tt=new WeakMap,Tn=new WeakMap,kr=new WeakMap,jt=new WeakSet,ph=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ns=function(s){const r=a=>{switch(s.type){case"failed":return{...a,fetchFailureCount:s.failureCount,fetchFailureReason:s.error};case"pause":return{...a,fetchStatus:"paused"};case"continue":return{...a,fetchStatus:"fetching"};case"fetch":return{...a,...hh(a.data,this.options),fetchMeta:s.meta??null};case"success":const n={...a,...eu(s.data,s.dataUpdatedAt),dataUpdateCount:a.dataUpdateCount+1,...!s.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Z(this,pa,s.manual?n:void 0),n;case"error":const o=s.error;return{...a,error:o,errorUpdateCount:a.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:a.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...a,isInvalidated:!0};case"setState":return{...a,...s.state}}};this.state=r(this.state),et.batch(()=>{this.observers.forEach(a=>{a.onQueryUpdate()}),C(this,$t).notify({query:this,type:"updated",action:s})})},kp);function hh(e,s){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ch(s.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function eu(e,s){return{data:e,dataUpdatedAt:s??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tu(e){const s=typeof e.initialData=="function"?e.initialData():e.initialData,r=s!==void 0,a=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:s,dataUpdateCount:0,dataUpdatedAt:r?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var ft,ye,Mn,dt,_r,ha,ks,Ys,Pn,xa,fa,Sr,Cr,Qs,ga,ke,dn,Dl,Ll,Ol,zl,Bl,Vl,Ul,xh,_p,my=(_p=class extends Fa{constructor(s,r){super();le(this,ke);le(this,ft);le(this,ye);le(this,Mn);le(this,dt);le(this,_r);le(this,ha);le(this,ks);le(this,Ys);le(this,Pn);le(this,xa);le(this,fa);le(this,Sr);le(this,Cr);le(this,Qs);le(this,ga,new Set);this.options=r,Z(this,ft,s),Z(this,Ys,null),Z(this,ks,Al()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(C(this,ye).addObserver(this),su(C(this,ye),this.options)?he(this,ke,dn).call(this):this.updateResult(),he(this,ke,zl).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Hl(C(this,ye),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Hl(C(this,ye),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,he(this,ke,Bl).call(this),he(this,ke,Vl).call(this),C(this,ye).removeObserver(this)}setOptions(s){const r=this.options,a=C(this,ye);if(this.options=C(this,ft).defaultQueryOptions(s),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof wt(this.options.enabled,C(this,ye))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");he(this,ke,Ul).call(this),C(this,ye).setOptions(this.options),r._defaulted&&!Lo(this.options,r)&&C(this,ft).getQueryCache().notify({type:"observerOptionsUpdated",query:C(this,ye),observer:this});const n=this.hasListeners();n&&ru(C(this,ye),a,this.options,r)&&he(this,ke,dn).call(this),this.updateResult(),n&&(C(this,ye)!==a||wt(this.options.enabled,C(this,ye))!==wt(r.enabled,C(this,ye))||sr(this.options.staleTime,C(this,ye))!==sr(r.staleTime,C(this,ye)))&&he(this,ke,Dl).call(this);const o=he(this,ke,Ll).call(this);n&&(C(this,ye)!==a||wt(this.options.enabled,C(this,ye))!==wt(r.enabled,C(this,ye))||o!==C(this,Qs))&&he(this,ke,Ol).call(this,o)}getOptimisticResult(s){const r=C(this,ft).getQueryCache().build(C(this,ft),s),a=this.createResult(r,s);return hy(this,a)&&(Z(this,dt,a),Z(this,ha,this.options),Z(this,_r,C(this,ye).state)),a}getCurrentResult(){return C(this,dt)}trackResult(s,r){return new Proxy(s,{get:(a,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&C(this,ks).status==="pending"&&C(this,ks).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(a,n))})}trackProp(s){C(this,ga).add(s)}getCurrentQuery(){return C(this,ye)}refetch({...s}={}){return this.fetch({...s})}fetchOptimistic(s){const r=C(this,ft).defaultQueryOptions(s),a=C(this,ft).getQueryCache().build(C(this,ft),r);return a.fetch().then(()=>this.createResult(a,r))}fetch(s){return he(this,ke,dn).call(this,{...s,cancelRefetch:s.cancelRefetch??!0}).then(()=>(this.updateResult(),C(this,dt)))}createResult(s,r){var P;const a=C(this,ye),n=this.options,o=C(this,dt),i=C(this,_r),l=C(this,ha),d=s!==a?s.state:C(this,Mn),{state:m}=s;let u={...m},h=!1,x;if(r._optimisticResults){const E=this.hasListeners(),M=!E&&su(s,r),S=E&&ru(s,a,r,n);(M||S)&&(u={...u,...hh(m.data,s.options)}),r._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:f,status:y}=u;x=u.data;let b=!1;if(r.placeholderData!==void 0&&x===void 0&&y==="pending"){let E;o!=null&&o.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(E=o.data,b=!0):E=typeof r.placeholderData=="function"?r.placeholderData((P=C(this,fa))==null?void 0:P.state.data,C(this,fa)):r.placeholderData,E!==void 0&&(y="success",x=Il(o==null?void 0:o.data,E,r),h=!0)}if(r.select&&x!==void 0&&!b)if(o&&x===(i==null?void 0:i.data)&&r.select===C(this,Pn))x=C(this,xa);else try{Z(this,Pn,r.select),x=r.select(x),x=Il(o==null?void 0:o.data,x,r),Z(this,xa,x),Z(this,Ys,null)}catch(E){Z(this,Ys,E)}C(this,Ys)&&(g=C(this,Ys),x=C(this,xa),f=Date.now(),y="error");const v=u.fetchStatus==="fetching",j=y==="pending",w=y==="error",N=j&&v,k=x!==void 0,R={status:y,fetchStatus:u.fetchStatus,isPending:j,isSuccess:y==="success",isError:w,isInitialLoading:N,isLoading:N,data:x,dataUpdatedAt:u.dataUpdatedAt,error:g,errorUpdatedAt:f,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:s.isFetched(),isFetchedAfterMount:u.dataUpdateCount>d.dataUpdateCount||u.errorUpdateCount>d.errorUpdateCount,isFetching:v,isRefetching:v&&!j,isLoadingError:w&&!k,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:w&&k,isStale:Vc(s,r),refetch:this.refetch,promise:C(this,ks),isEnabled:wt(r.enabled,s)!==!1};if(this.options.experimental_prefetchInRender){const E=R.data!==void 0,M=R.status==="error"&&!E,S=A=>{M?A.reject(R.error):E&&A.resolve(R.data)},T=()=>{const A=Z(this,ks,R.promise=Al());S(A)},I=C(this,ks);switch(I.status){case"pending":s.queryHash===a.queryHash&&S(I);break;case"fulfilled":(M||R.data!==I.value)&&T();break;case"rejected":(!M||R.error!==I.reason)&&T();break}}return R}updateResult(){const s=C(this,dt),r=this.createResult(C(this,ye),this.options);if(Z(this,_r,C(this,ye).state),Z(this,ha,this.options),C(this,_r).data!==void 0&&Z(this,fa,C(this,ye)),Lo(r,s))return;Z(this,dt,r);const a=()=>{if(!s)return!0;const{notifyOnChangeProps:n}=this.options,o=typeof n=="function"?n():n;if(o==="all"||!o&&!C(this,ga).size)return!0;const i=new Set(o??C(this,ga));return this.options.throwOnError&&i.add("error"),Object.keys(C(this,dt)).some(l=>{const c=l;return C(this,dt)[c]!==s[c]&&i.has(c)})};he(this,ke,xh).call(this,{listeners:a()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&he(this,ke,zl).call(this)}},ft=new WeakMap,ye=new WeakMap,Mn=new WeakMap,dt=new WeakMap,_r=new WeakMap,ha=new WeakMap,ks=new WeakMap,Ys=new WeakMap,Pn=new WeakMap,xa=new WeakMap,fa=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,Qs=new WeakMap,ga=new WeakMap,ke=new WeakSet,dn=function(s){he(this,ke,Ul).call(this);let r=C(this,ye).fetch(this.options,s);return s!=null&&s.throwOnError||(r=r.catch(pt)),r},Dl=function(){he(this,ke,Bl).call(this);const s=sr(this.options.staleTime,C(this,ye));if(yn.isServer()||C(this,dt).isStale||!Ml(s))return;const a=oh(C(this,dt).dataUpdatedAt,s)+1;Z(this,Sr,br.setTimeout(()=>{C(this,dt).isStale||this.updateResult()},a))},Ll=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(C(this,ye)):this.options.refetchInterval)??!1},Ol=function(s){he(this,ke,Vl).call(this),Z(this,Qs,s),!(yn.isServer()||wt(this.options.enabled,C(this,ye))===!1||!Ml(C(this,Qs))||C(this,Qs)===0)&&Z(this,Cr,br.setInterval(()=>{(this.options.refetchIntervalInBackground||Lc.isFocused())&&he(this,ke,dn).call(this)},C(this,Qs)))},zl=function(){he(this,ke,Dl).call(this),he(this,ke,Ol).call(this,he(this,ke,Ll).call(this))},Bl=function(){C(this,Sr)!==void 0&&(br.clearTimeout(C(this,Sr)),Z(this,Sr,void 0))},Vl=function(){C(this,Cr)!==void 0&&(br.clearInterval(C(this,Cr)),Z(this,Cr,void 0))},Ul=function(){const s=C(this,ft).getQueryCache().build(C(this,ft),this.options);if(s===C(this,ye))return;const r=C(this,ye);Z(this,ye,s),Z(this,Mn,s.state),this.hasListeners()&&(r==null||r.removeObserver(this),s.addObserver(this))},xh=function(s){et.batch(()=>{s.listeners&&this.listeners.forEach(r=>{r(C(this,dt))}),C(this,ft).getQueryCache().notify({query:C(this,ye),type:"observerResultsUpdated"})})},_p);function py(e,s){return wt(s.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&wt(s.retryOnMount,e)===!1)}function su(e,s){return py(e,s)||e.state.data!==void 0&&Hl(e,s,s.refetchOnMount)}function Hl(e,s,r){if(wt(s.enabled,e)!==!1&&sr(s.staleTime,e)!=="static"){const a=typeof r=="function"?r(e):r;return a==="always"||a!==!1&&Vc(e,s)}return!1}function ru(e,s,r,a){return(e!==s||wt(a.enabled,e)===!1)&&(!r.suspense||e.state.status!=="error")&&Vc(e,r)}function Vc(e,s){return wt(s.enabled,e)!==!1&&e.isStaleByTime(sr(s.staleTime,e))}function hy(e,s){return!Lo(e.getCurrentResult(),s)}var In,rs,ot,Er,as,Hs,Sp,xy=(Sp=class extends uh{constructor(s){super();le(this,as);le(this,In);le(this,rs);le(this,ot);le(this,Er);Z(this,In,s.client),this.mutationId=s.mutationId,Z(this,ot,s.mutationCache),Z(this,rs,[]),this.state=s.state||fh(),this.setOptions(s.options),this.scheduleGc()}setOptions(s){this.options=s,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(s){C(this,rs).includes(s)||(C(this,rs).push(s),this.clearGcTimeout(),C(this,ot).notify({type:"observerAdded",mutation:this,observer:s}))}removeObserver(s){Z(this,rs,C(this,rs).filter(r=>r!==s)),this.scheduleGc(),C(this,ot).notify({type:"observerRemoved",mutation:this,observer:s})}optionalRemove(){C(this,rs).length||(this.state.status==="pending"?this.scheduleGc():C(this,ot).remove(this))}continue(){var s;return((s=C(this,Er))==null?void 0:s.continue())??this.execute(this.state.variables)}async execute(s){var i,l,c,d,m,u,h,x,g,f,y,b,v,j,w,N,k,_;const r=()=>{he(this,as,Hs).call(this,{type:"continue"})},a={client:C(this,In),meta:this.options.meta,mutationKey:this.options.mutationKey};Z(this,Er,dh({fn:()=>this.options.mutationFn?this.options.mutationFn(s,a):Promise.reject(new Error("No mutationFn found")),onFail:(R,P)=>{he(this,as,Hs).call(this,{type:"failed",failureCount:R,error:P})},onPause:()=>{he(this,as,Hs).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>C(this,ot).canRun(this)}));const n=this.state.status==="pending",o=!C(this,Er).canStart();try{if(n)r();else{he(this,as,Hs).call(this,{type:"pending",variables:s,isPaused:o}),C(this,ot).config.onMutate&&await C(this,ot).config.onMutate(s,this,a);const P=await((l=(i=this.options).onMutate)==null?void 0:l.call(i,s,a));P!==this.state.context&&he(this,as,Hs).call(this,{type:"pending",context:P,variables:s,isPaused:o})}const R=await C(this,Er).start();return await((d=(c=C(this,ot).config).onSuccess)==null?void 0:d.call(c,R,s,this.state.context,this,a)),await((u=(m=this.options).onSuccess)==null?void 0:u.call(m,R,s,this.state.context,a)),await((x=(h=C(this,ot).config).onSettled)==null?void 0:x.call(h,R,null,this.state.variables,this.state.context,this,a)),await((f=(g=this.options).onSettled)==null?void 0:f.call(g,R,null,s,this.state.context,a)),he(this,as,Hs).call(this,{type:"success",data:R}),R}catch(R){try{await((b=(y=C(this,ot).config).onError)==null?void 0:b.call(y,R,s,this.state.context,this,a))}catch(P){Promise.reject(P)}try{await((j=(v=this.options).onError)==null?void 0:j.call(v,R,s,this.state.context,a))}catch(P){Promise.reject(P)}try{await((N=(w=C(this,ot).config).onSettled)==null?void 0:N.call(w,void 0,R,this.state.variables,this.state.context,this,a))}catch(P){Promise.reject(P)}try{await((_=(k=this.options).onSettled)==null?void 0:_.call(k,void 0,R,s,this.state.context,a))}catch(P){Promise.reject(P)}throw he(this,as,Hs).call(this,{type:"error",error:R}),R}finally{C(this,ot).runNext(this)}}},In=new WeakMap,rs=new WeakMap,ot=new WeakMap,Er=new WeakMap,as=new WeakSet,Hs=function(s){const r=a=>{switch(s.type){case"failed":return{...a,failureCount:s.failureCount,failureReason:s.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:s.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:s.isPaused,status:"pending",variables:s.variables,submittedAt:Date.now()};case"success":return{...a,data:s.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:s.error,failureCount:a.failureCount+1,failureReason:s.error,isPaused:!1,status:"error"}}};this.state=r(this.state),et.batch(()=>{C(this,rs).forEach(a=>{a.onMutationUpdate(s)}),C(this,ot).notify({mutation:this,type:"updated",action:s})})},Sp);function fh(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var _s,Ut,An,Cp,fy=(Cp=class extends Fa{constructor(s={}){super();le(this,_s);le(this,Ut);le(this,An);this.config=s,Z(this,_s,new Set),Z(this,Ut,new Map),Z(this,An,0)}build(s,r,a){const n=new xy({client:s,mutationCache:this,mutationId:++io(this,An)._,options:s.defaultMutationOptions(r),state:a});return this.add(n),n}add(s){C(this,_s).add(s);const r=co(s);if(typeof r=="string"){const a=C(this,Ut).get(r);a?a.push(s):C(this,Ut).set(r,[s])}this.notify({type:"added",mutation:s})}remove(s){if(C(this,_s).delete(s)){const r=co(s);if(typeof r=="string"){const a=C(this,Ut).get(r);if(a)if(a.length>1){const n=a.indexOf(s);n!==-1&&a.splice(n,1)}else a[0]===s&&C(this,Ut).delete(r)}}this.notify({type:"removed",mutation:s})}canRun(s){const r=co(s);if(typeof r=="string"){const a=C(this,Ut).get(r),n=a==null?void 0:a.find(o=>o.state.status==="pending");return!n||n===s}else return!0}runNext(s){var a;const r=co(s);if(typeof r=="string"){const n=(a=C(this,Ut).get(r))==null?void 0:a.find(o=>o!==s&&o.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){et.batch(()=>{C(this,_s).forEach(s=>{this.notify({type:"removed",mutation:s})}),C(this,_s).clear(),C(this,Ut).clear()})}getAll(){return Array.from(C(this,_s))}find(s){const r={exact:!0,...s};return this.getAll().find(a=>Qd(r,a))}findAll(s={}){return this.getAll().filter(r=>Qd(s,r))}notify(s){et.batch(()=>{this.listeners.forEach(r=>{r(s)})})}resumePausedMutations(){const s=this.getAll().filter(r=>r.state.isPaused);return et.batch(()=>Promise.all(s.map(r=>r.continue().catch(pt))))}},_s=new WeakMap,Ut=new WeakMap,An=new WeakMap,Cp);function co(e){var s;return(s=e.options.scope)==null?void 0:s.id}var Ss,Xs,gt,Cs,Es,Ro,Wl,Ep,gy=(Ep=class extends Fa{constructor(r,a){super();le(this,Es);le(this,Ss);le(this,Xs);le(this,gt);le(this,Cs);Z(this,Ss,r),this.setOptions(a),this.bindMethods(),he(this,Es,Ro).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var n;const a=this.options;this.options=C(this,Ss).defaultMutationOptions(r),Lo(this.options,a)||C(this,Ss).getMutationCache().notify({type:"observerOptionsUpdated",mutation:C(this,gt),observer:this}),a!=null&&a.mutationKey&&this.options.mutationKey&&Ir(a.mutationKey)!==Ir(this.options.mutationKey)?this.reset():((n=C(this,gt))==null?void 0:n.state.status)==="pending"&&C(this,gt).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=C(this,gt))==null||r.removeObserver(this)}onMutationUpdate(r){he(this,Es,Ro).call(this),he(this,Es,Wl).call(this,r)}getCurrentResult(){return C(this,Xs)}reset(){var r;(r=C(this,gt))==null||r.removeObserver(this),Z(this,gt,void 0),he(this,Es,Ro).call(this),he(this,Es,Wl).call(this)}mutate(r,a){var n;return Z(this,Cs,a),(n=C(this,gt))==null||n.removeObserver(this),Z(this,gt,C(this,Ss).getMutationCache().build(C(this,Ss),this.options)),C(this,gt).addObserver(this),C(this,gt).execute(r)}},Ss=new WeakMap,Xs=new WeakMap,gt=new WeakMap,Cs=new WeakMap,Es=new WeakSet,Ro=function(){var a;const r=((a=C(this,gt))==null?void 0:a.state)??fh();Z(this,Xs,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},Wl=function(r){et.batch(()=>{var a,n,o,i,l,c,d,m;if(C(this,Cs)&&this.hasListeners()){const u=C(this,Xs).variables,h=C(this,Xs).context,x={client:C(this,Ss),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(n=(a=C(this,Cs)).onSuccess)==null||n.call(a,r.data,u,h,x)}catch(g){Promise.reject(g)}try{(i=(o=C(this,Cs)).onSettled)==null||i.call(o,r.data,null,u,h,x)}catch(g){Promise.reject(g)}}else if((r==null?void 0:r.type)==="error"){try{(c=(l=C(this,Cs)).onError)==null||c.call(l,r.error,u,h,x)}catch(g){Promise.reject(g)}try{(m=(d=C(this,Cs)).onSettled)==null||m.call(d,void 0,r.error,u,h,x)}catch(g){Promise.reject(g)}}}this.listeners.forEach(u=>{u(C(this,Xs))})})},Ep),ns,Rp,by=(Rp=class extends Fa{constructor(s={}){super();le(this,ns);this.config=s,Z(this,ns,new Map)}build(s,r,a){const n=r.queryKey,o=r.queryHash??Oc(n,r);let i=this.get(o);return i||(i=new uy({client:s,queryKey:n,queryHash:o,options:s.defaultQueryOptions(r),state:a,defaultOptions:s.getQueryDefaults(n)}),this.add(i)),i}add(s){C(this,ns).has(s.queryHash)||(C(this,ns).set(s.queryHash,s),this.notify({type:"added",query:s}))}remove(s){const r=C(this,ns).get(s.queryHash);r&&(s.destroy(),r===s&&C(this,ns).delete(s.queryHash),this.notify({type:"removed",query:s}))}clear(){et.batch(()=>{this.getAll().forEach(s=>{this.remove(s)})})}get(s){return C(this,ns).get(s)}getAll(){return[...C(this,ns).values()]}find(s){const r={exact:!0,...s};return this.getAll().find(a=>Yd(r,a))}findAll(s={}){const r=this.getAll();return Object.keys(s).length>0?r.filter(a=>Yd(s,a)):r}notify(s){et.batch(()=>{this.listeners.forEach(r=>{r(s)})})}onFocus(){et.batch(()=>{this.getAll().forEach(s=>{s.onFocus()})})}onOnline(){et.batch(()=>{this.getAll().forEach(s=>{s.onOnline()})})}},ns=new WeakMap,Rp),We,Zs,er,ba,ya,tr,va,ja,Tp,yy=(Tp=class{constructor(e={}){le(this,We);le(this,Zs);le(this,er);le(this,ba);le(this,ya);le(this,tr);le(this,va);le(this,ja);Z(this,We,e.queryCache||new by),Z(this,Zs,e.mutationCache||new fy),Z(this,er,e.defaultOptions||{}),Z(this,ba,new Map),Z(this,ya,new Map),Z(this,tr,0)}mount(){io(this,tr)._++,C(this,tr)===1&&(Z(this,va,Lc.subscribe(async e=>{e&&(await this.resumePausedMutations(),C(this,We).onFocus())})),Z(this,ja,Oo.subscribe(async e=>{e&&(await this.resumePausedMutations(),C(this,We).onOnline())})))}unmount(){var e,s;io(this,tr)._--,C(this,tr)===0&&((e=C(this,va))==null||e.call(this),Z(this,va,void 0),(s=C(this,ja))==null||s.call(this),Z(this,ja,void 0))}isFetching(e){return C(this,We).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return C(this,Zs).findAll({...e,status:"pending"}).length}getQueryData(e){var r;const s=this.defaultQueryOptions({queryKey:e});return(r=C(this,We).get(s.queryHash))==null?void 0:r.state.data}ensureQueryData(e){const s=this.defaultQueryOptions(e),r=C(this,We).build(this,s),a=r.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(sr(s.staleTime,r))&&this.prefetchQuery(s),Promise.resolve(a))}getQueriesData(e){return C(this,We).findAll(e).map(({queryKey:s,state:r})=>{const a=r.data;return[s,a]})}setQueryData(e,s,r){const a=this.defaultQueryOptions({queryKey:e}),n=C(this,We).get(a.queryHash),o=n==null?void 0:n.state.data,i=ey(s,o);if(i!==void 0)return C(this,We).build(this,a).setData(i,{...r,manual:!0})}setQueriesData(e,s,r){return et.batch(()=>C(this,We).findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,s,r)]))}getQueryState(e){var r;const s=this.defaultQueryOptions({queryKey:e});return(r=C(this,We).get(s.queryHash))==null?void 0:r.state}removeQueries(e){const s=C(this,We);et.batch(()=>{s.findAll(e).forEach(r=>{s.remove(r)})})}resetQueries(e,s){const r=C(this,We);return et.batch(()=>(r.findAll(e).forEach(a=>{a.reset()}),this.refetchQueries({type:"active",...e},s)))}cancelQueries(e,s={}){const r={revert:!0,...s},a=et.batch(()=>C(this,We).findAll(e).map(n=>n.cancel(r)));return Promise.all(a).then(pt).catch(pt)}invalidateQueries(e,s={}){return et.batch(()=>(C(this,We).findAll(e).forEach(r=>{r.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},s)))}refetchQueries(e,s={}){const r={...s,cancelRefetch:s.cancelRefetch??!0},a=et.batch(()=>C(this,We).findAll(e).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let o=n.fetch(void 0,r);return r.throwOnError||(o=o.catch(pt)),n.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(a).then(pt)}fetchQuery(e){const s=this.defaultQueryOptions(e);s.retry===void 0&&(s.retry=!1);const r=C(this,We).build(this,s);return r.isStaleByTime(sr(s.staleTime,r))?r.fetch(s):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(pt).catch(pt)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(pt).catch(pt)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Oo.isOnline()?C(this,Zs).resumePausedMutations():Promise.resolve()}getQueryCache(){return C(this,We)}getMutationCache(){return C(this,Zs)}getDefaultOptions(){return C(this,er)}setDefaultOptions(e){Z(this,er,e)}setQueryDefaults(e,s){C(this,ba).set(Ir(e),{queryKey:e,defaultOptions:s})}getQueryDefaults(e){const s=[...C(this,ba).values()],r={};return s.forEach(a=>{bn(e,a.queryKey)&&Object.assign(r,a.defaultOptions)}),r}setMutationDefaults(e,s){C(this,ya).set(Ir(e),{mutationKey:e,defaultOptions:s})}getMutationDefaults(e){const s=[...C(this,ya).values()],r={};return s.forEach(a=>{bn(e,a.mutationKey)&&Object.assign(r,a.defaultOptions)}),r}defaultQueryOptions(e){if(e._defaulted)return e;const s={...C(this,er).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return s.queryHash||(s.queryHash=Oc(s.queryKey,s)),s.refetchOnReconnect===void 0&&(s.refetchOnReconnect=s.networkMode!=="always"),s.throwOnError===void 0&&(s.throwOnError=!!s.suspense),!s.networkMode&&s.persister&&(s.networkMode="offlineFirst"),s.queryFn===zc&&(s.enabled=!1),s}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...C(this,er).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){C(this,We).clear(),C(this,Zs).clear()}},We=new WeakMap,Zs=new WeakMap,er=new WeakMap,ba=new WeakMap,ya=new WeakMap,tr=new WeakMap,va=new WeakMap,ja=new WeakMap,Tp),gh=p.createContext(void 0),Da=e=>{const s=p.useContext(gh);if(!s)throw new Error("No QueryClient set, use QueryClientProvider to set one");return s},vy=({client:e,children:s})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),t.jsx(gh.Provider,{value:e,children:s})),bh=p.createContext(!1),jy=()=>p.useContext(bh);bh.Provider;function wy(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ny=p.createContext(wy()),ky=()=>p.useContext(Ny),_y=(e,s,r)=>{const a=r!=null&&r.state.error&&typeof e.throwOnError=="function"?Bc(e.throwOnError,[r.state.error,r]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||a)&&(s.isReset()||(e.retryOnMount=!1))},Sy=e=>{p.useEffect(()=>{e.clearReset()},[e])},Cy=({result:e,errorResetBoundary:s,throwOnError:r,query:a,suspense:n})=>e.isError&&!s.isReset()&&!e.isFetching&&a&&(n&&e.data===void 0||Bc(r,[e.error,a])),Ey=e=>{if(e.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...n)=>r(a(...n)):r(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Ry=(e,s)=>e.isLoading&&e.isFetching&&!s,Ty=(e,s)=>(e==null?void 0:e.suspense)&&s.isPending,au=(e,s,r)=>s.fetchOptimistic(e).catch(()=>{r.clearReset()});function My(e,s,r){var x,g,f,y;const a=jy(),n=ky(),o=Da(),i=o.defaultQueryOptions(e);(g=(x=o.getDefaultOptions().queries)==null?void 0:x._experimental_beforeQuery)==null||g.call(x,i);const l=o.getQueryCache().get(i.queryHash),c=e.subscribed!==!1;i._optimisticResults=a?"isRestoring":c?"optimistic":void 0,Ey(i),_y(i,n,l),Sy(n);const d=!o.getQueryCache().get(i.queryHash),[m]=p.useState(()=>new s(o,i)),u=m.getOptimisticResult(i),h=!a&&c;if(p.useSyncExternalStore(p.useCallback(b=>{const v=h?m.subscribe(et.batchCalls(b)):pt;return m.updateResult(),v},[m,h]),()=>m.getCurrentResult(),()=>m.getCurrentResult()),p.useEffect(()=>{m.setOptions(i)},[i,m]),Ty(i,u))throw au(i,m,n);if(Cy({result:u,errorResetBoundary:n,throwOnError:i.throwOnError,query:l,suspense:i.suspense}))throw u.error;if((y=(f=o.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||y.call(f,i,u),i.experimental_prefetchInRender&&!yn.isServer()&&Ry(u,a)){const b=d?au(i,m,n):l==null?void 0:l.promise;b==null||b.catch(pt).finally(()=>{m.updateResult()})}return i.notifyOnChangeProps?u:m.trackResult(u)}function ui(e,s){return My(e,my)}function mi(e,s){const r=Da(),[a]=p.useState(()=>new gy(r,e));p.useEffect(()=>{a.setOptions(e)},[a,e]);const n=p.useSyncExternalStore(p.useCallback(i=>a.subscribe(et.batchCalls(i)),[a]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),o=p.useCallback((i,l)=>{a.mutate(i,l).catch(pt)},[a]);if(n.error&&Bc(a.options.throwOnError,[n.error]))throw n.error;return{...n,mutate:o,mutateAsync:n.mutate}}const Py="modulepreload",Iy=function(e){return"/"+e},nu={},Ot=function(s,r,a){let n=Promise.resolve();if(r&&r.length>0){let i=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=i(r.map(d=>{if(d=Iy(d),d in nu)return;nu[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Py,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((x,g)=>{h.addEventListener("load",x),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return n.then(i=>{for(const l of i||[])l.status==="rejected"&&o(l.reason);return s().catch(o)})};/** +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TemplatesGalleryModal-CbchbwFl.js","assets/vendor-flow-bDma3vSM.js","assets/vendor-utils-_6D5wMFs.js","assets/vendor-charts-CwfdE1jD.js","assets/mermaid.core-BRmiRRt4.js","assets/InferencePage-D5u_4kVQ.js","assets/EDAPage-D-AvDDu5.js","assets/FormField-BxGvOnTr.js","assets/vendor-plotly-Bx-86y5L.js","assets/EDAPage-Dgihpmma.css","assets/DataDriftPage-BjX1Ahxl.js","assets/driftThresholds-BnFBRCeO.js","assets/ModelRegistry-B8Vj7yFC.js","assets/DeploymentsPage-BeXYd7e4.js","assets/SlowNodesPage-CVIoKIrD.js","assets/AuditLogPage-BjT9Erh4.js","assets/BaseModelParamsEditor-CyS6uUs-.js","assets/GeoDistanceSettings-B1xj7Hl4.js"])))=>i.map(i=>d[i]); +var P0=Object.defineProperty;var Gd=e=>{throw TypeError(e)};var I0=(e,s,r)=>s in e?P0(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var It=(e,s,r)=>I0(e,typeof s!="symbol"?s+"":s,r),Hi=(e,s,r)=>s.has(e)||Gd("Cannot "+r);var C=(e,s,r)=>(Hi(e,s,"read from private field"),r?r.call(e):s.get(e)),le=(e,s,r)=>s.has(e)?Gd("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,r),Z=(e,s,r,a)=>(Hi(e,s,"write to private field"),a?a.call(e,r):s.set(e,r),r),he=(e,s,r)=>(Hi(e,s,"access private method"),r);var io=(e,s,r,a)=>({set _(n){Z(e,s,n,r)},get _(){return C(e,s,a)}});import{j as t,c as Mp,b as Wi,d as A0,e as $0,f as Pp,g as $n,H as _l,P as is,h as F0,k as D0,l as Ip,m as L0,E as O0,R as Ap,i as $p,B as Fp,C as Dp,n as Dt,M as z0}from"./vendor-flow-bDma3vSM.js";import{g as Lp,a as p,b as ne,al as Op,aH as B0,X as Se,a1 as Fn,f as Lt,j as Ce,ac as Ke,aI as _c,aJ as V0,aw as zp,ad as rt,ab as Dn,T as Sc,aB as ps,af as Ct,A as U0,d as Pa,aK as ai,i as H0,E as W0,aL as G0,aM as q0,O as fe,c as hs,aN as K0,C as _t,as as Sl,N as dr,e as qt,J as Bp,ag as Me,Y as Ln,a6 as Vp,a7 as Up,y as Ps,m as xs,aO as Cc,L as ni,U as J0,$ as Y0,p as Ia,aP as Q0,ah as X0,n as Z0,w as _e,l as st,aQ as Cl,aR as oi,aS as xn,aT as eb,a4 as Aa,aU as Hp,z as Ec,K as ht,ao as El,S as ur,a3 as On,aE as Wp,_ as Pe,au as tb,av as sb,R as Gp,aG as Rc,aV as fn,aW as rb,aX as Tc,aY as Mc,I as ar,aZ as ab,a_ as $a,aF as qp,a$ as nb,aq as gn,b0 as Kp,b1 as Jp,b2 as ob,b3 as ib,b4 as lb,b5 as Rl,b6 as cb,W as ii,D as li,ai as Pc,b7 as Yp,ax as Qp,v as ss,aC as Ic,b8 as db,a2 as ub,u as mb,b9 as pb,ba as hb,bb as xb,bc as Xp,bd as Zp,be as fb,bf as gb,bg as bb,bh as yb,bi as vb,Z as Tl,bj as Ac,bk as $c,am as eh,bl as ci,bm as jb,bn as wb,bo as Nb,s as di,bp as th,bq as kb,br as _b,aa as sh,bs as Sb,bt as Cb,h as Fc,bu as Eb,bv as Rb,bw as Tb,bx as Mb,H as rh,by as ah,bz as Pb,bA as nh,bB as Dc,bC as Ib,bD as qd,bE as Ab,bF as $b,bG as Fb,bH as Db}from"./vendor-utils-_6D5wMFs.js";import{aY as Lb,u as Ob,r as zn,R as Ie,B as Xt,C as Be,X as De,Y as Le,T as Ae,h as lt,aj as zb,ak as Bb,j as wa,ah as Or,aZ as Vb,ag as Ub,ai as mt,av as Hb,a_ as xr,a$ as Wb,as as ct,au as fr,at as Zr,b0 as Gi,b1 as Kd}from"./vendor-charts-CwfdE1jD.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&a(i)}).observe(document,{childList:!0,subtree:!0});function r(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(n){if(n.ep)return;n.ep=!0;const o=r(n);fetch(n.href,o)}})();var lo={},Jd;function Gb(){if(Jd)return lo;Jd=1;var e=Lb();return lo.createRoot=e.createRoot,lo.hydrateRoot=e.hydrateRoot,lo}var qb=Gb();const Kb=Lp(qb);var Fa=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},vr,qs,ca,vp,Jb=(vp=class extends Fa{constructor(){super();le(this,vr);le(this,qs);le(this,ca);Z(this,ca,s=>{if(typeof window<"u"&&window.addEventListener){const r=()=>s();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){C(this,qs)||this.setEventListener(C(this,ca))}onUnsubscribe(){var s;this.hasListeners()||((s=C(this,qs))==null||s.call(this),Z(this,qs,void 0))}setEventListener(s){var r;Z(this,ca,s),(r=C(this,qs))==null||r.call(this),Z(this,qs,s(a=>{typeof a=="boolean"?this.setFocused(a):this.onFocus()}))}setFocused(s){C(this,vr)!==s&&(Z(this,vr,s),this.onFocus())}onFocus(){const s=this.isFocused();this.listeners.forEach(r=>{r(s)})}isFocused(){var s;return typeof C(this,vr)=="boolean"?C(this,vr):((s=globalThis.document)==null?void 0:s.visibilityState)!=="hidden"}},vr=new WeakMap,qs=new WeakMap,ca=new WeakMap,vp),Lc=new Jb,Yb={setTimeout:(e,s)=>setTimeout(e,s),clearTimeout:e=>clearTimeout(e),setInterval:(e,s)=>setInterval(e,s),clearInterval:e=>clearInterval(e)},Ks,kc,jp,Qb=(jp=class{constructor(){le(this,Ks,Yb);le(this,kc,!1)}setTimeoutProvider(e){Z(this,Ks,e)}setTimeout(e,s){return C(this,Ks).setTimeout(e,s)}clearTimeout(e){C(this,Ks).clearTimeout(e)}setInterval(e,s){return C(this,Ks).setInterval(e,s)}clearInterval(e){C(this,Ks).clearInterval(e)}},Ks=new WeakMap,kc=new WeakMap,jp),br=new Qb;function Xb(e){setTimeout(e,0)}var Zb=typeof window>"u"||"Deno"in globalThis;function pt(){}function ey(e,s){return typeof e=="function"?e(s):e}function Ml(e){return typeof e=="number"&&e>=0&&e!==1/0}function oh(e,s){return Math.max(e+(s||0)-Date.now(),0)}function sr(e,s){return typeof e=="function"?e(s):e}function wt(e,s){return typeof e=="function"?e(s):e}function Yd(e,s){const{type:r="all",exact:a,fetchStatus:n,predicate:o,queryKey:i,stale:l}=e;if(i){if(a){if(s.queryHash!==Oc(i,s.options))return!1}else if(!bn(s.queryKey,i))return!1}if(r!=="all"){const c=s.isActive();if(r==="active"&&!c||r==="inactive"&&c)return!1}return!(typeof l=="boolean"&&s.isStale()!==l||n&&n!==s.state.fetchStatus||o&&!o(s))}function Qd(e,s){const{exact:r,status:a,predicate:n,mutationKey:o}=e;if(o){if(!s.options.mutationKey)return!1;if(r){if(Ir(s.options.mutationKey)!==Ir(o))return!1}else if(!bn(s.options.mutationKey,o))return!1}return!(a&&s.state.status!==a||n&&!n(s))}function Oc(e,s){return((s==null?void 0:s.queryKeyHashFn)||Ir)(e)}function Ir(e){return JSON.stringify(e,(s,r)=>Pl(r)?Object.keys(r).sort().reduce((a,n)=>(a[n]=r[n],a),{}):r)}function bn(e,s){return e===s?!0:typeof e!=typeof s?!1:e&&s&&typeof e=="object"&&typeof s=="object"?Object.keys(s).every(r=>bn(e[r],s[r])):!1}var ty=Object.prototype.hasOwnProperty;function ih(e,s,r=0){if(e===s)return e;if(r>500)return s;const a=Xd(e)&&Xd(s);if(!a&&!(Pl(e)&&Pl(s)))return s;const o=(a?e:Object.keys(e)).length,i=a?s:Object.keys(s),l=i.length,c=a?new Array(l):{};let d=0;for(let m=0;m{br.setTimeout(s,e)})}function Il(e,s,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,s):r.structuralSharing!==!1?ih(e,s):s}function ry(e,s,r=0){const a=[...e,s];return r&&a.length>r?a.slice(1):a}function ay(e,s,r=0){const a=[s,...e];return r&&a.length>r?a.slice(0,-1):a}var zc=Symbol();function lh(e,s){return!e.queryFn&&(s!=null&&s.initialPromise)?()=>s.initialPromise:!e.queryFn||e.queryFn===zc?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Bc(e,s){return typeof e=="function"?e(...s):!!e}function ny(e,s,r){let a=!1,n;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(n??(n=s()),a||(a=!0,n.aborted?r():n.addEventListener("abort",r,{once:!0})),n)}),e}var yn=(()=>{let e=()=>Zb;return{isServer(){return e()},setIsServer(s){e=s}}})();function Al(){let e,s;const r=new Promise((n,o)=>{e=n,s=o});r.status="pending",r.catch(()=>{});function a(n){Object.assign(r,n),delete r.resolve,delete r.reject}return r.resolve=n=>{a({status:"fulfilled",value:n}),e(n)},r.reject=n=>{a({status:"rejected",reason:n}),s(n)},r}var oy=Xb;function iy(){let e=[],s=0,r=l=>{l()},a=l=>{l()},n=oy;const o=l=>{s?e.push(l):n(()=>{r(l)})},i=()=>{const l=e;e=[],l.length&&n(()=>{a(()=>{l.forEach(c=>{r(c)})})})};return{batch:l=>{let c;s++;try{c=l()}finally{s--,s||i()}return c},batchCalls:l=>(...c)=>{o(()=>{l(...c)})},schedule:o,setNotifyFunction:l=>{r=l},setBatchNotifyFunction:l=>{a=l},setScheduler:l=>{n=l}}}var et=iy(),da,Js,ua,wp,ly=(wp=class extends Fa{constructor(){super();le(this,da,!0);le(this,Js);le(this,ua);Z(this,ua,s=>{if(typeof window<"u"&&window.addEventListener){const r=()=>s(!0),a=()=>s(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",a,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",a)}}})}onSubscribe(){C(this,Js)||this.setEventListener(C(this,ua))}onUnsubscribe(){var s;this.hasListeners()||((s=C(this,Js))==null||s.call(this),Z(this,Js,void 0))}setEventListener(s){var r;Z(this,ua,s),(r=C(this,Js))==null||r.call(this),Z(this,Js,s(this.setOnline.bind(this)))}setOnline(s){C(this,da)!==s&&(Z(this,da,s),this.listeners.forEach(a=>{a(s)}))}isOnline(){return C(this,da)}},da=new WeakMap,Js=new WeakMap,ua=new WeakMap,wp),Oo=new ly;function cy(e){return Math.min(1e3*2**e,3e4)}function ch(e){return(e??"online")==="online"?Oo.isOnline():!0}var $l=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function dh(e){let s=!1,r=0,a;const n=Al(),o=()=>n.status!=="pending",i=f=>{var y;if(!o()){const b=new $l(f);h(b),(y=e.onCancel)==null||y.call(e,b)}},l=()=>{s=!0},c=()=>{s=!1},d=()=>Lc.isFocused()&&(e.networkMode==="always"||Oo.isOnline())&&e.canRun(),m=()=>ch(e.networkMode)&&e.canRun(),u=f=>{o()||(a==null||a(),n.resolve(f))},h=f=>{o()||(a==null||a(),n.reject(f))},x=()=>new Promise(f=>{var y;a=b=>{(o()||d())&&f(b)},(y=e.onPause)==null||y.call(e)}).then(()=>{var f;a=void 0,o()||(f=e.onContinue)==null||f.call(e)}),g=()=>{if(o())return;let f;const y=r===0?e.initialPromise:void 0;try{f=y??e.fn()}catch(b){f=Promise.reject(b)}Promise.resolve(f).then(u).catch(b=>{var k;if(o())return;const v=e.retry??(yn.isServer()?0:3),j=e.retryDelay??cy,w=typeof j=="function"?j(r,b):j,N=v===!0||typeof v=="number"&&rd()?void 0:x()).then(()=>{s?h(b):g()})})};return{promise:n,status:()=>n.status,cancel:i,continue:()=>(a==null||a(),n),cancelRetry:l,continueRetry:c,canStart:m,start:()=>(m()?g():x().then(g),n)}}var jr,Np,uh=(Np=class{constructor(){le(this,jr)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ml(this.gcTime)&&Z(this,jr,br.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(yn.isServer()?1/0:300*1e3))}clearGcTimeout(){C(this,jr)!==void 0&&(br.clearTimeout(C(this,jr)),Z(this,jr,void 0))}},jr=new WeakMap,Np);function dy(e){return{onFetch:(s,r)=>{var m,u,h,x,g;const a=s.options,n=(h=(u=(m=s.fetchOptions)==null?void 0:m.meta)==null?void 0:u.fetchMore)==null?void 0:h.direction,o=((x=s.state.data)==null?void 0:x.pages)||[],i=((g=s.state.data)==null?void 0:g.pageParams)||[];let l={pages:[],pageParams:[]},c=0;const d=async()=>{let f=!1;const y=j=>{ny(j,()=>s.signal,()=>f=!0)},b=lh(s.options,s.fetchOptions),v=async(j,w,N)=>{if(f)return Promise.reject(s.signal.reason);if(w==null&&j.pages.length)return Promise.resolve(j);const _=(()=>{const M={client:s.client,queryKey:s.queryKey,pageParam:w,direction:N?"backward":"forward",meta:s.options.meta};return y(M),M})(),R=await b(_),{maxPages:P}=s.options,E=N?ay:ry;return{pages:E(j.pages,R,P),pageParams:E(j.pageParams,w,P)}};if(n&&o.length){const j=n==="backward",w=j?mh:Fl,N={pages:o,pageParams:i},k=w(a,N);l=await v(N,k,j)}else{const j=e??o.length;do{const w=c===0?i[0]??a.initialPageParam:Fl(a,l);if(c>0&&w==null)break;l=await v(l,w),c++}while(c{var f,y;return(y=(f=s.options).persister)==null?void 0:y.call(f,d,{client:s.client,queryKey:s.queryKey,meta:s.options.meta,signal:s.signal},r)}:s.fetchFn=d}}}function Fl(e,{pages:s,pageParams:r}){const a=s.length-1;return s.length>0?e.getNextPageParam(s[a],s,r[a],r):void 0}function mh(e,{pages:s,pageParams:r}){var a;return s.length>0?(a=e.getPreviousPageParam)==null?void 0:a.call(e,s[0],s,r[0],r):void 0}function W6(e,s){return s?Fl(e,s)!=null:!1}function G6(e,s){return!s||!e.getPreviousPageParam?!1:mh(e,s)!=null}var ma,wr,pa,$t,Nr,tt,Tn,kr,jt,ph,Ns,kp,uy=(kp=class extends uh{constructor(s){super();le(this,jt);le(this,ma);le(this,wr);le(this,pa);le(this,$t);le(this,Nr);le(this,tt);le(this,Tn);le(this,kr);Z(this,kr,!1),Z(this,Tn,s.defaultOptions),this.setOptions(s.options),this.observers=[],Z(this,Nr,s.client),Z(this,$t,C(this,Nr).getQueryCache()),this.queryKey=s.queryKey,this.queryHash=s.queryHash,Z(this,wr,tu(this.options)),this.state=s.state??C(this,wr),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return C(this,ma)}get promise(){var s;return(s=C(this,tt))==null?void 0:s.promise}setOptions(s){if(this.options={...C(this,Tn),...s},s!=null&&s._type&&Z(this,ma,s._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=tu(this.options);r.data!==void 0&&(this.setState(eu(r.data,r.dataUpdatedAt)),Z(this,wr,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&C(this,$t).remove(this)}setData(s,r){const a=Il(this.state.data,s,this.options);return he(this,jt,Ns).call(this,{data:a,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),a}setState(s){he(this,jt,Ns).call(this,{type:"setState",state:s})}cancel(s){var a,n;const r=(a=C(this,tt))==null?void 0:a.promise;return(n=C(this,tt))==null||n.cancel(s),r?r.then(pt).catch(pt):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return C(this,wr)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(s=>wt(s.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===zc||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(s=>sr(s.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(s=>s.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(s=0){return this.state.data===void 0?!0:s==="static"?!1:this.state.isInvalidated?!0:!oh(this.state.dataUpdatedAt,s)}onFocus(){var r;const s=this.observers.find(a=>a.shouldFetchOnWindowFocus());s==null||s.refetch({cancelRefetch:!1}),(r=C(this,tt))==null||r.continue()}onOnline(){var r;const s=this.observers.find(a=>a.shouldFetchOnReconnect());s==null||s.refetch({cancelRefetch:!1}),(r=C(this,tt))==null||r.continue()}addObserver(s){this.observers.includes(s)||(this.observers.push(s),this.clearGcTimeout(),C(this,$t).notify({type:"observerAdded",query:this,observer:s}))}removeObserver(s){this.observers.includes(s)&&(this.observers=this.observers.filter(r=>r!==s),this.observers.length||(C(this,tt)&&(C(this,kr)||he(this,jt,ph).call(this)?C(this,tt).cancel({revert:!0}):C(this,tt).cancelRetry()),this.scheduleGc()),C(this,$t).notify({type:"observerRemoved",query:this,observer:s}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||he(this,jt,Ns).call(this,{type:"invalidate"})}async fetch(s,r){var d,m,u,h,x,g,f,y,b,v,j;if(this.state.fetchStatus!=="idle"&&((d=C(this,tt))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(C(this,tt))return C(this,tt).continueRetry(),C(this,tt).promise}if(s&&this.setOptions(s),!this.options.queryFn){const w=this.observers.find(N=>N.options.queryFn);w&&this.setOptions(w.options)}const a=new AbortController,n=w=>{Object.defineProperty(w,"signal",{enumerable:!0,get:()=>(Z(this,kr,!0),a.signal)})},o=()=>{const w=lh(this.options,r),k=(()=>{const _={client:C(this,Nr),queryKey:this.queryKey,meta:this.meta};return n(_),_})();return Z(this,kr,!1),this.options.persister?this.options.persister(w,k,this):w(k)},l=(()=>{const w={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:C(this,Nr),state:this.state,fetchFn:o};return n(w),w})(),c=C(this,ma)==="infinite"?dy(this.options.pages):this.options.behavior;c==null||c.onFetch(l,this),Z(this,pa,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&he(this,jt,Ns).call(this,{type:"fetch",meta:(u=l.fetchOptions)==null?void 0:u.meta}),Z(this,tt,dh({initialPromise:r==null?void 0:r.initialPromise,fn:l.fetchFn,onCancel:w=>{w instanceof $l&&w.revert&&this.setState({...C(this,pa),fetchStatus:"idle"}),a.abort()},onFail:(w,N)=>{he(this,jt,Ns).call(this,{type:"failed",failureCount:w,error:N})},onPause:()=>{he(this,jt,Ns).call(this,{type:"pause"})},onContinue:()=>{he(this,jt,Ns).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode,canRun:()=>!0}));try{const w=await C(this,tt).start();if(w===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(w),(x=(h=C(this,$t).config).onSuccess)==null||x.call(h,w,this),(f=(g=C(this,$t).config).onSettled)==null||f.call(g,w,this.state.error,this),w}catch(w){if(w instanceof $l){if(w.silent)return C(this,tt).promise;if(w.revert){if(this.state.data===void 0)throw w;return this.state.data}}throw he(this,jt,Ns).call(this,{type:"error",error:w}),(b=(y=C(this,$t).config).onError)==null||b.call(y,w,this),(j=(v=C(this,$t).config).onSettled)==null||j.call(v,this.state.data,w,this),w}finally{this.scheduleGc()}}},ma=new WeakMap,wr=new WeakMap,pa=new WeakMap,$t=new WeakMap,Nr=new WeakMap,tt=new WeakMap,Tn=new WeakMap,kr=new WeakMap,jt=new WeakSet,ph=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ns=function(s){const r=a=>{switch(s.type){case"failed":return{...a,fetchFailureCount:s.failureCount,fetchFailureReason:s.error};case"pause":return{...a,fetchStatus:"paused"};case"continue":return{...a,fetchStatus:"fetching"};case"fetch":return{...a,...hh(a.data,this.options),fetchMeta:s.meta??null};case"success":const n={...a,...eu(s.data,s.dataUpdatedAt),dataUpdateCount:a.dataUpdateCount+1,...!s.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Z(this,pa,s.manual?n:void 0),n;case"error":const o=s.error;return{...a,error:o,errorUpdateCount:a.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:a.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...a,isInvalidated:!0};case"setState":return{...a,...s.state}}};this.state=r(this.state),et.batch(()=>{this.observers.forEach(a=>{a.onQueryUpdate()}),C(this,$t).notify({query:this,type:"updated",action:s})})},kp);function hh(e,s){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ch(s.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function eu(e,s){return{data:e,dataUpdatedAt:s??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tu(e){const s=typeof e.initialData=="function"?e.initialData():e.initialData,r=s!==void 0,a=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:s,dataUpdateCount:0,dataUpdatedAt:r?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var ft,ye,Mn,dt,_r,ha,ks,Ys,Pn,xa,fa,Sr,Cr,Qs,ga,ke,dn,Dl,Ll,Ol,zl,Bl,Vl,Ul,xh,_p,my=(_p=class extends Fa{constructor(s,r){super();le(this,ke);le(this,ft);le(this,ye);le(this,Mn);le(this,dt);le(this,_r);le(this,ha);le(this,ks);le(this,Ys);le(this,Pn);le(this,xa);le(this,fa);le(this,Sr);le(this,Cr);le(this,Qs);le(this,ga,new Set);this.options=r,Z(this,ft,s),Z(this,Ys,null),Z(this,ks,Al()),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(C(this,ye).addObserver(this),su(C(this,ye),this.options)?he(this,ke,dn).call(this):this.updateResult(),he(this,ke,zl).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Hl(C(this,ye),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Hl(C(this,ye),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,he(this,ke,Bl).call(this),he(this,ke,Vl).call(this),C(this,ye).removeObserver(this)}setOptions(s){const r=this.options,a=C(this,ye);if(this.options=C(this,ft).defaultQueryOptions(s),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof wt(this.options.enabled,C(this,ye))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");he(this,ke,Ul).call(this),C(this,ye).setOptions(this.options),r._defaulted&&!Lo(this.options,r)&&C(this,ft).getQueryCache().notify({type:"observerOptionsUpdated",query:C(this,ye),observer:this});const n=this.hasListeners();n&&ru(C(this,ye),a,this.options,r)&&he(this,ke,dn).call(this),this.updateResult(),n&&(C(this,ye)!==a||wt(this.options.enabled,C(this,ye))!==wt(r.enabled,C(this,ye))||sr(this.options.staleTime,C(this,ye))!==sr(r.staleTime,C(this,ye)))&&he(this,ke,Dl).call(this);const o=he(this,ke,Ll).call(this);n&&(C(this,ye)!==a||wt(this.options.enabled,C(this,ye))!==wt(r.enabled,C(this,ye))||o!==C(this,Qs))&&he(this,ke,Ol).call(this,o)}getOptimisticResult(s){const r=C(this,ft).getQueryCache().build(C(this,ft),s),a=this.createResult(r,s);return hy(this,a)&&(Z(this,dt,a),Z(this,ha,this.options),Z(this,_r,C(this,ye).state)),a}getCurrentResult(){return C(this,dt)}trackResult(s,r){return new Proxy(s,{get:(a,n)=>(this.trackProp(n),r==null||r(n),n==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&C(this,ks).status==="pending"&&C(this,ks).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(a,n))})}trackProp(s){C(this,ga).add(s)}getCurrentQuery(){return C(this,ye)}refetch({...s}={}){return this.fetch({...s})}fetchOptimistic(s){const r=C(this,ft).defaultQueryOptions(s),a=C(this,ft).getQueryCache().build(C(this,ft),r);return a.fetch().then(()=>this.createResult(a,r))}fetch(s){return he(this,ke,dn).call(this,{...s,cancelRefetch:s.cancelRefetch??!0}).then(()=>(this.updateResult(),C(this,dt)))}createResult(s,r){var P;const a=C(this,ye),n=this.options,o=C(this,dt),i=C(this,_r),l=C(this,ha),d=s!==a?s.state:C(this,Mn),{state:m}=s;let u={...m},h=!1,x;if(r._optimisticResults){const E=this.hasListeners(),M=!E&&su(s,r),S=E&&ru(s,a,r,n);(M||S)&&(u={...u,...hh(m.data,s.options)}),r._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:g,errorUpdatedAt:f,status:y}=u;x=u.data;let b=!1;if(r.placeholderData!==void 0&&x===void 0&&y==="pending"){let E;o!=null&&o.isPlaceholderData&&r.placeholderData===(l==null?void 0:l.placeholderData)?(E=o.data,b=!0):E=typeof r.placeholderData=="function"?r.placeholderData((P=C(this,fa))==null?void 0:P.state.data,C(this,fa)):r.placeholderData,E!==void 0&&(y="success",x=Il(o==null?void 0:o.data,E,r),h=!0)}if(r.select&&x!==void 0&&!b)if(o&&x===(i==null?void 0:i.data)&&r.select===C(this,Pn))x=C(this,xa);else try{Z(this,Pn,r.select),x=r.select(x),x=Il(o==null?void 0:o.data,x,r),Z(this,xa,x),Z(this,Ys,null)}catch(E){Z(this,Ys,E)}C(this,Ys)&&(g=C(this,Ys),x=C(this,xa),f=Date.now(),y="error");const v=u.fetchStatus==="fetching",j=y==="pending",w=y==="error",N=j&&v,k=x!==void 0,R={status:y,fetchStatus:u.fetchStatus,isPending:j,isSuccess:y==="success",isError:w,isInitialLoading:N,isLoading:N,data:x,dataUpdatedAt:u.dataUpdatedAt,error:g,errorUpdatedAt:f,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:s.isFetched(),isFetchedAfterMount:u.dataUpdateCount>d.dataUpdateCount||u.errorUpdateCount>d.errorUpdateCount,isFetching:v,isRefetching:v&&!j,isLoadingError:w&&!k,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:w&&k,isStale:Vc(s,r),refetch:this.refetch,promise:C(this,ks),isEnabled:wt(r.enabled,s)!==!1};if(this.options.experimental_prefetchInRender){const E=R.data!==void 0,M=R.status==="error"&&!E,S=A=>{M?A.reject(R.error):E&&A.resolve(R.data)},T=()=>{const A=Z(this,ks,R.promise=Al());S(A)},I=C(this,ks);switch(I.status){case"pending":s.queryHash===a.queryHash&&S(I);break;case"fulfilled":(M||R.data!==I.value)&&T();break;case"rejected":(!M||R.error!==I.reason)&&T();break}}return R}updateResult(){const s=C(this,dt),r=this.createResult(C(this,ye),this.options);if(Z(this,_r,C(this,ye).state),Z(this,ha,this.options),C(this,_r).data!==void 0&&Z(this,fa,C(this,ye)),Lo(r,s))return;Z(this,dt,r);const a=()=>{if(!s)return!0;const{notifyOnChangeProps:n}=this.options,o=typeof n=="function"?n():n;if(o==="all"||!o&&!C(this,ga).size)return!0;const i=new Set(o??C(this,ga));return this.options.throwOnError&&i.add("error"),Object.keys(C(this,dt)).some(l=>{const c=l;return C(this,dt)[c]!==s[c]&&i.has(c)})};he(this,ke,xh).call(this,{listeners:a()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&he(this,ke,zl).call(this)}},ft=new WeakMap,ye=new WeakMap,Mn=new WeakMap,dt=new WeakMap,_r=new WeakMap,ha=new WeakMap,ks=new WeakMap,Ys=new WeakMap,Pn=new WeakMap,xa=new WeakMap,fa=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,Qs=new WeakMap,ga=new WeakMap,ke=new WeakSet,dn=function(s){he(this,ke,Ul).call(this);let r=C(this,ye).fetch(this.options,s);return s!=null&&s.throwOnError||(r=r.catch(pt)),r},Dl=function(){he(this,ke,Bl).call(this);const s=sr(this.options.staleTime,C(this,ye));if(yn.isServer()||C(this,dt).isStale||!Ml(s))return;const a=oh(C(this,dt).dataUpdatedAt,s)+1;Z(this,Sr,br.setTimeout(()=>{C(this,dt).isStale||this.updateResult()},a))},Ll=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(C(this,ye)):this.options.refetchInterval)??!1},Ol=function(s){he(this,ke,Vl).call(this),Z(this,Qs,s),!(yn.isServer()||wt(this.options.enabled,C(this,ye))===!1||!Ml(C(this,Qs))||C(this,Qs)===0)&&Z(this,Cr,br.setInterval(()=>{(this.options.refetchIntervalInBackground||Lc.isFocused())&&he(this,ke,dn).call(this)},C(this,Qs)))},zl=function(){he(this,ke,Dl).call(this),he(this,ke,Ol).call(this,he(this,ke,Ll).call(this))},Bl=function(){C(this,Sr)!==void 0&&(br.clearTimeout(C(this,Sr)),Z(this,Sr,void 0))},Vl=function(){C(this,Cr)!==void 0&&(br.clearInterval(C(this,Cr)),Z(this,Cr,void 0))},Ul=function(){const s=C(this,ft).getQueryCache().build(C(this,ft),this.options);if(s===C(this,ye))return;const r=C(this,ye);Z(this,ye,s),Z(this,Mn,s.state),this.hasListeners()&&(r==null||r.removeObserver(this),s.addObserver(this))},xh=function(s){et.batch(()=>{s.listeners&&this.listeners.forEach(r=>{r(C(this,dt))}),C(this,ft).getQueryCache().notify({query:C(this,ye),type:"observerResultsUpdated"})})},_p);function py(e,s){return wt(s.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&wt(s.retryOnMount,e)===!1)}function su(e,s){return py(e,s)||e.state.data!==void 0&&Hl(e,s,s.refetchOnMount)}function Hl(e,s,r){if(wt(s.enabled,e)!==!1&&sr(s.staleTime,e)!=="static"){const a=typeof r=="function"?r(e):r;return a==="always"||a!==!1&&Vc(e,s)}return!1}function ru(e,s,r,a){return(e!==s||wt(a.enabled,e)===!1)&&(!r.suspense||e.state.status!=="error")&&Vc(e,r)}function Vc(e,s){return wt(s.enabled,e)!==!1&&e.isStaleByTime(sr(s.staleTime,e))}function hy(e,s){return!Lo(e.getCurrentResult(),s)}var In,rs,ot,Er,as,Hs,Sp,xy=(Sp=class extends uh{constructor(s){super();le(this,as);le(this,In);le(this,rs);le(this,ot);le(this,Er);Z(this,In,s.client),this.mutationId=s.mutationId,Z(this,ot,s.mutationCache),Z(this,rs,[]),this.state=s.state||fh(),this.setOptions(s.options),this.scheduleGc()}setOptions(s){this.options=s,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(s){C(this,rs).includes(s)||(C(this,rs).push(s),this.clearGcTimeout(),C(this,ot).notify({type:"observerAdded",mutation:this,observer:s}))}removeObserver(s){Z(this,rs,C(this,rs).filter(r=>r!==s)),this.scheduleGc(),C(this,ot).notify({type:"observerRemoved",mutation:this,observer:s})}optionalRemove(){C(this,rs).length||(this.state.status==="pending"?this.scheduleGc():C(this,ot).remove(this))}continue(){var s;return((s=C(this,Er))==null?void 0:s.continue())??this.execute(this.state.variables)}async execute(s){var i,l,c,d,m,u,h,x,g,f,y,b,v,j,w,N,k,_;const r=()=>{he(this,as,Hs).call(this,{type:"continue"})},a={client:C(this,In),meta:this.options.meta,mutationKey:this.options.mutationKey};Z(this,Er,dh({fn:()=>this.options.mutationFn?this.options.mutationFn(s,a):Promise.reject(new Error("No mutationFn found")),onFail:(R,P)=>{he(this,as,Hs).call(this,{type:"failed",failureCount:R,error:P})},onPause:()=>{he(this,as,Hs).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>C(this,ot).canRun(this)}));const n=this.state.status==="pending",o=!C(this,Er).canStart();try{if(n)r();else{he(this,as,Hs).call(this,{type:"pending",variables:s,isPaused:o}),C(this,ot).config.onMutate&&await C(this,ot).config.onMutate(s,this,a);const P=await((l=(i=this.options).onMutate)==null?void 0:l.call(i,s,a));P!==this.state.context&&he(this,as,Hs).call(this,{type:"pending",context:P,variables:s,isPaused:o})}const R=await C(this,Er).start();return await((d=(c=C(this,ot).config).onSuccess)==null?void 0:d.call(c,R,s,this.state.context,this,a)),await((u=(m=this.options).onSuccess)==null?void 0:u.call(m,R,s,this.state.context,a)),await((x=(h=C(this,ot).config).onSettled)==null?void 0:x.call(h,R,null,this.state.variables,this.state.context,this,a)),await((f=(g=this.options).onSettled)==null?void 0:f.call(g,R,null,s,this.state.context,a)),he(this,as,Hs).call(this,{type:"success",data:R}),R}catch(R){try{await((b=(y=C(this,ot).config).onError)==null?void 0:b.call(y,R,s,this.state.context,this,a))}catch(P){Promise.reject(P)}try{await((j=(v=this.options).onError)==null?void 0:j.call(v,R,s,this.state.context,a))}catch(P){Promise.reject(P)}try{await((N=(w=C(this,ot).config).onSettled)==null?void 0:N.call(w,void 0,R,this.state.variables,this.state.context,this,a))}catch(P){Promise.reject(P)}try{await((_=(k=this.options).onSettled)==null?void 0:_.call(k,void 0,R,s,this.state.context,a))}catch(P){Promise.reject(P)}throw he(this,as,Hs).call(this,{type:"error",error:R}),R}finally{C(this,ot).runNext(this)}}},In=new WeakMap,rs=new WeakMap,ot=new WeakMap,Er=new WeakMap,as=new WeakSet,Hs=function(s){const r=a=>{switch(s.type){case"failed":return{...a,failureCount:s.failureCount,failureReason:s.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:s.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:s.isPaused,status:"pending",variables:s.variables,submittedAt:Date.now()};case"success":return{...a,data:s.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:s.error,failureCount:a.failureCount+1,failureReason:s.error,isPaused:!1,status:"error"}}};this.state=r(this.state),et.batch(()=>{C(this,rs).forEach(a=>{a.onMutationUpdate(s)}),C(this,ot).notify({mutation:this,type:"updated",action:s})})},Sp);function fh(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var _s,Ut,An,Cp,fy=(Cp=class extends Fa{constructor(s={}){super();le(this,_s);le(this,Ut);le(this,An);this.config=s,Z(this,_s,new Set),Z(this,Ut,new Map),Z(this,An,0)}build(s,r,a){const n=new xy({client:s,mutationCache:this,mutationId:++io(this,An)._,options:s.defaultMutationOptions(r),state:a});return this.add(n),n}add(s){C(this,_s).add(s);const r=co(s);if(typeof r=="string"){const a=C(this,Ut).get(r);a?a.push(s):C(this,Ut).set(r,[s])}this.notify({type:"added",mutation:s})}remove(s){if(C(this,_s).delete(s)){const r=co(s);if(typeof r=="string"){const a=C(this,Ut).get(r);if(a)if(a.length>1){const n=a.indexOf(s);n!==-1&&a.splice(n,1)}else a[0]===s&&C(this,Ut).delete(r)}}this.notify({type:"removed",mutation:s})}canRun(s){const r=co(s);if(typeof r=="string"){const a=C(this,Ut).get(r),n=a==null?void 0:a.find(o=>o.state.status==="pending");return!n||n===s}else return!0}runNext(s){var a;const r=co(s);if(typeof r=="string"){const n=(a=C(this,Ut).get(r))==null?void 0:a.find(o=>o!==s&&o.state.isPaused);return(n==null?void 0:n.continue())??Promise.resolve()}else return Promise.resolve()}clear(){et.batch(()=>{C(this,_s).forEach(s=>{this.notify({type:"removed",mutation:s})}),C(this,_s).clear(),C(this,Ut).clear()})}getAll(){return Array.from(C(this,_s))}find(s){const r={exact:!0,...s};return this.getAll().find(a=>Qd(r,a))}findAll(s={}){return this.getAll().filter(r=>Qd(s,r))}notify(s){et.batch(()=>{this.listeners.forEach(r=>{r(s)})})}resumePausedMutations(){const s=this.getAll().filter(r=>r.state.isPaused);return et.batch(()=>Promise.all(s.map(r=>r.continue().catch(pt))))}},_s=new WeakMap,Ut=new WeakMap,An=new WeakMap,Cp);function co(e){var s;return(s=e.options.scope)==null?void 0:s.id}var Ss,Xs,gt,Cs,Es,Ro,Wl,Ep,gy=(Ep=class extends Fa{constructor(r,a){super();le(this,Es);le(this,Ss);le(this,Xs);le(this,gt);le(this,Cs);Z(this,Ss,r),this.setOptions(a),this.bindMethods(),he(this,Es,Ro).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var n;const a=this.options;this.options=C(this,Ss).defaultMutationOptions(r),Lo(this.options,a)||C(this,Ss).getMutationCache().notify({type:"observerOptionsUpdated",mutation:C(this,gt),observer:this}),a!=null&&a.mutationKey&&this.options.mutationKey&&Ir(a.mutationKey)!==Ir(this.options.mutationKey)?this.reset():((n=C(this,gt))==null?void 0:n.state.status)==="pending"&&C(this,gt).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=C(this,gt))==null||r.removeObserver(this)}onMutationUpdate(r){he(this,Es,Ro).call(this),he(this,Es,Wl).call(this,r)}getCurrentResult(){return C(this,Xs)}reset(){var r;(r=C(this,gt))==null||r.removeObserver(this),Z(this,gt,void 0),he(this,Es,Ro).call(this),he(this,Es,Wl).call(this)}mutate(r,a){var n;return Z(this,Cs,a),(n=C(this,gt))==null||n.removeObserver(this),Z(this,gt,C(this,Ss).getMutationCache().build(C(this,Ss),this.options)),C(this,gt).addObserver(this),C(this,gt).execute(r)}},Ss=new WeakMap,Xs=new WeakMap,gt=new WeakMap,Cs=new WeakMap,Es=new WeakSet,Ro=function(){var a;const r=((a=C(this,gt))==null?void 0:a.state)??fh();Z(this,Xs,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},Wl=function(r){et.batch(()=>{var a,n,o,i,l,c,d,m;if(C(this,Cs)&&this.hasListeners()){const u=C(this,Xs).variables,h=C(this,Xs).context,x={client:C(this,Ss),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(n=(a=C(this,Cs)).onSuccess)==null||n.call(a,r.data,u,h,x)}catch(g){Promise.reject(g)}try{(i=(o=C(this,Cs)).onSettled)==null||i.call(o,r.data,null,u,h,x)}catch(g){Promise.reject(g)}}else if((r==null?void 0:r.type)==="error"){try{(c=(l=C(this,Cs)).onError)==null||c.call(l,r.error,u,h,x)}catch(g){Promise.reject(g)}try{(m=(d=C(this,Cs)).onSettled)==null||m.call(d,void 0,r.error,u,h,x)}catch(g){Promise.reject(g)}}}this.listeners.forEach(u=>{u(C(this,Xs))})})},Ep),ns,Rp,by=(Rp=class extends Fa{constructor(s={}){super();le(this,ns);this.config=s,Z(this,ns,new Map)}build(s,r,a){const n=r.queryKey,o=r.queryHash??Oc(n,r);let i=this.get(o);return i||(i=new uy({client:s,queryKey:n,queryHash:o,options:s.defaultQueryOptions(r),state:a,defaultOptions:s.getQueryDefaults(n)}),this.add(i)),i}add(s){C(this,ns).has(s.queryHash)||(C(this,ns).set(s.queryHash,s),this.notify({type:"added",query:s}))}remove(s){const r=C(this,ns).get(s.queryHash);r&&(s.destroy(),r===s&&C(this,ns).delete(s.queryHash),this.notify({type:"removed",query:s}))}clear(){et.batch(()=>{this.getAll().forEach(s=>{this.remove(s)})})}get(s){return C(this,ns).get(s)}getAll(){return[...C(this,ns).values()]}find(s){const r={exact:!0,...s};return this.getAll().find(a=>Yd(r,a))}findAll(s={}){const r=this.getAll();return Object.keys(s).length>0?r.filter(a=>Yd(s,a)):r}notify(s){et.batch(()=>{this.listeners.forEach(r=>{r(s)})})}onFocus(){et.batch(()=>{this.getAll().forEach(s=>{s.onFocus()})})}onOnline(){et.batch(()=>{this.getAll().forEach(s=>{s.onOnline()})})}},ns=new WeakMap,Rp),We,Zs,er,ba,ya,tr,va,ja,Tp,yy=(Tp=class{constructor(e={}){le(this,We);le(this,Zs);le(this,er);le(this,ba);le(this,ya);le(this,tr);le(this,va);le(this,ja);Z(this,We,e.queryCache||new by),Z(this,Zs,e.mutationCache||new fy),Z(this,er,e.defaultOptions||{}),Z(this,ba,new Map),Z(this,ya,new Map),Z(this,tr,0)}mount(){io(this,tr)._++,C(this,tr)===1&&(Z(this,va,Lc.subscribe(async e=>{e&&(await this.resumePausedMutations(),C(this,We).onFocus())})),Z(this,ja,Oo.subscribe(async e=>{e&&(await this.resumePausedMutations(),C(this,We).onOnline())})))}unmount(){var e,s;io(this,tr)._--,C(this,tr)===0&&((e=C(this,va))==null||e.call(this),Z(this,va,void 0),(s=C(this,ja))==null||s.call(this),Z(this,ja,void 0))}isFetching(e){return C(this,We).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return C(this,Zs).findAll({...e,status:"pending"}).length}getQueryData(e){var r;const s=this.defaultQueryOptions({queryKey:e});return(r=C(this,We).get(s.queryHash))==null?void 0:r.state.data}ensureQueryData(e){const s=this.defaultQueryOptions(e),r=C(this,We).build(this,s),a=r.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(sr(s.staleTime,r))&&this.prefetchQuery(s),Promise.resolve(a))}getQueriesData(e){return C(this,We).findAll(e).map(({queryKey:s,state:r})=>{const a=r.data;return[s,a]})}setQueryData(e,s,r){const a=this.defaultQueryOptions({queryKey:e}),n=C(this,We).get(a.queryHash),o=n==null?void 0:n.state.data,i=ey(s,o);if(i!==void 0)return C(this,We).build(this,a).setData(i,{...r,manual:!0})}setQueriesData(e,s,r){return et.batch(()=>C(this,We).findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,s,r)]))}getQueryState(e){var r;const s=this.defaultQueryOptions({queryKey:e});return(r=C(this,We).get(s.queryHash))==null?void 0:r.state}removeQueries(e){const s=C(this,We);et.batch(()=>{s.findAll(e).forEach(r=>{s.remove(r)})})}resetQueries(e,s){const r=C(this,We);return et.batch(()=>(r.findAll(e).forEach(a=>{a.reset()}),this.refetchQueries({type:"active",...e},s)))}cancelQueries(e,s={}){const r={revert:!0,...s},a=et.batch(()=>C(this,We).findAll(e).map(n=>n.cancel(r)));return Promise.all(a).then(pt).catch(pt)}invalidateQueries(e,s={}){return et.batch(()=>(C(this,We).findAll(e).forEach(r=>{r.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},s)))}refetchQueries(e,s={}){const r={...s,cancelRefetch:s.cancelRefetch??!0},a=et.batch(()=>C(this,We).findAll(e).filter(n=>!n.isDisabled()&&!n.isStatic()).map(n=>{let o=n.fetch(void 0,r);return r.throwOnError||(o=o.catch(pt)),n.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(a).then(pt)}fetchQuery(e){const s=this.defaultQueryOptions(e);s.retry===void 0&&(s.retry=!1);const r=C(this,We).build(this,s);return r.isStaleByTime(sr(s.staleTime,r))?r.fetch(s):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(pt).catch(pt)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(pt).catch(pt)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Oo.isOnline()?C(this,Zs).resumePausedMutations():Promise.resolve()}getQueryCache(){return C(this,We)}getMutationCache(){return C(this,Zs)}getDefaultOptions(){return C(this,er)}setDefaultOptions(e){Z(this,er,e)}setQueryDefaults(e,s){C(this,ba).set(Ir(e),{queryKey:e,defaultOptions:s})}getQueryDefaults(e){const s=[...C(this,ba).values()],r={};return s.forEach(a=>{bn(e,a.queryKey)&&Object.assign(r,a.defaultOptions)}),r}setMutationDefaults(e,s){C(this,ya).set(Ir(e),{mutationKey:e,defaultOptions:s})}getMutationDefaults(e){const s=[...C(this,ya).values()],r={};return s.forEach(a=>{bn(e,a.mutationKey)&&Object.assign(r,a.defaultOptions)}),r}defaultQueryOptions(e){if(e._defaulted)return e;const s={...C(this,er).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return s.queryHash||(s.queryHash=Oc(s.queryKey,s)),s.refetchOnReconnect===void 0&&(s.refetchOnReconnect=s.networkMode!=="always"),s.throwOnError===void 0&&(s.throwOnError=!!s.suspense),!s.networkMode&&s.persister&&(s.networkMode="offlineFirst"),s.queryFn===zc&&(s.enabled=!1),s}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...C(this,er).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){C(this,We).clear(),C(this,Zs).clear()}},We=new WeakMap,Zs=new WeakMap,er=new WeakMap,ba=new WeakMap,ya=new WeakMap,tr=new WeakMap,va=new WeakMap,ja=new WeakMap,Tp),gh=p.createContext(void 0),Da=e=>{const s=p.useContext(gh);if(!s)throw new Error("No QueryClient set, use QueryClientProvider to set one");return s},vy=({client:e,children:s})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),t.jsx(gh.Provider,{value:e,children:s})),bh=p.createContext(!1),jy=()=>p.useContext(bh);bh.Provider;function wy(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ny=p.createContext(wy()),ky=()=>p.useContext(Ny),_y=(e,s,r)=>{const a=r!=null&&r.state.error&&typeof e.throwOnError=="function"?Bc(e.throwOnError,[r.state.error,r]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||a)&&(s.isReset()||(e.retryOnMount=!1))},Sy=e=>{p.useEffect(()=>{e.clearReset()},[e])},Cy=({result:e,errorResetBoundary:s,throwOnError:r,query:a,suspense:n})=>e.isError&&!s.isReset()&&!e.isFetching&&a&&(n&&e.data===void 0||Bc(r,[e.error,a])),Ey=e=>{if(e.suspense){const r=n=>n==="static"?n:Math.max(n??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...n)=>r(a(...n)):r(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Ry=(e,s)=>e.isLoading&&e.isFetching&&!s,Ty=(e,s)=>(e==null?void 0:e.suspense)&&s.isPending,au=(e,s,r)=>s.fetchOptimistic(e).catch(()=>{r.clearReset()});function My(e,s,r){var x,g,f,y;const a=jy(),n=ky(),o=Da(),i=o.defaultQueryOptions(e);(g=(x=o.getDefaultOptions().queries)==null?void 0:x._experimental_beforeQuery)==null||g.call(x,i);const l=o.getQueryCache().get(i.queryHash),c=e.subscribed!==!1;i._optimisticResults=a?"isRestoring":c?"optimistic":void 0,Ey(i),_y(i,n,l),Sy(n);const d=!o.getQueryCache().get(i.queryHash),[m]=p.useState(()=>new s(o,i)),u=m.getOptimisticResult(i),h=!a&&c;if(p.useSyncExternalStore(p.useCallback(b=>{const v=h?m.subscribe(et.batchCalls(b)):pt;return m.updateResult(),v},[m,h]),()=>m.getCurrentResult(),()=>m.getCurrentResult()),p.useEffect(()=>{m.setOptions(i)},[i,m]),Ty(i,u))throw au(i,m,n);if(Cy({result:u,errorResetBoundary:n,throwOnError:i.throwOnError,query:l,suspense:i.suspense}))throw u.error;if((y=(f=o.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||y.call(f,i,u),i.experimental_prefetchInRender&&!yn.isServer()&&Ry(u,a)){const b=d?au(i,m,n):l==null?void 0:l.promise;b==null||b.catch(pt).finally(()=>{m.updateResult()})}return i.notifyOnChangeProps?u:m.trackResult(u)}function ui(e,s){return My(e,my)}function mi(e,s){const r=Da(),[a]=p.useState(()=>new gy(r,e));p.useEffect(()=>{a.setOptions(e)},[a,e]);const n=p.useSyncExternalStore(p.useCallback(i=>a.subscribe(et.batchCalls(i)),[a]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),o=p.useCallback((i,l)=>{a.mutate(i,l).catch(pt)},[a]);if(n.error&&Bc(a.options.throwOnError,[n.error]))throw n.error;return{...n,mutate:o,mutateAsync:n.mutate}}const Py="modulepreload",Iy=function(e){return"/"+e},nu={},Ot=function(s,r,a){let n=Promise.resolve();if(r&&r.length>0){let i=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));n=i(r.map(d=>{if(d=Iy(d),d in nu)return;nu[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Py,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((x,g)=>{h.addEventListener("load",x),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=i,window.dispatchEvent(l),!l.defaultPrevented)throw i}return n.then(i=>{for(const l of i||[])l.status==="rejected"&&o(l.reason);return s().catch(o)})};/** * react-router v7.18.2 * * Copyright (c) Remix Software Inc. @@ -13,8 +13,8 @@ var P0=Object.defineProperty;var Gd=e=>{throw TypeError(e)};var I0=(e,s,r)=>s in Please change the parent to .`)}let m=Rt(),u;if(s){let b=typeof s=="string"?La(s):s;He(c==="/"||((y=b.pathname)==null?void 0:y.startsWith(c)),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${b.pathname}" was given in the \`location\` prop.`),u=b}else u=m;let h=u.pathname||"/",x=h;if(c!=="/"){let b=c.replace(/^\//,"").split("/");x="/"+h.replace(/^\//,"").split("/").slice(b.length).join("/")}let g=r&&r.state.matches.length?r.state.matches.map(b=>Object.assign(b,{route:r.manifest[b.route.id]||b.route})):vh(e,{pathname:x});Kt(d||g!=null,`No routes matched location "${u.pathname}${u.search}${u.hash}" `),Kt(g==null||g[g.length-1].route.element!==void 0||g[g.length-1].route.Component!==void 0||g[g.length-1].route.lazy!==void 0,`Matched leaf route at location "${u.pathname}${u.search}${u.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.`);let f=_v(g&&g.map(b=>Object.assign({},b,{params:Object.assign({},i,b.params),pathname:Wt([c,a.encodeLocation?a.encodeLocation(b.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:b.pathname]),pathnameBase:b.pathnameBase==="/"?c:Wt([c,a.encodeLocation?a.encodeLocation(b.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:b.pathnameBase])})),n,r);return s&&f?p.createElement(Bn.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...u},navigationType:"POP"}},f):f}function jv(){let e=Tv(),s=av(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),r=e instanceof Error?e.stack:null,a="rgba(200,200,200, 0.5)",n={padding:"0.5rem",backgroundColor:a},o={padding:"2px 4px",backgroundColor:a},i=null;return console.error("Error handled by React Router default ErrorBoundary:",e),i=p.createElement(p.Fragment,null,p.createElement("p",null,"💿 Hey developer 👋"),p.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",p.createElement("code",{style:o},"ErrorBoundary")," or"," ",p.createElement("code",{style:o},"errorElement")," prop on your route.")),p.createElement(p.Fragment,null,p.createElement("h2",null,"Unexpected Application Error!"),p.createElement("h3",{style:{fontStyle:"italic"}},s),r?p.createElement("pre",{style:n},r):null,i)}var wv=p.createElement(jv,null),Fh=class extends p.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,s){return s.location!==e.location||s.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:s.error,location:s.location,revalidation:e.revalidation||s.revalidation}}componentDidCatch(e,s){this.props.onError?this.props.onError(e,s):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const r=xv(e.digest);r&&(e=r)}let s=e!==void 0?p.createElement(fs.Provider,{value:this.props.routeContext},p.createElement(Wc.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?p.createElement(Nv,{error:e},s):s}};Fh.contextType=Th;var Ki=new WeakMap;function Nv({children:e,error:s}){let{basename:r}=p.useContext(zt);if(typeof s=="object"&&s&&"digest"in s&&typeof s.digest=="string"){let a=hv(s.digest);if(a){let n=Ki.get(s);if(n)throw n;let o=Eh(a.location,r),i=o.absoluteURL||o.to;if(lv(i))throw new Error("Invalid redirect location");if(Ch&&!Ki.get(s))if(o.isExternal||a.reloadDocument)window.location.href=i;else{const l=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:a.replace}));throw Ki.set(s,l),l}return p.createElement("meta",{httpEquiv:"refresh",content:`0;url=${i}`})}}return e}function kv({routeContext:e,match:s,children:r}){let a=p.useContext(Oa);return a&&a.static&&a.staticContext&&(s.route.errorElement||s.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=s.route.id),p.createElement(fs.Provider,{value:e},r)}function _v(e,s=[],r){let a=r==null?void 0:r.state;if(e==null){if(!a)return null;if(a.errors)e=a.matches;else if(s.length===0&&!a.initialized&&a.matches.length>0)e=a.matches;else return null}let n=e,o=a==null?void 0:a.errors;if(o!=null){let m=n.findIndex(u=>u.route.id&&(o==null?void 0:o[u.route.id])!==void 0);He(m>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),n=n.slice(0,Math.min(n.length,m+1))}let i=!1,l=-1;if(r&&a){i=a.renderFallback;for(let m=0;m=0?n=n.slice(0,l+1):n=[n[0]];break}}}}let c=r==null?void 0:r.onError,d=a&&c?(m,u)=>{var h,x;c(m,{location:a.location,params:((x=(h=a.matches)==null?void 0:h[0])==null?void 0:x.params)??{},pattern:nv(a.matches),errorInfo:u})}:void 0;return n.reduceRight((m,u,h)=>{let x,g=!1,f=null,y=null;a&&(x=o&&u.route.id?o[u.route.id]:void 0,f=u.route.errorElement||wv,i&&(l<0&&h===0?(Dh("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),g=!0,y=null):l===h&&(g=!0,y=u.route.hydrateFallbackElement||null)));let b=s.concat(n.slice(0,h+1)),v=()=>{let j;return x?j=f:g?j=y:u.route.Component?j=p.createElement(u.route.Component,null):u.route.element?j=u.route.element:j=m,p.createElement(kv,{match:u,routeContext:{outlet:m,matches:b,isDataRoute:a!=null},children:j})};return a&&(u.route.ErrorBoundary||u.route.errorElement||h===0)?p.createElement(Fh,{location:a.location,revalidation:a.revalidation,component:f,error:x,children:v(),routeContext:{outlet:null,matches:b,isDataRoute:!0},onError:d}):v()},null)}function Gc(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Sv(e){let s=p.useContext(Oa);return He(s,Gc(e)),s}function Cv(e){let s=p.useContext(pi);return He(s,Gc(e)),s}function Ev(e){let s=p.useContext(fs);return He(s,Gc(e)),s}function qc(e){let s=Ev(e),r=s.matches[s.matches.length-1];return He(r.route.id,`${e} can only be used on routes that contain a unique "id"`),r.route.id}function Rv(){return qc("useRouteId")}function Tv(){var a;let e=p.useContext(Wc),s=Cv("useRouteError"),r=qc("useRouteError");return e!==void 0?e:(a=s.errors)==null?void 0:a[r]}function Mv(){let{router:e}=Sv("useNavigate"),s=qc("useNavigate"),r=p.useRef(!1);return Ah(()=>{r.current=!0}),p.useCallback(async(n,o={})=>{Kt(r.current,Ih),r.current&&(typeof n=="number"?await e.navigate(n):await e.navigate(n,{fromRouteId:s,...o}))},[e,s])}var uu={};function Dh(e,s,r){!s&&!uu[e]&&(uu[e]=!0,Kt(!1,r))}p.memo(Pv);function Pv({routes:e,manifest:s,future:r,state:a,isStatic:n,onError:o}){return $h(e,void 0,{manifest:s,state:a,isStatic:n,onError:o})}function Iv(e){return yv(e.context)}function vt(e){He(!1,"A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .")}function Av({basename:e="/",children:s=null,location:r,navigationType:a="POP",navigator:n,static:o=!1,useTransitions:i}){He(!Vn(),"You cannot render a inside another . You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=p.useMemo(()=>({basename:l,navigator:n,static:o,useTransitions:i,future:{}}),[l,n,o,i]);typeof r=="string"&&(r=La(r));let{pathname:d="/",search:m="",hash:u="",state:h=null,key:x="default",mask:g}=r,f=p.useMemo(()=>{let y=Rs(d,l);return y==null?null:{location:{pathname:y,search:m,hash:u,state:h,key:x,mask:g},navigationType:a}},[l,d,m,u,h,x,a,g]);return Kt(f!=null,` is not able to match the URL "${d}${m}${u}" because it does not start with the basename, so the won't render anything.`),f==null?null:p.createElement(zt.Provider,{value:c},p.createElement(Bn.Provider,{children:s,value:f}))}function $v({children:e,location:s}){return vv(ql(e),s)}function ql(e,s=[]){let r=[];return p.Children.forEach(e,(a,n)=>{if(!p.isValidElement(a))return;let o=[...s,n];if(a.type===p.Fragment){r.push.apply(r,ql(a.props.children,o));return}He(a.type===vt,`[${typeof a.type=="string"?a.type:a.type.name}] is not a component. All component children of must be a or `),He(!a.props.index||!a.props.children,"An index route cannot have child routes.");let i={id:a.props.id||o.join("-"),caseSensitive:a.props.caseSensitive,element:a.props.element,Component:a.props.Component,index:a.props.index,path:a.props.path,middleware:a.props.middleware,loader:a.props.loader,action:a.props.action,hydrateFallbackElement:a.props.hydrateFallbackElement,HydrateFallback:a.props.HydrateFallback,errorElement:a.props.errorElement,ErrorBoundary:a.props.ErrorBoundary,hasErrorBoundary:a.props.hasErrorBoundary===!0||a.props.ErrorBoundary!=null||a.props.errorElement!=null,shouldRevalidate:a.props.shouldRevalidate,handle:a.props.handle,lazy:a.props.lazy};a.props.children&&(i.children=ql(a.props.children,o)),r.push(i)}),r}var To="get",Mo="application/x-www-form-urlencoded";function hi(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function Fv(e){return hi(e)&&e.tagName.toLowerCase()==="button"}function Dv(e){return hi(e)&&e.tagName.toLowerCase()==="form"}function Lv(e){return hi(e)&&e.tagName.toLowerCase()==="input"}function Ov(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function zv(e,s){return e.button===0&&(!s||s==="_self")&&!Ov(e)}function Kl(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((s,r)=>{let a=e[r];return s.concat(Array.isArray(a)?a.map(n=>[r,n]):[[r,a]])},[]))}function Bv(e,s){let r=Kl(e);return s&&s.forEach((a,n)=>{r.has(n)||s.getAll(n).forEach(o=>{r.append(n,o)})}),r}var uo=null;function Vv(){if(uo===null)try{new FormData(document.createElement("form"),0),uo=!1}catch{uo=!0}return uo}var Uv=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function Ji(e){return e!=null&&!Uv.has(e)?(Kt(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${Mo}"`),null):e}function Hv(e,s){let r,a,n,o,i;if(Dv(e)){let l=e.getAttribute("action");a=l?Rs(l,s):null,r=e.getAttribute("method")||To,n=Ji(e.getAttribute("enctype"))||Mo,o=new FormData(e)}else if(Fv(e)||Lv(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a