Data’s Inferno: 7 Circles of Data Testing Hell with Airflow
By: Wb Advanced Analytics
Tags: Testing, Spark, Continuous Integration, Data Engineering, Airflow

How to use

Integrating this layer requires a number of steps (assuming you already have a CI environment set up):

In your CI, setup a task/stage that has pytest , airflow , and coverage available Define a conftest.py file in which you add any custom Airflow configuration you might need. For every file in your repository (get the paths to these files yourself), run the following code:

assert any(

isinstance(var, af_models.DAG)

for var in vars(module).values()

)

This code verifies that the file in which you claim to have defined a DAG actually contains a valid Airflow DAG.

Circle 2: Split Ingestion from Deployment

In an environment where you ingest data from multiple sources that end up in your project, you often have ETL specifically for your ingestion that can be logically separated from the ETL that goes into your project. At WBAA we do this by creating one Airflow DAG per data source and one DAG that does the ETL for our project. There were several reasons for us to do this:

If your ingestion fails, you do not want your project ETL to fail immediately. It might be perfectly fine that (one of) your data sources is not completely up-to-date. Your project can just use the data that was previously ingested correctly

It created a nice place to enforce an interface between data sources that are logically the same, but arrive in (vastly) different formats

It also allowed us to have one GIT repository per ingestion and per project, this meant that we could separate all the code and CI tests that we want to run per repository

It makes it easy to add and remove data sources from a project, and reuse data sources for other projects (or replace them if a newer latest-and-greatest data source shows up).

How to use

This layer is fairly easy to implement, you’ll need to logically separate your ingestion and deployment. The way it is implemented at WBAA:

Create a GIT repository per data source, containing the ETL for the ingestion, and one per project, containing the ETL for that specific project Keep all the logic and CI tests belonging to source/project isolated Define an interface per logical part

We will give an example of an interface we defined that forces all the different systems in ING that do payment transactions into the same shape. At the end of the ETL of the ingestion of a payment transaction data source we enforce the following schema for the data:

payer account

payer name

beneficiary account

beneficiary name

amount

currency

date

Why is this a necessary? Because one source system could send things in a party, counterparty format where the + or - sign within the monetary amount column indicates which way the money went. Yet another could do the exact same but have a credit or debit column, you get the picture :-).

Circle 3: Data Tests

You can see a data test as a way to check if the logic you have just used in an ETL process has done what you expected it to do. It combines a sort of unit test for your ETL step with a more statistical test to see if the data still makes sense after processing.

As previously mentioned, at WBAA we have split our Airflow DAGs in those for ingestion and those for project ETL. We also make a distinction in what kind of data tests we want to run in these DAGs to make sure that after running the DAG it has done what we expect.

Examples of data tests for ingestion

Are there files available for ingestion?

Did we get the columns that we expected?

Are the rows that are in there valid?

Did the row count of your table only increase?

The valid rows test is where we check if the customer ID’s that we got in a data source, actually reference a real record in our central customer database (referential integrity). You’d be surprised how often a simple test like this picks out weird records. Same with checking if after ingestion, you have more records. This simple test has let us know on several occasions that when we changed logic, we made a mistake because suddenly the number of records unexpectedly decreased.

Examples of project ETL data tests

Imagine you’re dealing with payment transaction data that has both information of companies and private individuals (PIs) and you need to perform an ETL step that aggregates these PIs in to one line per week for all payments from PIs to companies and vice versa, filters out PI to PI payments, and keeps company to company payments untouched.

An example of tests can then be:

Are the known private individuals filtered out?

Are the known companies still in?

Has the aggregation of PIs worked correctly?

In general, WBAA aims to have at least one data test after every ETL task in a DAG.

How to use

Make sure your environment has both pytest and airflow available Define a conftest.py file in which you create a SparkSession and other configuration that you want to set Create a .py file per test that you want to run You can now schedule this test file in Airflow by setting it downstream of your ETL step and then calling it with a BashOperator and running it with pytest

pytest_cmd = """

export PYTHONPATH=/usr/spark/python/:/usr/spark/python/lib/\

py4j-0.10.4-src.zip:{spark_directory} &&\

export SPARK_HOME={spark_home} &&\

export ENVIRONMENT={environment} &&\

export MASTER=local &&\

cd /usr/local/airflow &&\

python -m pytest {directory}{script}

""" test_union_transactions = BashOperator(

task_id='test_union_transactions',

bash_command=pytest_cmd.format(

environment=ENVIRONMENT,

directory=TESTS_DIRECTORY,

spark_directory=SPARK_DIRECTORY,

script='test_union_transactions.py',

spark_home=SPARK_HOME

),

dag=dag

)

Circle 4: Alerting

When things go wrong (and we assume that this will happen), it is important that we, as engineers, are notified, so that we can respond quickly. Chuck Norris helps us with this. Chuck Norris is a Slack ‘bot’ that posts to a designated Slack channel when a DAG fails, with some details on which DAG and which task in this DAG failed. For privacy reasons, we don’t post any more information on the error in Slack, but you could add this if your data is not privacy-sensitive. Chuck Norris allows us to avoid constantly checking a DAG’s progress. One danger is that you can become reliant on Chuck to notify you of failure, so if Chuck himself fails (for instance, because a firewall opening is closed), you would wrongfully assume all is well.

How to use

When we initially added Chuck Norris, Airflow’s Slack operator did not meet our requirements. We therefore use a simple BashOperator. Because we don’t want you good people posting into our Slack channel, we haven’t included this in the GitHub repository. You can, however, easily integrate this in your own code with the following steps:

