Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 61 additions & 11 deletions buckaroo/dataflow/styling_core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import copy
import logging
from typing import TYPE_CHECKING, Iterable, Mapping, Sequence, Union, List, Dict, Any, Literal, cast
from typing import TYPE_CHECKING, Callable, Iterable, Iterator, Mapping, NamedTuple, Sequence, Tuple, Union, List, Dict, Any, Literal, cast
from typing_extensions import NotRequired, TypeAlias, TypedDict

import pandas as pd
Expand Down Expand Up @@ -515,6 +515,18 @@ def fix_column_config(cls, col: ColIdentifier, orig_col_name: ColIdentifier, bas
def default_styling(cls, col_name:Union[Iterable[str], str], /) -> ColumnConfig:
return cls.fix_column_config(col_name, col_name, {'displayer_args': {'displayer': 'obj'}})

@classmethod
def _style_column_chain(cls) -> List[Tuple[type, Callable[[ColIdentifier, ColMeta], BaseColumnConfig]]]:
"""Every style_column in the MRO, most specific first, bound to cls."""
chain: List[Tuple[type, Callable[[ColIdentifier, ColMeta], BaseColumnConfig]]] = []
for klass in cls.__mro__:
if 'style_column' not in klass.__dict__ or klass is StylingAnalysis:
# StylingAnalysis' own style_column is the plain obj config that
# default_styling returns, and default_styling ends the fallback chain
continue
chain.append((klass, klass.__dict__['style_column'].__get__(None, cls)))
return chain

@classmethod
def style_column_with_fallback(cls, col:ColIdentifier, col_meta:ColMeta, orig_col_name:ColIdentifier) -> ColumnConfig:
"""Try each style_column in the MRO, most specific first.
Expand All @@ -525,12 +537,7 @@ def style_column_with_fallback(cls, col:ColIdentifier, col_meta:ColMeta, orig_co
Every attempt gets its own copy of col_meta so edits made by a
failing style_column don't leak into the next attempt or the sd.
"""
for klass in cls.__mro__:
if 'style_column' not in klass.__dict__ or klass is StylingAnalysis:
# StylingAnalysis' own style_column is the plain obj config that
# default_styling returns, and default_styling ends the chain below
continue
style_column = klass.__dict__['style_column'].__get__(None, cls)
for klass, style_column in cls._style_column_chain():
try:
return cls.fix_column_config(col, orig_col_name, style_column(col, dict(col_meta)))
except Exception as exc:
Expand Down Expand Up @@ -561,16 +568,16 @@ def get_dfviewer_config(cls, sd:SDType, df:DataFrameLike) -> DFViewerConfig:
'component_config': cls.component_config}

@classmethod
def style_columns(cls, sd:SDType, df:DataFrameLike) -> List[ColumnConfig]:
ret_col_config: List[ColumnConfig] = []
def _columns_to_style(cls, sd:SDType, df:DataFrameLike) -> Iterator[Tuple[ColIdentifier, ColMeta, ColIdentifier]]:
"""(col, col_meta, orig_col_name) for each column style_columns styles, in order.
Hidden columns are left out."""
skip_orig_cols = []
for col, col_meta in sd.items():
#FIXME: why does this come up here too
if col_meta.get('merge_rule', None) == 'hidden':
skip_orig_cols.append(col)

rewrites= dict( old_col_new_col(df))
rewritten_to_orig: Dict[ColIdentifier, ColIdentifier] = {v: k for k, v in rewrites.items()}
rewritten_to_orig: Dict[ColIdentifier, ColIdentifier] = {v: k for k, v in old_col_new_col(df)}
for col, col_meta in sd.items():
if col_meta.get('orig_col_name') in skip_orig_cols or col_meta.get('merge_rule', None) == 'hidden':
continue
Expand All @@ -581,6 +588,13 @@ def style_columns(cls, sd:SDType, df:DataFrameLike) -> List[ColumnConfig]:
if orig_col_name is None:
orig_col_name = rewritten_to_orig.get(col, col)
#it actually gets tuples here
yield col, col_meta, orig_col_name

