-
Notifications
You must be signed in to change notification settings - Fork 10
WIP: Metric anomaly check #103
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
timgent
wants to merge
7
commits into
master
Choose a base branch
from
metric-anomaly-check
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1796371
Failing test for absoluteChangeAnomalyCheck
6a36ec6
Implement absoluteChangeAnomalyCheck
ffdaff3
Wire in Anomaly checks (tests passing)
eccf0b9
Anomalous checks based on historic std deviation and mean
bbf7c0b
Remove duplication for applyCheckOnMetrics method
9471b43
Minor tidy ups for code organisation for anomaly checks
ba46206
Handle error case if there were no previous metrics for a dataset wit…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 20 additions & 2 deletions
22
src/main/scala/com/github/timgent/dataflare/checks/metrics/MetricsBasedCheck.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
src/main/scala/com/github/timgent/dataflare/checks/metrics/SingleMetricAnomalyCheck.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| package com.github.timgent.dataflare.checks.metrics | ||
|
|
||
| import java.time.Instant | ||
|
|
||
| import com.github.timgent.dataflare.FlareError.{LookedUpMetricOfWrongType, MetricMissing} | ||
| import com.github.timgent.dataflare.checks.CheckDescription.SingleMetricCheckDescription | ||
| import com.github.timgent.dataflare.checks.QCCheck.SingleDsCheck | ||
| import com.github.timgent.dataflare.checks._ | ||
| import com.github.timgent.dataflare.metrics.MetricValue.LongMetric | ||
| import com.github.timgent.dataflare.metrics.{MetricDescriptor, MetricValue} | ||
|
|
||
| import scala.reflect.ClassTag | ||
|
|
||
| /** | ||
| * A check based on a single metric and the history of that metric, in order to detect anomalies | ||
| * | ||
| * @param metric - describes the metric the check will be done on | ||
| * @param checkDescription - the user friendly description for this check | ||
| * @param check - the check to be done | ||
| * @tparam MV - the type of the MetricValue that will be calculated in order to complete this check | ||
| */ | ||
| case class SingleMetricAnomalyCheck[MV <: MetricValue](metric: MetricDescriptor { type MetricType = MV }, checkDescription: String)( | ||
| check: (MV#T, Map[Instant, MV#T]) => RawCheckResult | ||
| ) extends MetricsBasedCheck | ||
| with SingleDsCheck { | ||
|
|
||
| override def qcType: QcType = QcType.SingleMetricAnomalyCheck | ||
|
|
||
| override def description: CheckDescription = | ||
| SingleMetricCheckDescription(checkDescription, metric.toSimpleMetricDescriptor) // TODO: Should have more info in the description | ||
|
|
||
| def applyCheck(metric: MV, historicMetrics: Map[Instant, MV#T]): CheckResult = { | ||
| check(metric.value, historicMetrics).withDescription(QcType.SingleMetricAnomalyCheck, description) | ||
| } | ||
|
|
||
| // typeTag required here to enable match of metric on type MV. Without class tag this type check would be fruitless | ||
| private[dataflare] final def applyCheckOnMetrics( | ||
| metrics: Map[MetricDescriptor, MetricValue], | ||
| historicMetrics: Map[Instant, MetricValue] | ||
| )(implicit classTag: ClassTag[MV]): CheckResult = { | ||
| val maybeMetricOfInterest = getMetric(metric, metrics) | ||
| val relevantHistoricMetrics: Map[Instant, MV#T] = historicMetrics.collect { | ||
| case (instant, metricValue: MV) => (instant, metricValue.value) | ||
| } | ||
| maybeMetricOfInterest match { | ||
| case Left(MetricMissing) => metricNotPresentErrorResult | ||
| case Left(LookedUpMetricOfWrongType) => metricTypeErrorResult | ||
| case Right(metric) => applyCheck(metric, relevantHistoricMetrics) | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
||
| object SingleMetricAnomalyCheck { | ||
| def absoluteChangeAnomalyCheck( | ||
| maxReduction: Long, | ||
| maxIncrease: Long, | ||
| metricDescriptor: MetricDescriptor.Aux[LongMetric] // SizeMetric | ||
| ): SingleMetricAnomalyCheck[LongMetric] = | ||
| SingleMetricAnomalyCheck[LongMetric](metricDescriptor, "AbsoluteChangeAnomalyCheck") { (currentMetricValue, historicMetricValues) => | ||
| val (_, lastMetricValue) = historicMetricValues.maxBy(_._1) | ||
| val isWithinAcceptableRange = | ||
| (lastMetricValue + maxIncrease) <= currentMetricValue && (lastMetricValue - maxReduction) >= currentMetricValue | ||
| if (isWithinAcceptableRange) | ||
| RawCheckResult( | ||
| CheckStatus.Success, | ||
| s"MetricValue of $currentMetricValue was not anomalous compared to previous result of $lastMetricValue" | ||
| ) | ||
| else | ||
| RawCheckResult( | ||
| CheckStatus.Error, | ||
| s"MetricValue of $currentMetricValue was anomalous compared to previous result of $lastMetricValue" | ||
| ) | ||
| } | ||
|
|
||
| def stdChangeAnomalyCheck( | ||
| lowerDeviationFactor: Int = 2, | ||
| higherDeviationFactor: Int = 2, | ||
| metricDescriptor: MetricDescriptor.Aux[LongMetric] | ||
| ): SingleMetricAnomalyCheck[LongMetric] = { | ||
|
|
||
| SingleMetricAnomalyCheck[LongMetric](metricDescriptor, "STDChangeAnomalyCheck") { | ||
| (currentMetricValue: Long, historicMetricValues: Map[Instant, Long]) => | ||
| import com.github.timgent.dataflare.utils.stats.{mean, stdDev} | ||
|
|
||
| val historicValues = historicMetricValues.values | ||
|
|
||
| val historicMean: Double = mean(historicValues) | ||
| val historicSTD: Double = stdDev(historicValues) | ||
|
|
||
| val isValidRange = | ||
| currentMetricValue >= historicMean - (lowerDeviationFactor * historicSTD) && | ||
| currentMetricValue <= (higherDeviationFactor * historicSTD) + historicMean | ||
|
|
||
| if (isValidRange) | ||
| RawCheckResult( | ||
| CheckStatus.Success, | ||
| s"MetricValue of $currentMetricValue was not anomalous compared to previous results. Mean: $historicMean; STD: $historicSTD" | ||
| ) | ||
| else | ||
| RawCheckResult( | ||
| CheckStatus.Error, | ||
| s"MetricValue of $currentMetricValue was anomalous compared to previous results. Mean: $historicMean; STD: $historicSTD" | ||
| ) | ||
|
|
||
| } | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,8 +8,8 @@ import com.github.timgent.dataflare.checks.ArbDualDsCheck.DatasetPair | |
| import com.github.timgent.dataflare.checks.DatasourceDescription.{DualDsDescription, SingleDsDescription} | ||
| import com.github.timgent.dataflare.checks.QCCheck.{DualDsQCCheck, SingleDsCheck} | ||
| import com.github.timgent.dataflare.checks._ | ||
| import com.github.timgent.dataflare.checks.metrics.{DualMetricCheck, SingleMetricCheck} | ||
| import com.github.timgent.dataflare.metrics.{MetricDescriptor, MetricValue, MetricsCalculator} | ||
| import com.github.timgent.dataflare.checks.metrics.{DualMetricCheck, SingleMetricAnomalyCheck, SingleMetricCheck} | ||
| import com.github.timgent.dataflare.metrics.{MetricDescriptor, MetricValue, MetricsCalculator, SimpleMetricDescriptor} | ||
| import com.github.timgent.dataflare.repository.{MetricsPersister, NullMetricsPersister, NullQcResultsRepository, QcResultsRepository} | ||
| import org.apache.spark.sql.Dataset | ||
|
|
||
|
|
@@ -72,6 +72,12 @@ case class ChecksSuite( | |
| (dds, relevantChecks) | ||
| } | ||
|
|
||
| private val singleMetricAnomalyChecks: Map[DescribedDs, Seq[SingleMetricAnomalyCheck[_]]] = singleDsChecks.map { | ||
| case (dds, checks) => | ||
| val relevantChecks = checks.collect { case check: SingleMetricAnomalyCheck[_] => check } | ||
| (dds, relevantChecks) | ||
| } | ||
|
|
||
| private val arbDualDsChecks: Map[DescribedDsPair, Seq[ArbDualDsCheck]] = dualDsChecks.map { | ||
| case (ddsPair, checks) => | ||
| val relevantChecks = checks.collect { case check: ArbDualDsCheck => check } | ||
|
|
@@ -138,6 +144,7 @@ case class ChecksSuite( | |
| */ | ||
| private def getMinimumRequiredMetrics( | ||
| seqSingleDatasetMetricsChecks: Map[DescribedDs, Seq[SingleMetricCheck[_]]], | ||
| seqSingleDatasetMetricAnomalyChecks: Map[DescribedDs, Seq[SingleMetricAnomalyCheck[_]]], | ||
| seqDualDatasetMetricChecks: Map[DescribedDsPair, Seq[DualMetricCheck[_]]], | ||
| trackMetrics: Map[DescribedDs, Seq[MetricDescriptor]] | ||
| ): Map[DescribedDs, List[MetricDescriptor]] = { | ||
|
|
@@ -146,6 +153,11 @@ case class ChecksSuite( | |
| metricDescriptors = checks.map(_.metric).toList | ||
| } yield (dds, metricDescriptors)).groupBy(_._1).mapValues(_.flatMap(_._2).toList) | ||
|
|
||
| val singleDatasetAnomalyMetricDescriptors: Map[DescribedDs, List[MetricDescriptor]] = (for { | ||
| (dds, checks) <- seqSingleDatasetMetricAnomalyChecks | ||
| metricDescriptors = checks.map(_.metric).toList | ||
| } yield (dds, metricDescriptors)).groupBy(_._1).mapValues(_.flatMap(_._2).toList) | ||
|
|
||
| val dualDatasetAMetricDescriptors: Map[DescribedDs, List[MetricDescriptor]] = (for { | ||
| (ddsPair, checks) <- seqDualDatasetMetricChecks | ||
| describedDatasetA: DescribedDs = ddsPair.ds | ||
|
|
@@ -159,7 +171,7 @@ case class ChecksSuite( | |
| } yield (describedDatasetB, metricDescriptors)).groupBy(_._1).mapValues(_.flatMap(_._2).toList) | ||
|
|
||
| val allMetricDescriptors: Map[DescribedDs, List[MetricDescriptor]] = | ||
| (singleDatasetMetricDescriptors |+| dualDatasetAMetricDescriptors |+| dualDatasetBMetricDescriptors | ||
| (singleDatasetMetricDescriptors |+| singleDatasetAnomalyMetricDescriptors |+| dualDatasetAMetricDescriptors |+| dualDatasetBMetricDescriptors | ||
| |+| trackMetrics.mapValues(_.toList)) | ||
| .mapValues(_.distinct) | ||
|
|
||
|
|
@@ -170,14 +182,21 @@ case class ChecksSuite( | |
| timestamp: Instant | ||
| )(implicit ec: ExecutionContext): Future[Seq[CheckResult]] = { | ||
| val allMetricDescriptors: Map[DescribedDs, List[MetricDescriptor]] = | ||
| getMinimumRequiredMetrics(singleMetricChecks, dualMetricChecks, metricsToTrack) | ||
| getMinimumRequiredMetrics( | ||
| singleMetricChecks, | ||
| singleMetricAnomalyChecks, | ||
| dualMetricChecks, | ||
| metricsToTrack | ||
| ) | ||
| val calculatedMetrics: Map[DescribedDs, Either[MetricCalculationError, Map[MetricDescriptor, MetricValue]]] = | ||
| allMetricDescriptors.map { | ||
| case (describedDataset, metricDescriptors) => | ||
| val metricValues: Either[MetricCalculationError, Map[MetricDescriptor, MetricValue]] = | ||
| MetricsCalculator.calculateMetrics(describedDataset, metricDescriptors) | ||
| (describedDataset, metricValues) | ||
| } | ||
| val allPreviousMetricsFut: Future[Map[Instant, Map[SingleDsDescription, Map[SimpleMetricDescriptor, MetricValue]]]] = | ||
| metricsPersister.loadAll | ||
|
|
||
| val metricsToSave = calculatedMetrics.collect { | ||
| case (describedDataset, Right(metrics)) => | ||
|
|
@@ -192,6 +211,7 @@ case class ChecksSuite( | |
|
|
||
| for { | ||
| _ <- storedMetricsFut | ||
| allPreviousMetrics: Map[Instant, Map[SingleDsDescription, Map[SimpleMetricDescriptor, MetricValue]]] <- allPreviousMetricsFut | ||
|
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As per above we should only load historic metrics we actually need |
||
| } yield { | ||
| val singleDatasetCheckResults: Seq[CheckResult] = singleMetricChecks.toSeq.flatMap { | ||
| case (dds, checks) => | ||
|
|
@@ -207,6 +227,28 @@ case class ChecksSuite( | |
| checkResults | ||
| } | ||
|
|
||
| val singleDatasetAnomalyCheckResults: Seq[CheckResult] = singleMetricAnomalyChecks.toSeq.flatMap { | ||
| case (dds, checks) => | ||
| val datasetDescription = SingleDsDescription(dds.description) | ||
| val maybeMetricsForDs: Either[MetricCalculationError, Map[MetricDescriptor, MetricValue]] = calculatedMetrics(dds) | ||
| val checkResults: Seq[CheckResult] = checks.map { check => | ||
| maybeMetricsForDs match { | ||
| case Left(err) => check.getMetricErrorCheckResult(dds.datasourceDescription, err) | ||
| case Right(metricsForDs: Map[MetricDescriptor, MetricValue]) => | ||
| val historicMetricsForOurMetric = allPreviousMetrics | ||
| .mapValues { ddsToMetricsMap => | ||
| for { | ||
| metricsMap <- ddsToMetricsMap.get(datasetDescription) | ||
| metricValue <- metricsMap.get(check.metric.toSimpleMetricDescriptor) | ||
| } yield metricValue | ||
| } | ||
| .collect { case (instant, Some(metricValue)) => (instant, metricValue) } | ||
| check.applyCheckOnMetrics(metricsForDs, historicMetricsForOurMetric).withDatasourceDescription(datasetDescription) | ||
| } | ||
| } | ||
| checkResults | ||
| } | ||
|
|
||
| val dualDatasetCheckResults: Seq[CheckResult] = dualMetricChecks.toSeq.flatMap { | ||
| case (ddsPair, checks) => | ||
| val dds = ddsPair.ds | ||
|
|
@@ -229,7 +271,7 @@ case class ChecksSuite( | |
| checkResults | ||
| } | ||
|
|
||
| singleDatasetCheckResults ++ dualDatasetCheckResults | ||
| singleDatasetCheckResults ++ dualDatasetCheckResults ++ singleDatasetAnomalyCheckResults | ||
| } | ||
|
|
||
| } | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
src/main/scala/com/github/timgent/dataflare/utils/stats.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.github.timgent.dataflare.utils | ||
|
|
||
| object stats { | ||
|
|
||
| import Numeric.Implicits._ | ||
|
|
||
| def mean[T: Numeric](xs: Iterable[T]): Double = xs.sum[T].toDouble() / xs.size | ||
|
|
||
| def variance[T: Numeric](xs: Iterable[T]): Double = { | ||
| val avg = mean(xs) | ||
| xs.map(_.toDouble).map(a => math.pow(a - avg, 2)).sum / xs.size | ||
| } | ||
|
|
||
| def stdDev[T: Numeric](xs: Iterable[T]): Double = math.sqrt(variance(xs)) | ||
|
|
||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should load only historic metrics that we actually need