In the default_args object that you use to create your DAG object, add the following:

'on_failure_callback': send_slack_alert

2. Add the following function to your Airflowfile:

def send_slack_alert(context=None):

"""Send slack alert on failure to alert the team"""

payload_vars = {

'url': 'https://hooks.slack.com/services/<CREDENTIALS>',

'run_id': str(context['run_id']),

'task': str(context['task']),

'dag_name': str(context['dag'].dag_id)

}

error_message = """

{dag_name} Failure! Task failed: {task} Check log at: \

{run_id}

""".format(**payload_vars)



payload_vars['json'] = """

payload={{"channel":"#<YOUR_CHANNEL_HERE>","text":"{0}"}}

""".format(error_message) slack_cmd = """

curl-X POST \

--data-urlencode '{json}' \

{url}

""".format(**payload_vars) slack_alert = BashOperator(

task_id='slack_alert',

dag=dag,

bash_command=slack_cmd

)

slack_alert.execute(context)

Now, every time a task fails, the send_slack_alert() function is called, which can perform any logic you want (in this case, post a Slack message).

Circle 5: Git Enforcing

Git Enforcing to us means making sure that each day a process resets each DAG to the last verified version (i.e. the code on origin/master ). We call this ‘Nuclear git’, because it will blow away any unchecked code. In this way, we can safely guarantee what code is actually executed in our daily ingestion and deployment DAGs.

In our environment, we have a single Airflow installation, which runs all data pipelines for dev, tst, acc and prd. One of the main reasons for this is that it limits the access to the central infrastructure to a single place, which makes it easier to control. Moreover, for some of our circles (e.g. Circle 7), it is very important that our code runs on production data. This means, however, that in some cases code in our Airflow environment is undergoing active development. Even the best engineers are only human (well, most of them ;-) ), and thus can forget to checkout the correct branch at the end of the day. In order to prevent unexpected results (because of dangling, in-development code), we added Nuclear git to our environment. The assumption is that all DAGs are git repositories that reside on your Airflow environment.

How to use

Nuclear git is, in fact, an Airflow DAG, in our case scheduled to run every day. The code is very simple, a single BashOperator with the following code:

BEWARE! Run this code at your own peril!

# this will hard reset all repos to the version on master branch

# any local commits that have not been pushed yet will be lost.

echo "Resetting "${dir%/*}

git fetch

git checkout -f master

git reset --hard origin/master

git clean -df

git submodule update --recursive --force

A nice side-effect of nuclear git is that it enforces good version control behaviour. A single commit at the end of the day is not good enough, and is very easy to forget. Nuclear git punishes this behaviour, and makes developers think about their git usage more consciously.

Circle 6: Mock Pipeline Tests

One of the most difficult aspects of designing and implementing reliable data pipelines is the fact that when working with real data, there are two moving parts: the data (and its quality) and your code. In order to be able to reliably test your code, it’s very important to ensure that your code is the only ‘moving part’. This circle of tests fixes the data in place, allowing the tests to focus on the code. By fixing the data, you know what data goes in to the functions in your code, and you can verify that the output of the functions in your code matches what you expect. In a sense, we are treating our code as a black box, and verifying its behaviour given certain input data.

Implementing this layer is quite involved, and requires a good understanding and definition of your data. The usefulness of the tests here will very strongly depend on how well your fake data models the real data. Of course, as you learn more about your data and its characteristics, you can and should update your fake data.

How to use

We have implemented our fake data tests with PySpark, as almost all of our data processing logic leverages Spark. In order to use the fake data tests, you’ll need a couple of things (assuming you have a working CI environment):

In your CI, setup a task/stage that has pytest , pyspark , and coverage available Create a conftest.py file in which you define the schemas of your data. Once that is in place, use these schemas to generate a given number of rows of data in Spark dataframes. Be sure to create rows of data that are representative of your real data. Write out each Spark dataframe to a table. By default, Spark will use Derby as its metastore. For testing purposes this is fine, you should be careful to ensure that your data generation in conftest.py uses the same metastore and spark-warehouse that the tests will use (otherwise the data will be missing) Create as many test files as you want. The general rule of thumb here is one test file for every Spark script in your data pipeline, possibly with multiple tests per file. In each test, call the function you’re testing. Once this completes, use Spark to verify that the output tables now contain the data you would expect given the input data you defined. As an example, imagine you work for a bank and have to ensure that North Korean transactions are removed from your data

Step 1: Define your fake data

PERSON = [('name': 'Kim Yong Un', 'country': 'North Korea', 'iban': 'NK99NKBK0000000666'), …] TRANSACTIONS= [('iban': 'NK99NKBK0000000666', 'amount': 10 ), …]

Step 2: Run your function

filter_data(spark, "tst")

Step 3: Verify the output of the function

assert spark.sql("""

SELECT COUNT(*) ct

FROM filtered_data

WHERE iban = 'NK99NKBK0000000666'

""").first().ct == 0

Circle 7: DTAP

Splitting application back-ends and front-ends across multiple environments has been a best practice in software development for many years. Generally, four environments are defined: development, test, acceptance, and production. Each of these serves a distinct purpose. At WBAA, in order to deal with the reality of real data, we have extended this concept of multiple environments to our data. Normally, only the production environment of an application runs on production (i.e. real) data. In our case, however, we have created 4 distinct environments, in which real data is used in all. We do this, because real data always contains unexpected, surprising characteristics. We use 4 environments: