ExpectColumnValuesToBeIncreasing/Decreasing fail silently on a pandas datetime column
Describe the bug
ExpectColumnValuesToBeIncreasing and ExpectColumnValuesToBeDecreasing both state in their docstring:
By default, this expectation only works for numeric or datetime data.
On a pandas datetime column they evaluate nothing. The validation comes back success=False with an empty result, and the real error is buried in exception_info keyed by MetricConfigurationID, so it reads as "the data failed the expectation" rather than "the metric raised".
On a strictly increasing datetime column:
success: False
result: {}
exception_info keys: ["MetricConfigurationID(metric_name='column_values.increasing.condition', metric_domain_kwargs_id='82b09...', metric_value_kwargs_id='strictly=False')"]The traceback, with catch_exceptions=False:
TypeError: Invalid value '1' for dtype 'timedelta64[us]'
at great_expectations/execution_engine/execution_engine.py:577The cause is in great_expectations/expectations/metrics/column_map_metrics/column_values_increasing.py:38 (and the mirror at column_values_decreasing.py:37):
series_diff = temp_column.diff()
# The first element is null, so it gets a bye and is always treated as True
series_diff[series_diff.isnull()] = 1 # <-- int into a timedelta64 seriescolumn.diff() of a datetime column is timedelta64, so writing the int 1 into it is a dtype violation.
This is not specific to pandas 3. With pandas==2.2.3 (the project declares pandas>=1.3.0) the same line raises a FutureWarning ("Setting an item of incompatible dtype is deprecated... Value '1' has dtype incompatible with timedelta64[ns]"), upcasts to object, and the comparison on the next line fails instead:
TypeError: '>=' not supported between instances of 'Timedelta' and 'int'Same break, different line.
Two things suggest this is an oversight rather than a limitation. The Spark provider of the same class handles datetime on purpose (if isinstance(column_metadata["type"], (pyspark.types.TimestampType, pyspark.types.DateType)): diff = F.datediff(...)), so pandas is the only one of the two engines without that care. And there is no test covering it: the existing unit tests for these metrics use [1, 2, 4, 5, 3, 6, 7], and there was no integration test file for either expectation.
Great Expectations version
1.23.1+7.g8deddc7 (develop at 8deddc7)
Python version
3.12.13
Execution engine / data source
pandas
Minimal reproduction
import pandas as pd
import great_expectations as gx
ctx = gx.get_context(mode="ephemeral")
df = pd.DataFrame({"event_at": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"])})
batch = (
ctx.data_sources.add_pandas("p")
.add_dataframe_asset("a")
.add_batch_definition_whole_dataframe("b")
.get_batch(batch_parameters={"dataframe": df})
)
r = batch.validate(gx.expectations.ExpectColumnValuesToBeIncreasing(column="event_at"))
print(r.success) # False, on a strictly increasing column
print(r.result) # {}ExpectColumnValuesToBeDecreasing fails the same way on a descending datetime column.
Additional context
I have a fix and integration tests ready: compare against a zero taken from the diff's own dtype (pd.Timedelta(0) for timedelta, 0 otherwise) and keep the first row's bye through | series_diff.isnull() instead of writing into the series, which keeps the numeric behaviour byte-identical. With it, the reproduction above returns success=True with a full result, and 7 new integration cases (increasing, strictly, a step backwards, ties, and the decreasing mirrors) go from 7 failed to 7 passed, with +7 passes and no new failures across tests/integration/data_sources_and_expectations/expectations.
Before opening that PR I need to settle the CLA on my side, since AGENTS.md is explicit that it is a legal affirmation by the human contributor. Happy to send it as soon as that is sorted, or for a maintainer to take the fix from here if that is faster.
Source: fivetran/great_expectations