Skip to content
Merged

0824 #175

Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
5302500
feat(canvas): guide template setup with dataset and target selection
flyingriverhorse Sep 20, 2026
6dc5ba8
chore: stop tracking local initiatives documents
flyingriverhorse Sep 20, 2026
aaf5c1e
fix(backend): redact credentials across error diagnostic sinks
flyingriverhorse Sep 20, 2026
44147b0
fix: align notebook exports with Canvas training and inference
flyingriverhorse Sep 20, 2026
f855e2e
fix: persist results from the job target node
flyingriverhorse Sep 20, 2026
b051edd
fix: publish local model artifacts atomically
flyingriverhorse Sep 20, 2026
660154c
fix: isolate S3 caches by full object identity
flyingriverhorse Sep 20, 2026
a67ad39
fix: reject incomplete preprocessing before publishing model bundles
flyingriverhorse Sep 20, 2026
4b50004
fix: require explicit temporal features at model boundaries
flyingriverhorse Sep 20, 2026
831a5ed
fix: preserve quoted inference CSV records through import and export
flyingriverhorse Sep 20, 2026
0ec6076
fix: validate advanced searches and persist job descriptions without …
flyingriverhorse Sep 20, 2026
921e120
fix: isolate run warnings and keep prediction and realtime responsive
flyingriverhorse Sep 20, 2026
fda5527
fix: preserve monitoring context and surface migration and tuning fai…
flyingriverhorse Sep 20, 2026
cf93586
fix: validate numeric inputs and correct decomposition and timeline r…
flyingriverhorse Sep 20, 2026
61a3b83
fix: preserve EDA filter context and align drift history and exports
flyingriverhorse Sep 21, 2026
127f340
fix: exclude missing predictions from numeric summaries
flyingriverhorse Sep 21, 2026
78c461a
fix: apply exact histogram bin filters atomically
flyingriverhorse Sep 21, 2026
37f0346
fix: validate threshold weights and align correlation exports
flyingriverhorse Sep 21, 2026
3c300c9
fix: retain relative error histogram tails and explain exclusions
flyingriverhorse Sep 21, 2026
661bb82
fix: validate drift thresholds and expose effective values
flyingriverhorse Sep 21, 2026
05528d2
fix: render unavailable EDA statistics without inventing zero
flyingriverhorse Sep 21, 2026
67f0222
fix: surface decomposition failures with scoped retry
flyingriverhorse Sep 21, 2026
43c5fbc
fix: label clustering export as the displayed summary
flyingriverhorse Sep 21, 2026
cf13767
fix: distinguish missing EDA analysis from empty results
flyingriverhorse Sep 21, 2026
4e33cde
fix: label seasonality charts with the recorded measure
flyingriverhorse Sep 21, 2026
ee2981b
fix: synchronize connected ensemble parameter changes
flyingriverhorse Sep 21, 2026
1fcf991
fix: close verified lifecycle and pipeline audit findings
flyingriverhorse Sep 21, 2026
08d8068
chore: release 0.8.24 with audit fixes and contract coverage
flyingriverhorse Sep 21, 2026
50b6c3b
fix: restore CI gates and bind template model targets
flyingriverhorse Sep 21, 2026
1548096
fix: upgrade vulnerable AnyIO and Jupyter Server dependencies
flyingriverhorse Sep 21, 2026
f713003
fix backend
flyingriverhorse Sep 21, 2026
3587521
fix e2e
flyingriverhorse Sep 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ app_data/
backups/

# === Documentation (build artifacts) ===

*initiatives

# === Local library bundle ===
skyulf-mlflow/
Expand Down
5 changes: 3 additions & 2 deletions backend/data/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import contextlib
import hashlib
import logging
import os
import tempfile
Expand Down Expand Up @@ -344,8 +345,8 @@ def _get_s3_path(self, dataset_id: str) -> str:
return f"s3://{self.bucket_name}/{dataset_id}"

def _get_cache_path(self, s3_path: str) -> str:
# Create a safe filename from the S3 path
safe_name = s3_path.replace("s3://", "").replace("/", "_").replace("\\", "_")
"""Hash the full bucket/key identity without reusing ambiguous legacy caches."""
safe_name = "s3-v2-" + hashlib.sha256(s3_path.encode("utf-8")).hexdigest()
resolved = os.path.realpath(os.path.join(self.cache_dir, safe_name))
base = os.path.realpath(self.cache_dir)
if not resolved.startswith(base + os.sep) and resolved != base:
Expand Down
16 changes: 16 additions & 0 deletions backend/data_ingestion/schemas/ingestion.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator

