Testing and Validation
After establishing a process for migrating data from source systems and running analytics jobs on Amazon EMR, ensuring data quality becomes increasingly important. Unit tests are typically written for code, but testing data quality is often overlooked, and incorrect or malformed data can significantly impact production systems. Common data quality issues include the following:
-
Missing values can lead to failures in production systems that require non-null values.
-
Changes in data distribution can lead to unexpected outputs of machine learning models.
-
Aggregations of incorrect data can lead to ill-informed business decisions.
This section covers multiple methods of checking data quality using modern AWS native and open-source tools, applied as part of your Amazon EMR migration strategy.
Cluster-level validation
When migrating workloads to Amazon EMR, validating cluster health and resource utilization is as important as validating data quality. Cluster-level validation ensures that migrated workloads perform as expected and that clusters are right-sized.
Monitor cluster metrics with Amazon CloudWatch
Amazon EMR automatically publishes metrics to Amazon CloudWatch every five minutes at no additional charge. Monitor the following key metrics during and after migration:
-
AppsRunningandAppsPendingtrack application throughput and queuing. A sustained increase inAppsPendingmight indicate that the cluster is undersized. -
ContainerPendingandContainerAllocatedtrack YARN container allocation. A highContainerPendingvalue indicates resource contention. -
YARNMemoryAvailablePercentagereports available YARN memory as a percentage. Low values signal memory saturation. -
HDFSUtilizationandCapacityRemainingGBreport HDFS disk usage if your cluster uses HDFS.
For Spark-specific monitoring, you can publish application-level metrics to Amazon
CloudWatch. For more information, see Monitor
Apache Spark applications on Amazon EMR with Amazon CloudWatch
Compare performance against on-premises baselines
Establish baseline metrics from your on-premises environment, such as job duration,
resource consumption, and throughput, before migration. After migrating, compare Amazon EMR
CloudWatch metrics against these baselines to validate that migrated jobs meet expected SLAs.
Metrics such as RunningMapTasks, RemainingMapTasks, and
Spark application execution times are directly useful.
Validate cluster sizing and capacity planning
Use CloudWatch metrics to right-size clusters after migration. When managed scaling is enabled, Amazon EMR publishes high-resolution metrics at one-minute granularity, including current and target capacity units. Monitor these metrics to verify that managed scaling responds appropriately and whether minimum or maximum instance counts need adjustment. For more information, see Estimating Amazon EMR cluster capacity in the AWS Prescriptive Guidance.
Set up alerts for cluster health
Configure CloudWatch alarms with Amazon SNS notifications on critical metrics. For example,
alert when YARNMemoryAvailablePercentage drops below a threshold, when
ContainerPending exceeds a sustained count, or when IsIdle
indicates that a long-running cluster has no active workloads.
Data quality overview
Data quality measures how well your data meets the expectations of its consumers, the correctness of the data relative to the object it models. Consider data quality from the following dimensions:
-
Completeness measures how comprehensive your data is.
-
Uniqueness measures duplication within your data.
-
Timeliness measures data freshness and availability within SLAs.
-
Validity measures conformance to defined schemas, syntax, and requirements.
-
Accuracy measures correctness in representing objects within scope.
-
Consistency measures differences when referencing the same object or relationships.
Organizations can define additional metrics and attributes as dimensions for their specific needs.
Check your ingestion pipeline
Data integrity is a crucial part of data quality checks. One of the most important areas to validate is whether ingested raw data is correct.
Understanding tool-specific validation
First, understand your tool's existing validation mechanisms. For example, Apache Sqoop
validates data copy jobs through the --validate flag, which performs row
count comparisons.
sqoop import --connect jdbc:mysql://source/db --table orders \ --target-dir s3://bucket/orders/ --validate
However, Sqoop validation has limitations. It does not support the following:
-
The all-tables option
-
The free-form query option
-
Data imported into Hive or HBase
-
Table import with the
--whereargument -
Incremental imports
Fundamentally, Sqoop only performs row count comparisons. To validate every transferred value, you must reverse your data flow and compare old data against new data with hashes or checksums, an expensive operation that requires careful risk assessment.
AWS CLI and Amazon S3 data transfer validation
The following are common validation questions when you use the AWS CLI to transfer data to Amazon S3:
-
Does the AWS CLI validate objects as they land in Amazon S3? Yes, the AWS CLI uses MD5 checksums for integrity validation.
-
How does the AWS CLI validate objects? Through
Content-MD5headers and ETags. -
Does Amazon S3 expose the checksum? Yes, through the ETag, with caveats for multipart uploads.
-
What about multipart uploads? Amazon S3 calculates checksums for parts and for the whole object differently.
-
How do you validate without relying on the ETag? Use the AWS CLI
--checksum-algorithmoption, such as SHA256 or CRC32.
Use the AWS CLI with explicit checksum algorithms.
aws s3 cp source.parquet s3://bucket/data/ \ --checksum-algorithm SHA256 \ --metadata-directive REPLACE
Overall data quality policy
Data sources and extraction processes used during initial development frequently differ from production. Research is often performed on sample, cleaned, or enriched data, while production uses raw, real-time data. Test this assumption. Create data lineage diagrams for the following:
-
Development pipeline: document all data sources and transformations used to build models.
-
Production pipeline: document the production data catalog and pipeline.
-
Gap analysis: identify similarities and differences.
Address the following key questions:
-
If the pipelines are the same, are they subject to the same errors, and are these errors acceptable?
-
If the pipelines differ, do the differences impact analytics jobs or ML models, and how do you know?
Share the diagrams with subject matter experts and project sponsors. If the gap is too large, consider alternative approaches to sourcing data that better represent production.
Estimating impact of data quality
During initial analytics jobs, it is common to begin with cleaned data or to clean data before running jobs. For example, data might be dropped if no direct key match is found during merges, records with null or extreme values might be dropped, and multiple cleaning and transformation steps are performed. However, production data comes from different sources through different paths.
Compare statistics
Add formal checkpoints that compare source input data to the data actually used for training. Evaluate from both quantitative and qualitative perspectives. Use the following quantitative evaluation:
-
Compare counts: identify, track, and highlight data loss. What percentage of source data was used, and is there potential bias from unintentionally dropped data?
-
Review data duration: what time period does each dataset cover, and are all relevant business cycles included?
-
Quantify precision: compare mean, median, and standard deviation, calculate outliers, and use box plots for visual assessment.
Use the following qualitative evaluation:
-
Assess accuracy: based on experience and sample exploration, how confident are you that the data is accurate?
-
Document anecdotes: are there sufficient error reports, for example, "this sensor always runs high"?
-
Segment data: take different actions on segments discovered during analysis.
Validate model against unclean data inputs
Take a subset of data eliminated during every cleaning and transformation step, and compare it to the data eventually used. Assess the resulting outputs with the following questions:
-
Does the endpoint provide reasonable responses in all cases?
-
Where should checks and error handling be added?
-
Should error handling be added to the inference endpoint, or should calling applications handle problematic inputs and outputs?
Tools to help with data quality
Instead of implementing validation from scratch, use AWS native and open-source tools.
AWS Glue Data Quality
AWS Glue Data Quality is a fully managed service built on Deequ that measures and monitors data quality. It automatically computes statistics, recommends quality rules, monitors data, and alerts you when issues are detected. It also uses ML algorithms to surface hidden issues. The following are key capabilities:
-
Automated rule recommendations
-
Data Quality Definition Language (DQDL) for straightforward and advanced validation rules
-
Integration with ETL pipelines, by adding Evaluate Data Quality nodes in AWS Glue Studio
-
Reduced manual effort, from days to hours
The following example shows DQDL rules:
Rules = [ ColumnValues "order_amount" > 0, ColumnValues "customer_id" matches "[A-Z]{2}[0-9]{6}", Completeness "email" > 0.95, Uniqueness "transaction_id" > 0.99, RowCount between 1000000 and 2000000 ]
To get started, see the following references:
Apache Deequ (open source)
Apache Deequ is an open-source library built on Apache Spark for defining "unit tests for data." It measures data quality in large datasets and scales with data in distributed file systems or data warehouses. You can use Deequ directly within your Amazon EMR cluster as part of a Spark job, which makes it a natural fit for validating data quality inline with existing Amazon EMR workloads. This differs from AWS Glue Data Quality, which runs as a separate transient job outside the Amazon EMR cluster in the AWS Glue service. The following are key capabilities:
-
Calculate data quality metrics on datasets.
-
Define and verify data quality constraints.
-
Be informed about changes in data distribution.
-
Scale through its implementation on top of Apache Spark.
-
Run natively on Amazon EMR clusters alongside your Spark applications.
The following example shows usage on Amazon EMR:
val verificationResult = VerificationSuite() .onData(dataset) .addCheck( Check(CheckLevel.Error, "Data Quality Check") .hasSize(_ >= 1000000) .isComplete("customer_id") .isUnique("transaction_id") .isNonNegative("order_amount")) .run()
For more information, see the following resources:
Apache Griffin (large-scale migration validation)
Apache Griffin is an open-source data quality solution for big data that supports both batch and streaming modes, and it is particularly effective for large-scale data migration validation. Griffin runs as a Spark application on Amazon EMR, which makes it a natural fit for validating migrated datasets directly on your Amazon EMR cluster. The following are key capabilities:
-
A unified process to measure data quality from different perspectives
-
Support for both batch and streaming modes
-
Configuration-based validation for large datasets
-
Combination with StreamSets or Apache Kafka for end-to-end streaming workflows
Griffin operates as a Spark job submitted with spark-submit. You define
validation rules in JSON configuration files, called measures, that specify source and target
datasets, data quality dimensions such as accuracy, completeness, and timeliness, and comparison
rules.
spark-submit --class org.apache.griffin.core.GriffinMain \ --master yarn --deploy-mode cluster \ griffin-measure.jar <measure-config.json> <env-config.json>
Follow these best practices for Griffin on Amazon EMR.
-
Use transient Amazon EMR clusters for validation jobs to optimize costs.
-
Store Griffin configuration files in Amazon S3 for version control and reuse.
-
Use Amazon EMR auto-scaling for large dataset comparisons.
-
Integrate with Amazon CloudWatch to monitor job execution and set alerts for validation failures.
-
Schedule validation jobs with AWS Step Functions or Amazon MWAA for automated post-migration validation pipelines.
Use case: validate large datasets after migration using configuration-based rules without
writing custom code. Define source-to-target comparison measures in JSON, submit them as Spark
jobs on Amazon EMR, and review the results stored in Amazon S3 or HDFS. For more information, see
Blog:
Automate Large-Scale Data Validation Using Amazon EMR and Apache Griffin
Apache Spark Troubleshooting Agent for testing
The Apache Spark Troubleshooting Agent automates root cause analysis for data quality validation failures during Amazon EMR migration. When Deequ or Apache Griffin validation jobs fail or exhibit performance issues, the agent analyzes Spark event logs, YARN container logs, CloudWatch metrics, and Amazon EMR configurations to identify the underlying causes.
Common scenarios include the following:
-
Memory-related failures, where Deequ constraint validation encounters an
OutOfMemoryErroror excessive GC pressure, greater than 10 percent of task time. The agent identifies whether the issues stem from insufficientspark.executor.memory, inadequatespark.executor.memoryOverhead, or data skew, and provides specific recommendations. For example, it might recommend increasing executor memory from4gto8gwhen peak usage reaches 95 percent. -
Performance degradation, where large-scale Griffin validation jobs experience shuffle spills that exceed 100 GB during joins. The agent detects partition skew and recommends increasing
spark.sql.shuffle.partitionsor implementing salting. -
Validation jobs that run slower on Amazon EMR with Amazon S3 than on-premises HDFS. The agent identifies Amazon S3 access pattern issues, such as excessive list operations or request throttling, and recommends optimizations such as
spark.hadoop.fs.s3a.experimental.input.fadvise=randomand file consolidation.
The agent is particularly effective for iterative validation workflows. After you implement Deequ verification suites to validate schema completeness, uniqueness constraints, and statistical distributions, the agent monitors execution through Spark History Server and YARN ResourceManager. It automatically detects stage-level failures, data skew in validation joins (recommending Adaptive Query Execution or broadcast joins), and serialization errors (recommending Kryo serialization or broadcast variables). The agent provides automated timeline correlation across observability sources, which reduces troubleshooting time from hours to minutes.
10:15:23 - Validation job started (CloudWatch) 10:16:45 - Executor OOM during Uniqueness check (YARN logs) 10:17:12 - GC time spike to 60% (Spark History Server) 10:18:30 - Executor lost, task retry initiated (Spark event log) 10:19:45 - Job failed after 3 retries (YARN ResourceManager) Root Cause: Memory pressure during distinct count operation Recommendation: Increase spark.executor.memory to 12g and enable spark.sql.adaptive.coalescePartitions.enabled=true
This allows migration teams to focus on actual data quality issues, such as schema mismatches, data type inconsistencies, and business rule violations, rather than debugging validation infrastructure. The agent integrates with Amazon EMR observability tools, including CloudWatch, Spark History Server, and YARN ResourceManager. For full details, see Spark Agents.
Best practices for testing and validation
Apply the following best practices for testing and validation:
-
Validate early, validate often. Integrate validation checks throughout the entire data pipeline, not just at the final stages, and add checkpoints at the ingestion, transformation, and output stages.
-
Use AWS Glue Data Quality for managed, automated validation with minimal setup. It automatically computes statistics and recommends rules using DQDL, and you add Evaluate Data Quality nodes in AWS Glue Studio.
-
Implement Deequ for custom Spark-based validation logic on Amazon EMR clusters. It runs directly within your Amazon EMR cluster as part of a Spark job.
-
Use Apache Griffin for large-scale migration validation scenarios. Validate large datasets after migration by comparing source and target data on Amazon EMR using a configuration-based approach.
-
Define quantifiable metrics for data accuracy and establish acceptable risk levels. Set measurable thresholds for completeness, uniqueness, validity, accuracy, consistency, and timeliness, with acceptable tolerance levels.
-
Document data lineage from source to consumption. Data lineage in Amazon SageMaker Unified Studio provides an OpenLineage-compatible capability to trace data origins, track transformations, and visualize consumption. For Spark workloads on Amazon EMR, capture lineage events using the OpenLineage Spark integration and publish them through the OpenLineage-compatible API, and then visualize end-to-end lineage in Amazon SageMaker Unified Studio.
-
Automate alerts for data quality violations using CloudWatch and Amazon SNS. Configure CloudWatch alarms on these metrics with Amazon SNS notifications.
-
Test with production-like data during development to catch issues early. Use representative production data volumes and distributions to surface issues that only appear at scale.