@classmethod
def style_columns(cls, sd:SDType, df:DataFrameLike) -> List[ColumnConfig]:
ret_col_config: List[ColumnConfig] = []
rewrites= dict( old_col_new_col(df))
for col, col_meta, orig_col_name in cls._columns_to_style(sd, df):
base_style: ColumnConfig = cls.style_column_with_fallback(col, col_meta, orig_col_name)

if 'column_config_override' in col_meta:
Expand All @@ -595,6 +609,42 @@ def style_columns(cls, sd:SDType, df:DataFrameLike) -> List[ColumnConfig]:
return ret_col_config


class StylingFailure(NamedTuple):
"""A column check_styling couldn't style."""
col: ColIdentifier
orig_col_name: ColIdentifier
klass: type # the class whose style_column raised
exc: Exception


def check_styling(klass: type, sd: SDType, df: DataFrameLike) -> List[StylingFailure]:
"""Style each column the way style_columns does, but report failures instead of falling back.

Rendering hides a broken style_column behind its parent's styling and a log line,
so a display class can lose its styling on every column without anyone noticing.
A column fails here when the most specific style_column raises or returns something
that isn't a column config, whether or not a parent's would have worked. Every
column is tried; an empty list means they all styled. The sd isn't modified.
"""
if not (isinstance(klass, type) and issubclass(klass, StylingAnalysis)):
raise TypeError(f"check_styling needs a StylingAnalysis subclass, got {klass!r}")
chain = klass._style_column_chain()
if chain:
owner, first_attempt = chain[0]
else:
# nothing overrides style_column, so rendering goes straight to default_styling
owner = next(k for k in klass.__mro__ if 'default_styling' in k.__dict__)
def first_attempt(col: ColIdentifier, col_meta: ColMeta, /) -> BaseColumnConfig:
return klass.default_styling(col)
failures: List[StylingFailure] = []
for col, col_meta, orig_col_name in klass._columns_to_style(sd, df):
try:
klass.fix_column_config(col, orig_col_name, first_attempt(col, dict(col_meta)))
except Exception as exc:
failures.append(StylingFailure(col, orig_col_name, owner, exc))
return failures


# Stat keys the JS color-map rule reads per column straight off the wire
# payload (``histogram_bins`` / ``histogram_log_bins`` in gridUtils.ts),
# independent of any pinned row.
Expand Down
53 changes: 40 additions & 13 deletions buckaroo/server/xorq_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,11 +265,11 @@ def get_xorq_metadata(xorq_dataflow: XorqServerDataflow, build_dir: str) -> dict
# walk ``col.__class__.__mro__``); acceptable because the project owner is
# trusted (the buckaroo subprocess only reads project paths a host like
# pydata-app explicitly passed in).
_SAFE_BUILTIN_NAMES = ("True", "False", "None", "abs", "min", "max", "round", "sum", "len", "int", "float", "str", "bool", "list", "tuple", "dict", "set", "range", "enumerate", "zip", "map", "filter", "isinstance", "issubclass", "type")
SAFE_BUILTIN_NAMES = ("True", "False", "None", "abs", "min", "max", "round", "sum", "len", "int", "float", "str", "bool", "list", "tuple", "dict", "set", "range", "enumerate", "zip", "map", "filter", "isinstance", "issubclass", "type")


def _safe_builtins() -> dict:
return {n: getattr(builtins, n) for n in _SAFE_BUILTIN_NAMES}
return {n: getattr(builtins, n) for n in SAFE_BUILTIN_NAMES}


def load_project_stat_klasses(project_root) -> list:
Expand Down Expand Up @@ -491,10 +491,7 @@ class found in the resulting namespace that (a) subclasses ``ColAnalysis``
if not display_dir.is_dir():
return []

from buckaroo.pluggable_analysis_framework.col_analysis import ColAnalysis # noqa: PLC0415
from buckaroo.customizations.styling import ( # noqa: PLC0415
DefaultMainStyling, DefaultSummaryStatsStyling, StylingAnalysis)

bases = _display_bases()
klasses: list = []
for path in sorted(display_dir.glob("*.py")):
if path.name.startswith("_"):
Expand All @@ -505,20 +502,50 @@ class found in the resulting namespace that (a) subclasses ``ColAnalysis``
path)
continue
try:
found = _compile_project_display(path, ColAnalysis,
DefaultMainStyling, DefaultSummaryStatsStyling, StylingAnalysis)
klasses.extend(found)
klasses.extend(_compile_project_display(path, *bases))
except Exception as e:
log.warning("project display %s skipped: %s", path, e)
return klasses


