diff --git a/docs/concepts/audits.md b/docs/concepts/audits.md index a537927e53..4e73b9b21a 100644 --- a/docs/concepts/audits.md +++ b/docs/concepts/audits.md @@ -265,9 +265,9 @@ MODEL ( ``` #### not_null_proportion, not_null_proportion_non_blocking -Ensures that the specified column's proportion of `NULL` values is no greater than a threshold. +Ensures that the proportion of non-`NULL` values in the specified column is at least `threshold`, a number between 0 and 1. -This example asserts that the `zip` column has no more than 80% `NULL` values: +This example asserts that at least 80% of the `zip` column's values are not `NULL` (that is, no more than 20% are `NULL`): ```sql linenums="1" MODEL ( diff --git a/sqlmesh/core/audit/builtin.py b/sqlmesh/core/audit/builtin.py index e2a5eccb22..f387efe6dd 100644 --- a/sqlmesh/core/audit/builtin.py +++ b/sqlmesh/core/audit/builtin.py @@ -191,7 +191,7 @@ def create_non_blocking_copy(audit: Audit) -> Audit: FROM @this_model WHERE @condition ) AS s -WHERE s.cnt_not_null <= s.cnt_tot * @threshold +WHERE s.cnt_not_null < s.cnt_tot * @threshold """, ) diff --git a/tests/core/test_audit.py b/tests/core/test_audit.py index 4ac44da664..288d6280e0 100644 --- a/tests/core/test_audit.py +++ b/tests/core/test_audit.py @@ -1064,6 +1064,44 @@ def test_not_constant_audit(model: Model): ) +@pytest.mark.parametrize( + "non_null_rows, null_rows, threshold, passes", + [ + (10, 0, 1, True), + (9, 1, 1, False), + (8, 2, 0.8, True), + (7, 3, 0.8, False), + (0, 10, 0, True), + (0, 0, 0.8, True), + ], +) +def test_not_null_proportion_audit( + non_null_rows: int, null_rows: int, threshold: float, passes: bool +): + import duckdb + + model = create_sql_model( + "db.test_model", parse_one("SELECT x FROM db.src"), kind=FullKind(), dialect="duckdb" + ) + rendered_query = model.render_audit_query( + builtin.not_null_proportion_audit, + column=exp.column("x"), + threshold=exp.convert(threshold), + ) + + connection = duckdb.connect() + connection.execute("CREATE SCHEMA db; CREATE TABLE db.test_model (x INT)") + if non_null_rows or null_rows: + connection.execute( + "INSERT INTO db.test_model " + f"SELECT CASE WHEN i < {non_null_rows} THEN i END FROM range({non_null_rows + null_rows}) AS t(i)" + ) + + # threshold is the minimum proportion of non-NULL values; the audit returns a row when it fails + assert (connection.execute(rendered_query.sql("duckdb")).fetchall() == []) == passes + connection.close() + + def test_valid_uuid_audit(model: Model): import duckdb