id: gx-data-quality-gate
namespace: company.team
inputs:
- id: sample_url
type: URI
displayName: Sample CSV (manual runs)
description: CSV validated when the flow is run manually instead of by the S3 trigger.
defaults: https://huggingface.co/datasets/kestra/datasets/raw/main/csv/orders.csv
- id: inject_bad_rows
type: BOOL
displayName: Inject bad rows (manual runs)
description: Validate a second copy of the sample with a duplicate id, an
invalid email, a negative price and a zero quantity, so you can watch the
gate reject it.
defaults: true
- id: load_to_postgres
type: BOOL
displayName: Load passing files on manual runs
description: S3-triggered runs always load passing files. Enable this to also
load them on manual runs (requires the Postgres secrets).
defaults: false
- id: notify_slack
type: BOOL
displayName: Send Slack alerts on manual runs
description: S3-triggered runs always alert on failures. Enable this to also
alert on manual runs (requires SLACK_WEBHOOK_URL).
defaults: false
variables:
bucket: my-data-landing
region: eu-west-1
landing_prefix: landing/orders/
processed_prefix: processed/orders/
quarantine_prefix: quarantine/orders/
target_table: public.orders
tasks:
- id: download_sample
type: io.kestra.plugin.core.http.Download
description: On manual runs, fetch the sample CSV that stands in for files
arriving in S3.
runIf: "{{ trigger is not defined }}"
uri: "{{ inputs.sample_url }}"
- id: plan_batch
type: io.kestra.plugin.core.output.OutputValues
description: Build the list of files to validate, either the new S3 objects or
the demo files, and record whether the run came from S3.
values:
triggered: "{{ trigger is defined }}"
files: >-
{{ trigger is defined ? trigger.objects : (inputs.inject_bad_rows ? [
{'key': vars.landing_prefix ~ 'orders.csv', 'uri':
outputs.download_sample.uri, 'inject': false}, {'key':
vars.landing_prefix ~ 'orders_with_bad_rows.csv', 'uri':
outputs.download_sample.uri, 'inject': true} ] : [ {'key':
vars.landing_prefix ~ 'orders.csv', 'uri': outputs.download_sample.uri,
'inject': false} ]) }}
- id: validate_files
type: io.kestra.plugin.core.flow.Loop
description: Validate every file in parallel and route it based on its Great
Expectations result.
values: "{{ outputs.plan_batch.values.files }}"
concurrencyLimit: 4
tasks:
- id: validate
type: io.kestra.plugin.scripts.python.Script
description: Run the expectation suite against the file with Great Expectations
and output the verdict and the failing expectations.
containerImage: python:3.12-slim
beforeCommands:
- pip install -q --root-user-action=ignore great_expectations==1.23.2
env:
INJECT_BAD_ROWS: "{{ fromJson(item.value).inject ?? false }}"
FILE_KEY: "{{ fromJson(item.value).key }}"
GX_ANALYTICS_ENABLED: "false"
inputFiles:
data.csv: "{{ fromJson(item.value).uri }}"
suite.json: |
{
"name": "orders",
"expectations": [
{"type": "expect_table_columns_to_match_ordered_list", "kwargs": {"column_list": ["order_id", "customer_name", "customer_email", "product_id", "price", "quantity", "total"]}},
{"type": "expect_column_values_to_not_be_null", "kwargs": {"column": "order_id"}},
{"type": "expect_column_values_to_be_unique", "kwargs": {"column": "order_id"}},
{"type": "expect_column_values_to_match_regex", "kwargs": {"column": "customer_email", "regex": "^[^@\\s]+@[^@\\s]+\\.[A-Za-z]{2,}$"}},
{"type": "expect_column_values_to_not_be_null", "kwargs": {"column": "price"}},
{"type": "expect_column_values_to_be_between", "kwargs": {"column": "price", "min_value": 0, "strict_min": true}},
{"type": "expect_column_values_to_not_be_null", "kwargs": {"column": "quantity"}},
{"type": "expect_column_values_to_be_between", "kwargs": {"column": "quantity", "min_value": 1, "max_value": 100}}
]
}
script: |
import json
import os
import great_expectations as gx
import pandas as pd
from great_expectations.expectations.expectation_configuration import ExpectationConfiguration
try:
df = pd.read_csv("data.csv")
except Exception as error:
outputs = {"passed": False, "rows": 0, "evaluated": 0, "failed_count": 0, "failed": "", "summary": f"unreadable CSV: {error}"}
print(f"{os.environ['FILE_KEY']}: FAILED {outputs}")
print("::" + json.dumps({"outputs": outputs}) + "::")
raise SystemExit(0)
if os.environ["INJECT_BAD_ROWS"].lower() == "true":
bad_rows = pd.DataFrame([
{"order_id": 1, "customer_name": "Duplicate Id", "customer_email": "dup@example.com", "product_id": 1, "price": 10.0, "quantity": 1, "total": 10.0},
{"order_id": 9001, "customer_name": "Bad Email", "customer_email": "not-an-email", "product_id": 2, "price": 10.0, "quantity": 1, "total": 10.0},
{"order_id": 9002, "customer_name": "Negative Price", "customer_email": "neg@example.com", "product_id": 3, "price": -5.0, "quantity": 1, "total": -5.0},
{"order_id": 9003, "customer_name": "Bulk Typo", "customer_email": "bulk@example.com", "product_id": 4, "price": 10.0, "quantity": 500, "total": 5000.0},
])
df = pd.concat([df, bad_rows], ignore_index=True)
with open("suite.json") as f:
spec = json.load(f)
suite = gx.ExpectationSuite(name=spec["name"])
for expectation in spec["expectations"]:
suite.add_expectation_configuration(
ExpectationConfiguration(type=expectation["type"], kwargs=expectation["kwargs"])
)
context = gx.get_context(mode="ephemeral")
batch_definition = (
context.data_sources.add_pandas("files")
.add_dataframe_asset("file")
.add_batch_definition_whole_dataframe("whole_file")
)
result = batch_definition.get_batch(batch_parameters={"dataframe": df}).validate(suite)
failed = []
for r in result.results:
if not r.success:
column = r.expectation_config.kwargs.get("column", "table")
unexpected = r.result.get("unexpected_count")
detail = f" ({unexpected} rows)" if unexpected is not None else ""
failed.append(f"{r.expectation_config.type} on {column}{detail}")
outputs = {
"passed": result.success,
"rows": len(df),
"evaluated": result.statistics["evaluated_expectations"],
"failed_count": len(failed),
"failed": "; ".join(failed),
"summary": f"{len(failed)} of {result.statistics['evaluated_expectations']} expectations failed: " + "; ".join(failed),
}
print(f"{os.environ['FILE_KEY']}: {'PASSED' if result.success else 'FAILED'} {outputs}")
print("::" + json.dumps({"outputs": outputs}) + "::")
- id: route_file
type: io.kestra.plugin.core.flow.If
description: Load and archive files that pass; quarantine and report files that
fail.
condition: "{{ outputs.validate.vars.passed }}"
then:
- id: load_to_postgres
type: io.kestra.plugin.jdbc.postgresql.CopyIn
description: Append the validated rows to the target table.
runIf: "{{ (outputs.plan_batch.values.triggered | string) == 'true' or
inputs.load_to_postgres }}"
url: "{{ secret('POSTGRES_URL') }}"
username: "{{ secret('POSTGRES_USER') }}"
password: "{{ secret('POSTGRES_PASSWORD') }}"
format: CSV
header: true
table: "{{ vars.target_table }}"
from: "{{ fromJson(item.value).uri }}"
- id: archive_file
type: io.kestra.plugin.aws.s3.Upload
description: Keep a copy of the loaded file under the processed prefix.
runIf: "{{ (outputs.plan_batch.values.triggered | string) == 'true' }}"
accessKeyId: "{{ secret('AWS_ACCESS_KEY_ID') }}"
secretKeyId: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
region: "{{ vars.region }}"
bucket: "{{ vars.bucket }}"
key: "{{ vars.processed_prefix ~ (execution.startDate | date('yyyy-MM-dd')) ~
'/' ~ execution.id ~ '_' ~ (fromJson(item.value).key | split('/')
| last) }}"
from: "{{ fromJson(item.value).uri }}"
else:
- id: log_failure
type: io.kestra.plugin.core.log.Log
description: Record why the file was rejected, even when Slack is off.
level: WARN
message: "Rejected {{ fromJson(item.value).key }}: {{
outputs.validate.vars.summary }}"
- id: quarantine_file
type: io.kestra.plugin.aws.s3.Upload
description: Copy the rejected file to the quarantine prefix for inspection.
runIf: "{{ (outputs.plan_batch.values.triggered | string) == 'true' }}"
accessKeyId: "{{ secret('AWS_ACCESS_KEY_ID') }}"
secretKeyId: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
region: "{{ vars.region }}"
bucket: "{{ vars.bucket }}"
key: "{{ vars.quarantine_prefix ~ (execution.startDate | date('yyyy-MM-dd')) ~
'/' ~ execution.id ~ '_' ~ (fromJson(item.value).key | split('/')
| last) }}"
from: "{{ fromJson(item.value).uri }}"
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the data team which expectations the file failed.
runIf: "{{ (outputs.plan_batch.values.triggered | string) == 'true' or
inputs.notify_slack }}"
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": {{ ('Data quality gate rejected `' ~ fromJson(item.value).key ~ '`: ' ~ outputs.validate.vars.summary ~ '. Execution: ' ~ execution.id) | toJson }}
}
errors:
- id: alert_failed_run
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert when the run itself fails, because the trigger has already
removed the files from the landing prefix.
runIf: "{{ trigger is defined or inputs.notify_slack }}"
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": {{ ('Data quality gate execution ' ~ execution.id ~ ' failed before routing all files. They are kept in Kestra internal storage: fix the cause and restart the execution.') | toJson }}
}
triggers:
- id: new_files
type: io.kestra.plugin.aws.s3.Trigger
description: Start the gate when new CSV files land under the landing prefix.
Enable after setting the AWS secrets.
disabled: true
interval: PT1M
accessKeyId: "{{ secret('AWS_ACCESS_KEY_ID') }}"
secretKeyId: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
region: "{{ vars.region }}"
bucket: "{{ vars.bucket }}"
prefix: "{{ vars.landing_prefix }}"
regexp: ".*\\.csv$"
filter: FILES
maxKeys: 20
action: DELETE