from backend.utils.logging_utils import redact_error_details

# Keys inside `config` that should never be sent to clients.
_SENSITIVE_CONFIG_KEYS = frozenset(
{
Expand Down Expand Up @@ -65,6 +67,12 @@ class IngestionStatus(BaseModel):
details: dict[str, Any] | None = None
updated_at: datetime

@field_validator("error", "details", mode="before")
@classmethod
def redact_diagnostics(cls, value: Any) -> Any:
"""Protect stored status diagnostics, including records written before redaction."""
return redact_error_details(value)


class DataSourceRead(BaseModel):
"""Client-safe view of a ``DataSource`` row.
Expand All @@ -89,6 +97,14 @@ class DataSourceRead(BaseModel):
columns: int | None = None
size_bytes: int | None = None

@field_validator("source_metadata", mode="before")
@classmethod
def redact_ingestion_diagnostics(cls, value: Any) -> Any:
"""Copy and scrub ingestion status without changing user data in the profile."""
if isinstance(value, dict) and "ingestion_status" in value:
return {**value, "ingestion_status": redact_error_details(value["ingestion_status"])}
return value

@field_validator("config", mode="before")
@classmethod
def redact_sensitive_config(cls, v: Any) -> Any:
Expand Down
28 changes: 21 additions & 7 deletions backend/data_ingestion/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

import logging
import traceback
import uuid
from collections.abc import Sequence
from datetime import UTC, datetime
Expand All @@ -31,6 +32,7 @@
from backend.pagination import MAX_SAMPLE_ROWS, validate_limit, validate_page_bounds
from backend.services.data_service import DataService
from backend.utils import sanitize_for_log
from backend.utils.logging_utils import redact_credentials

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -198,12 +200,18 @@ async def _fetch_s3_sample(
except (ForbiddenException, ResourceNotFoundException) as e:
# Typed exceptions raised by S3Connector for 403/404 provider
# responses — classified there rather than string-matched here.
logger.error(f"Failed to get S3 sample: {e}", exc_info=log_exc_info)
diagnostic = "".join(traceback.format_exception(e)) if log_exc_info else str(e)
logger.error(
"Failed to get S3 sample: %s", sanitize_for_log(redact_credentials(diagnostic))
)
raise HTTPException(
status_code=400, detail="S3 access denied or resource not found"
) from e
except Exception as e:
logger.error(f"Failed to get S3 sample: {e}", exc_info=log_exc_info)
diagnostic = "".join(traceback.format_exception(e)) if log_exc_info else str(e)
logger.error(
"Failed to get S3 sample: %s", sanitize_for_log(redact_credentials(diagnostic))
)
raise SkyulfException(message="Failed to read S3 data sample") from e

async def _sample_local_file(self, file_path: Any, limit: int) -> list[dict]:
Expand Down Expand Up @@ -334,7 +342,11 @@ def _trigger_ingestion(
def _on_done(t: asyncio.Task) -> None:
exc = t.exception() if not t.cancelled() else None
if exc:
logger.error("Ingestion task failed for source %s: %s", source_id, exc)
logger.error(
"Ingestion task failed for source %s: %s",
source_id,
sanitize_for_log(redact_credentials(exc)),
)

_task.add_done_callback(_on_done)

Expand Down Expand Up @@ -405,8 +417,9 @@ async def handle_create_source(
except HTTPException:
raise
except Exception as e:
logger.error(f"Database error: {e}")
raise SkyulfException(message=f"Database error: {str(e)}") from e
safe_error = redact_credentials(e)
logger.error("Database error: %s", sanitize_for_log(safe_error))
raise SkyulfException(message=f"Database error: {safe_error}") from e

@staticmethod
def _check_declared_upload_size(file: UploadFile, settings: Any) -> None:
Expand Down Expand Up @@ -525,11 +538,12 @@ async def _create_file_source_and_ingest(
)

except Exception as e:
logger.error(f"Database error: {e}")
safe_error = redact_credentials(e)
logger.error("Database error: %s", sanitize_for_log(safe_error))
# Cleanup file if DB fails
if file_path.exists():
file_path.unlink()
raise SkyulfException(message=f"Database error: {str(e)}") from e
raise SkyulfException(message=f"Database error: {safe_error}") from e

async def handle_file_upload(
self,
Expand Down
15 changes: 12 additions & 3 deletions backend/data_ingestion/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from backend.data_ingestion.connectors.s3 import S3Connector
from backend.data_ingestion.engine.profiler import DataProfiler
from backend.database.models import DataSource
from backend.utils.logging_utils import redact_credentials, sanitize_for_log

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -139,7 +140,8 @@ def _mark_ingestion_completed(session, data_source, metadata: dict, profile: dic

def _handle_ingestion_failure(session, source_id: int, error: Exception) -> None:
"""Log the ingestion failure and, if possible, persist a 'failed' ingestion status."""
logger.error(f"Ingestion failed for source {source_id}: {str(error)}")
safe_error = redact_credentials(error)
logger.error("Ingestion failed for source %s: %s", source_id, sanitize_for_log(safe_error))
if session:
# Roll back first: if the exception came from a DB error (e.g. a
# failed commit above), the session is left in a rolled-back/
Expand All @@ -150,7 +152,7 @@ def _handle_ingestion_failure(session, source_id: int, error: Exception) -> None
metadata = dict(data_source.source_metadata or {})
metadata["ingestion_status"] = {
"status": "failed",
"error": str(error),
"error": safe_error,
"updated_at": datetime.now(UTC).isoformat(),
}
data_source.source_metadata = metadata
Expand Down Expand Up @@ -185,6 +187,13 @@ def ingest_data_task(source_id: int):
logger.info(f"Ingestion completed for source {source_id}")

except Exception as e: # noqa: BLE001 - task boundary, failure recorded by handler
_handle_ingestion_failure(session, source_id, e)
try:
_handle_ingestion_failure(session, source_id, e)
except Exception as recovery_error: # noqa: BLE001 - sanitize Celery failure boundary
# Keep the task failed, but prevent Celery from serializing SQL parameters
# or logging the original exception chain containing source credentials.
raise RuntimeError(
f"Unable to persist ingestion failure: {redact_credentials(recovery_error)}"
) from None
finally:
session.close()
33 changes: 17 additions & 16 deletions backend/database/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,14 @@ class DatabaseType:
SNOWFLAKE = "snowflake"


# Maps DB type -> tuple of recognized URL prefixes, checked in order.
_URL_PREFIX_TYPES: tuple[tuple[str, tuple[str, ...]], ...] = (
(DatabaseType.POSTGRES, ("postgresql://", "postgresql+asyncpg://")),
(DatabaseType.SQLITE, ("sqlite://", "sqlite+aiosqlite://")),
(DatabaseType.MYSQL, ("mysql://", "mysql+aiomysql://")),
(DatabaseType.MONGODB, ("mongodb://", "mongodb+srv://")),
)
# Backend family does not depend on the optional driver suffix.
_URL_SCHEME_TYPES = {
"postgresql": DatabaseType.POSTGRES,
"sqlite": DatabaseType.SQLITE,
"mysql": DatabaseType.MYSQL,
"mongodb": DatabaseType.MONGODB,
"snowflake": DatabaseType.SNOWFLAKE,
}


def get_db_type_from_url(database_url: str) -> str:
Expand All @@ -59,16 +60,16 @@ def get_db_type_from_url(database_url: str) -> str:

Returns:
str: Database type identifier
"""
for db_type, prefixes in _URL_PREFIX_TYPES:
if database_url.startswith(prefixes):
return db_type

if "snowflake" in database_url.lower():
return DatabaseType.SNOWFLAKE

# Default fallback
return DatabaseType.SQLITE
Raises:
ValueError: The URL scheme is absent or unsupported. Driver availability
and async compatibility are validated when the connection is opened.
"""
scheme, separator, _ = database_url.partition("://")
backend = scheme.lower().split("+", 1)[0]
if separator and backend in _URL_SCHEME_TYPES:
return _URL_SCHEME_TYPES[backend]
raise ValueError("Unsupported database URL scheme")


def get_db_type(settings: Settings) -> str:
Expand Down
66 changes: 50 additions & 16 deletions backend/database/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,9 @@ async def _run_migrations() -> None:
``_MIGRATIONS`` list below so that existing databases are patched on the
next startup.

Each statement is executed inside its own try/except so that:
* Fresh databases (column already exists via create_all) skip silently.
* Repeated startups are idempotent.
Inspect columns before executing each ALTER so repeated startups are
idempotent. Missing legacy tables are optional; inspection and DDL failures
for the current schema propagate to prevent a falsely successful startup.

HOW TO ADD A FUTURE MIGRATION:
1. Add the column to the SQLAlchemy model as usual.
Expand All @@ -206,17 +206,18 @@ async def _run_migrations() -> None:
if not async_engine:
return

from sqlalchemy import text
from sqlalchemy import inspect, text
from sqlalchemy.exc import DBAPIError

_MIGRATIONS: list[tuple[str, str]] = [
# v0.5.0 — Promote Winner
("0.5.0", "ALTER TABLE basic_training_jobs ADD COLUMN promoted_at DATETIME"),
("0.5.0", "ALTER TABLE advanced_tuning_jobs ADD COLUMN promoted_at DATETIME"),
("0.5.0", "ALTER TABLE basic_training_jobs ADD COLUMN promoted_at TIMESTAMP"),
("0.5.0", "ALTER TABLE advanced_tuning_jobs ADD COLUMN promoted_at TIMESTAMP"),
# v0.6.0 — Threshold Tuning Phase 2
("0.6.0", "ALTER TABLE training_jobs ADD COLUMN tuned_thresholds JSON"),
(
"0.6.0",
"ALTER TABLE training_jobs ADD COLUMN tuned_thresholds_enabled BOOLEAN NOT NULL DEFAULT 0",
"ALTER TABLE training_jobs ADD COLUMN tuned_thresholds_enabled BOOLEAN NOT NULL DEFAULT FALSE",
),
# v0.7.6 — OPS-002 model-to-deployment lineage
("0.7.6", "ALTER TABLE deployments ADD COLUMN previous_deployment_id INTEGER"),
Expand All @@ -230,8 +231,8 @@ async def _run_migrations() -> None:
"ALTER TABLE drift_check_results ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'new'",
),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN owner VARCHAR(255)"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN acknowledged_at DATETIME"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN resolved_at DATETIME"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN acknowledged_at TIMESTAMP"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN resolved_at TIMESTAMP"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN disposition_history JSON"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN threshold_version INTEGER"),
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN threshold_psi FLOAT"),
Expand All @@ -248,18 +249,51 @@ async def _run_migrations() -> None:
("0.7.6", "ALTER TABLE drift_check_results ADD COLUMN error_message TEXT"),
]

def needs_column(sync_conn, table, column):
"""Skip existing columns and absent, retired job tables only."""
inspector = inspect(sync_conn)
if table in {"basic_training_jobs", "advanced_tuning_jobs"} and not inspector.has_table(
table
):
return False
return column not in {item["name"] for item in inspector.get_columns(table)}

applied = 0
for version, ddl in _MIGRATIONS:
# Entries use the documented ALTER TABLE <table> ADD COLUMN <column>
# format; identifiers come exclusively from the static list above.
tokens = ddl.split()
table, column = tokens[2], tokens[5]

try:
# Each migration runs in its own transaction so that a "column
# already exists" error on PostgreSQL does not abort the whole
# batch and crash startup.
async with async_engine.begin() as conn:
if not await conn.run_sync(needs_column, table, column):
continue
await conn.execute(text(ddl))
applied += 1
logger.info("Migration [%s] applied: %s", version, ddl)
except Exception: # noqa: BLE001 - idempotent migration skips existing column
pass # nosec B110 - Column already exists — idempotent migration, safe to skip
except DBAPIError as exc:
# A second startup worker may add the column after inspection.
# Accept only a driver-confirmed duplicate, then verify the schema
# in a new transaction after the failed ALTER has rolled back.
original = exc.orig
duplicate = (
async_engine.dialect.name == "postgresql"
and getattr(original, "sqlstate", None) == "42701"
) or (
async_engine.dialect.name == "sqlite"
and getattr(original, "sqlite_errorcode", None) == 1
and str(original) == f"duplicate column name: {column}"
)
if not duplicate:
raise
async with async_engine.begin() as conn:
columns = await conn.run_sync(
lambda sync_conn, table_name: inspect(sync_conn).get_columns(table_name), table
)
if column not in {item["name"] for item in columns}:
raise
continue
applied += 1
logger.info("Migration [%s] applied: %s", version, ddl)

if applied:
logger.info("✅ %d migration(s) applied", applied)
Expand Down
Loading
Loading