def compile_display_source(source: str, name: str) -> list:
"""Exec display source text the way ``load_project_display_klasses``
execs a ``display/<name>.py`` file, and return the display klasses it
defines.

Same sandbox builtins and injected base classes as the loader, but
where the loader logs and skips a file that fails, this raises, so a
host can vet source before writing it into a project. ``name`` plays
the file stem's part and must be a python identifier, as the loader
requires. Loading doesn't style anything; ``check_styling`` in
``buckaroo.dataflow.styling_core`` catches a klass that loads but
can't style a column.
"""
if not name.isidentifier():
raise ValueError(
f"display name {name!r} is not a valid python identifier; "
"load_project_display_klasses would skip it")
return _exec_display_source(source, name, name, *_display_bases())


def _display_bases() -> tuple:
"""ColAnalysis and the styling classes a display file can subclass
without importing them."""
from buckaroo.pluggable_analysis_framework.col_analysis import ColAnalysis # noqa: PLC0415
from buckaroo.customizations.styling import ( # noqa: PLC0415
DefaultMainStyling, DefaultSummaryStatsStyling, StylingAnalysis)
return ColAnalysis, DefaultMainStyling, DefaultSummaryStatsStyling, StylingAnalysis


def _compile_project_display(path: Path, ColAnalysis, *extra_bases):
"""Exec one display file and return all ColAnalysis subclasses with
``df_display_name`` found in its namespace. Raises on syntax errors
so the loader can log-and-skip. Returns an empty list when a valid
file defines no qualifying classes (not an error)."""
source = path.read_text()
return _exec_display_source(path.read_text(), str(path.stem), str(path), ColAnalysis, *extra_bases)


def _exec_display_source(source: str, name: str, filename: str, ColAnalysis, *extra_bases) -> list:
safe = _safe_builtins()
# __build_class__ is the CPython hook that executes class bodies; without
# it, any ``class Foo:`` statement raises NameError. Adding it opens more
Expand All @@ -530,21 +557,21 @@ def _compile_project_display(path: Path, ColAnalysis, *extra_bases):
safe["__build_class__"] = __build_class__
safe["classmethod"] = classmethod
safe["staticmethod"] = staticmethod
# super() is a builtin but not in _SAFE_BUILTIN_NAMES; without it,
# super() is a builtin but not in SAFE_BUILTIN_NAMES; without it,
# calling super() inside any method succeeds at class-definition time
# but raises NameError at render time — the common override pattern
# (subclass DefaultMainStyling, call super().style_column(...)) would
# silently break.
safe["super"] = super
globs: dict = {"__builtins__": safe, "__name__": str(path.stem), "ColAnalysis": ColAnalysis}
globs: dict = {"__builtins__": safe, "__name__": name, "ColAnalysis": ColAnalysis}
for base in extra_bases:
globs[base.__name__] = base

# Track identities of pre-injected classes so we don't return them as
# user-defined klasses — they're context for the file, not the output.
injected_ids = {id(ColAnalysis)} | {id(b) for b in extra_bases}

exec(compile(source, str(path), "exec"), globs)
exec(compile(source, filename, "exec"), globs)

found = []
for obj in globs.values():
Expand Down
72 changes: 72 additions & 0 deletions tests/unit/dataflow/styling_core_test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import copy
from typing import Dict, List
import pandas as pd
from buckaroo.dataflow import styling_core
from buckaroo.dataflow.styling_core import ColumnConfig, DFViewerConfig, NormalColumnConfig, PartialColConfig, StylingAnalysis, merge_sd_overrides, rewrite_override_col_references
from buckaroo.customizations.styling import (DefaultMainStyling, _formatted_char_count, estimate_min_width_px, _HISTOGRAM_MIN_PX, _MIN_COL_PX)
from buckaroo.ddd_library import get_basic_df2, get_multiindex_index_df, get_multiindex_index_multiindex_with_names_cols_df, get_multiindex_index_with_names_multiindex_cols_df, get_multiindex_with_names_both, get_multiindex_with_names_index_df, get_multiindex_cols_df, get_multiindex_with_names_cols_df, get_tuple_cols_df, get_multiindex_int_cols_df, get_multiindex_int_levels_df, get_multiindex_int_names_df, get_multiindex_partly_named_index_df
Expand Down Expand Up @@ -576,3 +577,74 @@ def test_overridden_default_styling_is_used_as_the_last_resort() -> None:
{'a': {'orig_col_name': 'foo'}}, pd.DataFrame({'foo': [1]}))
assert col_config == [{'col_name': 'a', 'header_name': 'foo',
'displayer_args': {'displayer': 'string', 'max_length': 5}}]


