Skip to content
Merged

0823 #167

Show file tree
Hide file tree
Changes from 12 commits
Commits
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
  •  
  •  
  •  
6 changes: 5 additions & 1 deletion backend/data_ingestion/connectors/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import polars as pl

from backend.config import get_settings
from backend.pagination import MAX_SAMPLE_ROWS, validate_limit

from .base import BaseConnector

Expand Down Expand Up @@ -187,8 +188,11 @@ async def fetch_data(self, limit: int | None = None) -> pl.DataFrame:

CSV and Parquet satisfy a bounded request through a lazy ``head`` so a
preview never materialises the file. Every other case reads the file in
full and truncates afterwards.
full and truncates afterwards. Explicit limits must be between 1 and
50,000; ``None`` keeps the full-file ingestion operation.
"""
if limit is not None:
validate_limit(limit, MAX_SAMPLE_ROWS)
lazy_head = self._try_lazy_head(limit=limit)
if lazy_head is not None:
return lazy_head
Expand Down
17 changes: 11 additions & 6 deletions backend/data_ingestion/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
caller. Each site carries a ``KNOWN-GAP`` comment to that effect.
"""

from typing import Annotated

from fastapi import (
APIRouter,
BackgroundTasks,
Expand All @@ -24,6 +26,7 @@

from backend.config import get_settings
from backend.middleware.rate_limiter import limiter
from backend.pagination import MAX_SAMPLE_ROWS, validate_query_limit

from .dependencies import get_data_service
from .schemas.ingestion import (
Expand All @@ -43,14 +46,15 @@

@sources_router.get("/sources", response_model=DataSourceListResponse)
async def list_sources(
limit: int | None = None,
skip: int = 0,
limit: Annotated[int | None, Query(ge=1)] = None,
skip: Annotated[int, Query(ge=0)] = 0,
service: DataIngestionService = Depends(get_data_service),
):
"""List all available data sources."""
"""List sources with a positive limit up to MAX_PAGE_SIZE and a non-negative skip."""
# KNOWN-GAP: Auth not implemented yet — all sources are visible.
# TODO(auth): Replace None with real user ID from auth dependency.
effective_limit = limit if limit is not None else get_settings().DEFAULT_PAGE_SIZE
validate_query_limit(effective_limit, get_settings().MAX_PAGE_SIZE)
sources = await service.list_sources(user_id=None, limit=effective_limit, skip=skip)
return DataSourceListResponse(sources=[DataSourceRead.model_validate(s) for s in sources])

Expand All @@ -76,11 +80,12 @@ async def get_source(source_id: str, service: DataIngestionService = Depends(get
@sources_router.get("/sources/{source_id}/sample", response_model=DataSourceSampleResponse)
async def get_source_sample(
source_id: str,
limit: int | None = None,
limit: Annotated[int | None, Query(ge=1, le=MAX_SAMPLE_ROWS)] = None,
service: DataIngestionService = Depends(get_data_service),
):
"""Get a sample of data from the source."""
"""Get up to 50,000 source rows; omitted limits use DEFAULT_SAMPLE_ROWS."""
effective_limit = limit if limit is not None else get_settings().DEFAULT_SAMPLE_ROWS
validate_query_limit(effective_limit, MAX_SAMPLE_ROWS)
data = await service.get_sample(source_id, effective_limit)
return DataSourceSampleResponse(data=data)

Expand All @@ -98,7 +103,7 @@ async def delete_source(source_id: str, service: DataIngestionService = Depends(
async def export_source_data(
source_id: str,
format: str = Query("csv", pattern="^(csv|parquet)$"), # noqa: A002 # pylint: disable=redefined-builtin
limit: int = Query(1000, ge=1, le=50_000),
limit: int = Query(1000, ge=1, le=MAX_SAMPLE_ROWS),
service: DataIngestionService = Depends(get_data_service),
) -> Response:
"""Export data from a source as CSV or Parquet."""
Expand Down
2 changes: 1 addition & 1 deletion backend/data_ingestion/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ def _handle_decimal_like(obj: Any) -> Any:
if hasattr(obj, "__float__"):
try:
value = float(obj)
return None if value != value else value
return value if math.isfinite(value) else None
except Exception: # noqa: BLE001 - capability probe, next handler follows
logger.debug("float conversion failed for %s", type(obj))
return JSONSafeSerializer._NOT_HANDLED
Expand Down
5 changes: 4 additions & 1 deletion backend/data_ingestion/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from backend.data_ingestion.tasks import ingest_data_task
from backend.database.models import DataSource
from backend.exceptions.core import ForbiddenException, ResourceNotFoundException, SkyulfException
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

Expand Down Expand Up @@ -65,6 +66,7 @@ async def list_sources(
) -> Sequence[DataSource]:
"""List all data sources."""
effective_limit = limit if limit is not None else get_settings().DEFAULT_PAGE_SIZE
validate_page_bounds(effective_limit, skip)
query = select(DataSource)
if user_id:
query = query.where(DataSource.created_by == user_id)
Expand Down Expand Up @@ -296,8 +298,9 @@ async def _route_sample(
return []

async def get_sample(self, source_id: int | str, limit: int | None = None) -> list[dict]:
"""Get a sample of data from the source."""
"""Get 1 to 50,000 source rows, validating the limit before source lookup."""
effective_limit = limit if limit is not None else get_settings().DEFAULT_SAMPLE_ROWS
validate_limit(effective_limit, MAX_SAMPLE_ROWS)

source = await self.get_source(source_id)
if not source:
Expand Down
9 changes: 8 additions & 1 deletion backend/database/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from collections.abc import AsyncGenerator

from sqlalchemy import create_engine
from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
Expand Down Expand Up @@ -58,7 +59,13 @@ async def init_db() -> None:
echo=settings.DB_ECHO,
future=True,
# SQLite specific settings for async
poolclass=StaticPool,
# File databases need distinct connections for concurrent
# transactions. Only memory databases must share one connection.
**(
{"poolclass": StaticPool}
if make_url(settings.DATABASE_URL).database in (None, "", ":memory:")
else {}
),
connect_args={
"check_same_thread": False,
# Enable WAL mode for better concurrency
Expand Down
2 changes: 2 additions & 0 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
validation_exception_handler,
)
from backend.health.routes import router as health_router
from backend.middleware.default_rate_limit import DefaultRateLimitMiddleware
from backend.middleware.error_handler import ErrorHandlerMiddleware
from backend.middleware.logging import LoggingMiddleware
from backend.middleware.rate_limiter import limiter
Expand Down Expand Up @@ -303,6 +304,7 @@ def create_app() -> FastAPI:
RateLimitExceeded,
_rate_limit_exceeded_handler, # ty: ignore[invalid-argument-type]
)
app.add_middleware(DefaultRateLimitMiddleware)

# Add middleware (order matters!)
_add_middleware(app, settings)
Expand Down
77 changes: 77 additions & 0 deletions backend/middleware/default_rate_limit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Apply SlowAPI defaults using actual routing order and transparent ASGI delivery."""

from collections.abc import Callable
from typing import Any

from fastapi import routing as fastapi_routing
from slowapi import Limiter
from slowapi.middleware import _get_route_name, async_check_limits
from starlette.datastructures import MutableHeaders
from starlette.requests import Request
from starlette.routing import Match
from starlette.types import ASGIApp, Message, Receive, Scope, Send


def _first_route_handler(app: Any, scope: Scope) -> Callable | None:
"""Match Starlette's first full route, leaving mounted applications to themselves."""
# Newer FastAPI includes routers lazily; its public iterator supplies the
# effective prefixes. Older versions already expose a flat route list.
route_contexts = getattr(fastapi_routing, "iter_route_contexts", iter)
for route in route_contexts(app.routes):
if route.matches(scope)[0] == Match.FULL:
return getattr(route, "endpoint", None)
return None


def _skip_default_check(limiter: Limiter, handler: Callable | None) -> bool:
"""Let explicit decorators own static/dynamic limits and exemptions."""
if not limiter.enabled or handler is None:
return True
name = _get_route_name(handler)
return any(
name in routes
for routes in (limiter._exempt_routes, limiter._route_limits, limiter._dynamic_route_limits)
)


class DefaultRateLimitMiddleware:
"""Enforce configured defaults without consuming streaming bodies or WebSockets.

SlowAPI's bundled middleware keeps the last matching route, which selects
the SPA catch-all over an earlier API route. Its ASGI responder also emits
response-start for each body chunk. Keep routing and delivery here while
retaining SlowAPI's counter, failure-handler and header behavior.
"""

def __init__(self, app: ASGIApp) -> None:
"""Store the downstream ASGI application without sharing request state."""
self.app = app

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
"""Check HTTP defaults once before reaching the endpoint."""
if scope["type"] != "http":
await self.app(scope, receive, send)
return

app = scope["app"]
limiter = app.state.limiter
handler = _first_route_handler(app, scope)
if _skip_default_check(limiter, handler):
await self.app(scope, receive, send)
return

request = Request(scope, receive=receive, send=send)
response, inject_headers = await async_check_limits(limiter, request, handler, app)
if response is not None:
await response(scope, receive, send)
return

async def send_with_headers(message: Message) -> None:
"""Decorate the single response start while forwarding body frames unchanged."""
if message["type"] == "http.response.start" and inject_headers:
view_limit = getattr(request.state, "view_rate_limit", None)
if view_limit is not None:
limiter._inject_asgi_headers(MutableHeaders(scope=message), view_limit)
await send(message)

await self.app(scope, receive, send_with_headers)
32 changes: 30 additions & 2 deletions backend/ml_pipeline/_execution/_schema_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,28 @@

from skyulf.preprocessing import SkyulfSchema

from .graph_utils import _discover_ancestors_bfs
from .schemas import NodeConfig, PipelineConfig

# Param keys whose values are column names (str or list of str).
_STRING_REF_KEYS = ("target", "target_column", "column", "label_column")
_STRING_REF_KEYS = (
"target",
"target_column",
"column",
"label_column",
"lat1_col",
"lon1_col",
"lat2_col",
"lon2_col",
)
_LIST_REF_KEYS = (
"columns",
"feature_columns",
"numeric_columns",
"categorical_columns",
)
# Param keys whose values are dicts keyed by column name.
_DICT_KEY_REF_KEYS = ("column_types", "column_mapping", "rename_map")
_DICT_KEY_REF_KEYS = ("column_types", "column_mapping", "rename_map", "bounds")

# Some step types have column-ref params that are genuinely optional:
# the pipeline runs fine even when the column is absent upstream.
Expand Down Expand Up @@ -120,6 +130,22 @@ def _upstream_schema(
return predicted.get(upstream_id)


def _feature_input_schema(
node: NodeConfig, schema: SkyulfSchema, node_map: dict[str, NodeConfig]
) -> SkyulfSchema:
"""Exclude separated labels for controls whose Core appliers operate only on X."""
if node.step_type not in {"ManualBounds", "GeoDistance"}:
return schema
ancestors = _discover_ancestors_bfs(node.node_id, node_map)
targets = (
node_map[node_id].params.get("target_column")
for node_id in ancestors
if node_id in node_map
and node_map[node_id].step_type in {"feature_target_split", "TrainTestSplitter", "Split"}
)
return schema.drop(target for target in targets if isinstance(target, str))


def find_broken_references(
config: PipelineConfig,
predicted_schemas: dict[str, SkyulfSchema | None],
Expand All @@ -137,11 +163,13 @@ def find_broken_references(
Nodes whose upstream schema is unknown (``None``) are skipped.
"""
broken: list[dict[str, Any]] = []
node_map = {node.node_id: node for node in config.nodes}

for node in config.nodes:
upstream = _upstream_schema(node, predicted_schemas)
if upstream is None:
continue
upstream = _feature_input_schema(node, upstream, node_map)
upstream_id = node.inputs[0] if node.inputs else None
step = node.step_type.value if hasattr(node.step_type, "value") else str(node.step_type)
optional_keys: set[str] = _OPTIONAL_PARAM_KEYS.get(step, set())
Expand Down
3 changes: 3 additions & 0 deletions backend/ml_pipeline/_execution/advanced_tuning_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from sqlalchemy.orm import Session

from backend.config import get_settings
from backend.data_ingestion.serialization import JSONSafeSerializer
from backend.database.models import TrainingJob
from backend.ml_pipeline._execution.graph_utils import (
determine_search_strategy,
Expand Down Expand Up @@ -170,6 +171,8 @@ async def cancel_tuning_job(session: AsyncSession, job_id: str) -> bool:

@staticmethod
def _update_tuning_result(job: TrainingJob, result: dict[str, Any]):
"""Persist a JSON-safe tuning result copy, including dedicated score columns."""
result = JSONSafeSerializer.clean_for_json(result)
if "best_params" in result:
job.best_params = result["best_params"]
if "best_score" in result:
Expand Down
3 changes: 3 additions & 0 deletions backend/ml_pipeline/_execution/basic_training_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from sqlalchemy.orm import Session

from backend.config import get_settings
from backend.data_ingestion.serialization import JSONSafeSerializer
from backend.database.models import TrainingJob
from backend.ml_pipeline._execution.graph_utils import (
extract_job_details,
Expand Down Expand Up @@ -165,6 +166,8 @@ async def cancel_training_job(session: AsyncSession, job_id: str) -> bool:

@staticmethod
def _update_training_result(job: TrainingJob, result: dict[str, Any]):
"""Persist a JSON-safe result copy without changing the worker's payload."""
result = JSONSafeSerializer.clean_for_json(result)
if "metrics" in result:
job.metrics = result["metrics"]
if "artifact_uri" in result:
Expand Down
Loading
Loading