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
113 changes: 79 additions & 34 deletions dataframely/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ def sample(
`overrides`.
ValueError: If `overrides` are specified as a sequence of mappings and
the mappings do not provide the same keys.
ValueError: If the values in `overrides` violate rules that only
reference columns fully provided via `overrides`, i.e. no valid data
frame can be sampled irrespective of the sampled values.
ValueError: If no valid data frame can be found in the configured maximum
number of iterations.

Expand Down Expand Up @@ -257,6 +260,7 @@ def sample(
"`num_rows` is different from the length of the provided overrides."
)
num_rows = values.height
cls._check_sampling_overrides(values, missing_override_indices)
else:
# In case that neither `num_rows` nor `overrides` are provided, fall back to `1`
if num_rows is None:
Expand Down Expand Up @@ -298,7 +302,7 @@ def sample(
# dataframes with length `n`.
values = values.with_row_index(name="__row_index__")

result, used_values, remaining_values = cls._sample_filter(
result, used_values, remaining_values, failure = cls._sample_filter(
num_rows,
g,
previous_result=cls.create_empty(),
Expand All @@ -311,32 +315,19 @@ def sample(
sampling_rounds = 1
while len(result) != num_rows:
if sampling_rounds >= Config.options["max_sampling_iterations"]:
relevant_rows = pl.concat(
[
df
for df in [
result,
used_values.drop("__row_index__"),
remaining_values.drop("__row_index__"),
]
],
how="diagonal", # `used_values` and `remaining_values` only contain columns in `overrides`
)
validation_error = None
try:
cls.validate(relevant_rows)
except ValidationError as e:
validation_error = str(e)
# NOTE: We report the failures of the last sampling iteration (i.e. of
# all previously accepted rows along with the most recently sampled
# rows) as these are the rules that prevented sampling a valid frame.
raise ValueError(
f"After sampling for {Config.options['max_sampling_iterations']} "
f"iterations, {validation_error or 'no valid data frame was found'}. "
f"Consider increasing the maximum number "
f"iterations, {cls._format_failures(failure)}. "
"Consider increasing the maximum number "
"of sampling iterations via `dy.Config` or implement your custom sampling "
"logic. Alternatively, passing predefined value to `overrides` "
"or implementing `_sampling_overrides` for your schema can also "
"help the sampling procedure find a valid data frame."
)
result, used_values, remaining_values = cls._sample_filter(
result, used_values, remaining_values, failure = cls._sample_filter(
num_rows - len(result),
g,
previous_result=result,
Expand All @@ -363,6 +354,36 @@ def sample(
# Row order does not affect the validity of a data frame.
return result # type: ignore

@classmethod
def _check_sampling_overrides(
cls, values: pl.DataFrame, missing_value_indices: dict[str, pl.Series]
) -> None:
"""Check that the overrides do not violate rules that sampling cannot fix."""
fixed_columns = [c for c in values.columns if c not in missing_value_indices]
rules = {
name: rule
for name, rule in cls._validation_rules(with_cast=False).items()
if (
set(rule.expr.meta.root_names()).issubset(fixed_columns)
and (
not rule.expr.meta.has_multiple_outputs()
or set(cls.column_names()).issubset(fixed_columns)
)
)
}
if not rules:
return

failure = cls._failure_info(
values.select(fixed_columns).lazy().pipe(cls._with_evaluated_rules, rules),
Comment thread
borchero marked this conversation as resolved.
Resolved
rules,
)
if failure.counts():
raise ValueError(
"The provided `overrides` can never yield a valid data frame, "
f"{cls._format_failures(failure)}."
)

@classmethod
def _sample_filter(
cls,
Expand All @@ -373,11 +394,12 @@ def _sample_filter(
remaining_values: pl.DataFrame,
override_expressions: list[pl.Expr],
missing_value_indices: dict[str, pl.Series],
) -> tuple[pl.DataFrame, pl.DataFrame, pl.DataFrame]:
) -> tuple[pl.DataFrame, pl.DataFrame, pl.DataFrame, FailureInfo]:
"""Private method to sample a data frame with the schema including subsequent filtering.

Returns:
The filtered data frame, the used values, and the remaining values.
The filtered data frame, the used values, the remaining values, and the
failure info for the rows that were filtered out in this iteration.
"""
sampled = pl.DataFrame(
{
Expand Down Expand Up @@ -425,7 +447,12 @@ def _sample_filter(
rules = cls._validation_rules(with_cast=False)
if not rules:
# We surely included all items from `remaining_values`
return combined_dataframe, remaining_values, remaining_values.head(0)
return (
combined_dataframe,
remaining_values,
remaining_values.head(0),
FailureInfo(lf=pl.LazyFrame(), rule_columns=[]),
)

evaluated = combined_dataframe.lazy().pipe(cls._with_evaluated_rules, rules)
filtered = evaluated.filter(_COLUMN_VALID).select(cls.column_names())
Expand All @@ -434,7 +461,12 @@ def _sample_filter(
if concat_values.height == 0:
# If we didn't provide any values, we can simply return empty data frames
# with the right schema for used and remaining values
return filtered.collect(), concat_values, concat_values
return (
filtered.collect(),
concat_values,
concat_values,
cls._failure_info(evaluated, rules),
)

# NOTE: We can filter `concat_values` using the bitmask from the above filter
# operation as the ordering of the custom values is guaranteed to be the
Expand All @@ -445,6 +477,7 @@ def _sample_filter(
filtered_df,
concat_values.filter(evaluated_df.get_column(_COLUMN_VALID)),
concat_values.filter(~evaluated_df.get_column(_COLUMN_VALID)),
cls._failure_info(evaluated_df.lazy(), rules),
)

@classmethod
Expand Down Expand Up @@ -539,16 +572,7 @@ def validate(
if isinstance(df, pl.DataFrame):
out, failure = cls.filter(df, cast=cast, **kwargs)
if len(failure) > 0:
counts = failure.counts()
raise ValidationError(
format_rule_failures(
list(counts.items()),
failures_from=failure._df.select(counts.keys()),
examples_from=failure.invalid(),
primary_key_columns=cls.primary_key(),
max_examples=Config.options["max_failure_examples"],
)
)
raise ValidationError(cls._format_failures(failure))
return out
else:
lf = df.lazy().pipe(
Expand Down Expand Up @@ -730,6 +754,27 @@ def filter(
return result.collect_all(**kwargs)
return result

@classmethod
def _failure_info(
cls, evaluated: pl.LazyFrame, rules: dict[str, Rule]
) -> FailureInfo:
"""Create the failure info from a frame returned by :meth:`_with_evaluated_rules`."""
return FailureInfo(
lf=evaluated.filter(~pl.col(_COLUMN_VALID)).drop(_COLUMN_VALID),
rule_columns=list(rules.keys()),
)

@classmethod
def _format_failures(cls, failure: FailureInfo) -> str:
counts = failure.counts()
return format_rule_failures(
list(counts.items()),
failures_from=failure._df.select(counts.keys()),
examples_from=failure.invalid(),
primary_key_columns=cls.primary_key(),
max_examples=Config.options["max_failure_examples"],
)

@classmethod
def _with_evaluated_rules(
cls, lf: pl.LazyFrame, rules: dict[str, Rule]
Expand Down
73 changes: 69 additions & 4 deletions tests/schema/test_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,78 @@ def test_sample_invalid_override_values_raises(
with pytest.raises(
ValueError,
match=(
r"After sampling for 100 iterations, 1 rules failed validation:"
r"The provided `overrides` can never yield a valid data frame, "
r"1 rules failed validation:"
rf"\n \* Column '{failed_column}' failed validation for 1 rules:"
rf"\n - '{failed_rule}' failed for {failed_rows} rows."
rf"\n - '{failed_rule}' failed for {failed_rows} rows.$"
),
):
with dy.Config(max_sampling_iterations=100): # speed up the test
MyAdvancedSchema.sample(overrides=overrides)
MyAdvancedSchema.sample(overrides=overrides)


class FailFastSchema(dy.Schema):
id = dy.Int64(primary_key=True)
a = dy.Int64(min=0, max=10)
b = dy.Float64(min=0.0)


@pytest.mark.parametrize(
"schema,overrides,failed_rule,failed_rows",
[
# Column rule; rules on sampled columns must not be reported
(FailFastSchema, [{"id": 1, "a": 4}, {"id": 2, "a": 12}], "max", 1),
# Primary key
(FailFastSchema, [{"id": 1}, {"id": 1}, {"id": 2}], "primary_key", 2),
# Explicit null for non-nullable column
(FailFastSchema, {"id": [1, 2], "a": [1, None]}, "nullability", 1),
# Group rule which only references the overridden `a`; `b` is sampled
(ComplexSchema, {"a": [1, 2, 2]}, "minimum_two_per_a", 1),
# Custom rule with all columns overridden
(CheckSchema, {"a": [1, 2], "b": [0, 3]}, "a_ge_b", 1),
# Aggregating column check without holes
(
create_schema("test", {"a": dy.Int64(check=lambda c: c.sum() > 100)}),
{"a": [1, 2]},
"check",
2,
),
],
)
def test_sample_invalid_overrides_fail_fast(
schema: type[dy.Schema],
overrides: Any,
failed_rule: str,
failed_rows: int,
) -> None:
# A large number of iterations ensures that we fail before sampling
with dy.Config(max_sampling_iterations=1_000_000):
with pytest.raises(
ValueError,
match=(
r"^The provided `overrides` can never yield a valid data frame, "
r"1 rules failed validation:\n[\s\S]*"
rf"'{failed_rule}' failed for {failed_rows} rows.$"
),
):
schema.sample(overrides=overrides)


def test_sample_override_holes_are_not_checked() -> None:
# Missing keys in row-layout overrides are sampled and must not be reported as
# null values.
df = FailFastSchema.sample(overrides=[{"id": 1, "a": 1}, {"id": 2}, {"a": 2}])
FailFastSchema.validate(df)
assert df.get_column("a").to_list()[::2] == [1, 2]


def test_sample_override_check_referencing_other_column() -> None:
# Checks referencing other columns cannot be evaluated on the overrides alone
schema = create_schema(
"test",
{"a": dy.Int64(), "b": dy.Int64(check=lambda c: c >= pl.col("a"))},
)
df = schema.sample(overrides={"b": [2**62, 2**62 + 1]})
schema.validate(df)


def test_sample_empty_override_sequence() -> None:
Expand Down
Loading