class RaisingOnStringStyling(DefaultMainStyling):
@classmethod
def style_column(cls, col, column_metadata):
if column_metadata.get('_type') == 'string':
raise NameError("boom")
return super().style_column(col, column_metadata)


class InheritsRaisingStyling(RaisingMainStyling):
"""Defines no style_column of its own, so RaisingMainStyling's is the one that runs."""


def test_check_styling_is_empty_when_every_column_styles() -> None:
assert styling_core.check_styling(DefaultMainStyling, FALLBACK_SD, FALLBACK_DF) == []
assert styling_core.check_styling(ColoredMainStyling, FALLBACK_SD, FALLBACK_DF) == []


def test_check_styling_reports_every_failing_column() -> None:
"""No fallback and no stopping at the first failure: each column gets its own entry."""
failures = styling_core.check_styling(RaisingMainStyling, FALLBACK_SD, FALLBACK_DF)
assert [(f.col, f.orig_col_name, f.klass) for f in failures] == [
('a', 'foo', RaisingMainStyling), ('b', 'bar', RaisingMainStyling)]
assert all(isinstance(f.exc, NameError) for f in failures)


def test_check_styling_reports_only_the_columns_that_fail() -> None:
failures = styling_core.check_styling(RaisingOnStringStyling, FALLBACK_SD, FALLBACK_DF)
assert [(f.col, f.orig_col_name) for f in failures] == [('b', 'bar')]


def test_check_styling_names_the_most_specific_style_column() -> None:
"""A failure is the most specific style_column raising, even when a parent's would have worked."""
failures = styling_core.check_styling(RaisingColoredStyling, FALLBACK_SD, FALLBACK_DF)
assert {f.klass for f in failures} == {RaisingColoredStyling}
failures = styling_core.check_styling(InheritsRaisingStyling, FALLBACK_SD, FALLBACK_DF)
assert {f.klass for f in failures} == {RaisingMainStyling}


def test_check_styling_counts_a_non_dict_as_a_failure() -> None:
failures = styling_core.check_styling(NoneReturningMainStyling, FALLBACK_SD, FALLBACK_DF)
assert [f.col for f in failures] == ['a', 'b']


def test_check_styling_leaves_the_sd_alone() -> None:
sd = copy.deepcopy(FALLBACK_SD)
assert len(styling_core.check_styling(MutateThenRaiseStyling, sd, FALLBACK_DF)) == 2
assert sd == FALLBACK_SD


def test_check_styling_skips_hidden_columns() -> None:
"""Hidden columns are never styled for display, so they can't fail."""
sd: SDType = {**FALLBACK_SD, 'b': {**FALLBACK_SD['b'], 'merge_rule': 'hidden'}}
assert styling_core.check_styling(RaisingOnStringStyling, sd, FALLBACK_DF) == []


class RaisingDefaultOnlyStyling(StylingAnalysis):
"""Overrides only default_styling, which is where rendering starts for this class."""
requires_summary = []

@classmethod
def default_styling(cls, col_name, /):
raise NameError("boom")


def test_check_styling_checks_default_styling_when_nothing_overrides_style_column() -> None:
failures = styling_core.check_styling(RaisingDefaultOnlyStyling, FALLBACK_SD, FALLBACK_DF)
assert [(f.col, f.klass) for f in failures] == [
('a', RaisingDefaultOnlyStyling), ('b', RaisingDefaultOnlyStyling)]
assert styling_core.check_styling(StylingAnalysis, FALLBACK_SD, FALLBACK_DF) == []
Loading
Loading