-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
validator.py
2395 lines (2085 loc) · 97.1 KB
/
validator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import datetime
import inspect
import itertools
import json
import logging
import traceback
import warnings
from collections import defaultdict, namedtuple
from collections.abc import Hashable
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union
from dateutil.parser import parse
from tqdm.auto import tqdm
from great_expectations import __version__ as ge_version
from great_expectations.core.batch import Batch, BatchDefinition, BatchMarkers
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.core.expectation_suite import (
ExpectationSuite,
expectationSuiteSchema,
)
from great_expectations.core.expectation_validation_result import (
ExpectationSuiteValidationResult,
ExpectationValidationResult,
)
from great_expectations.core.id_dict import BatchSpec
from great_expectations.core.run_identifier import RunIdentifier
from great_expectations.core.util import convert_to_json_serializable
from great_expectations.data_asset.util import recursively_convert_to_json_serializable
from great_expectations.dataset import PandasDataset, SparkDFDataset, SqlAlchemyDataset
from great_expectations.dataset.sqlalchemy_dataset import SqlAlchemyBatchReference
from great_expectations.exceptions import (
GreatExpectationsError,
InvalidExpectationConfigurationError,
MetricResolutionError,
)
from great_expectations.execution_engine import (
ExecutionEngine,
PandasExecutionEngine,
SparkDFExecutionEngine,
SqlAlchemyExecutionEngine,
)
from great_expectations.execution_engine.execution_engine import MetricDomainTypes
from great_expectations.execution_engine.pandas_batch_data import PandasBatchData
from great_expectations.expectations.registry import (
get_expectation_impl,
get_metric_provider,
list_registered_expectation_implementations,
)
from great_expectations.marshmallow__shade import ValidationError
from great_expectations.rule_based_profiler.config import RuleBasedProfilerConfig
from great_expectations.rule_based_profiler.expectation_configuration_builder import (
ExpectationConfigurationBuilder,
)
from great_expectations.rule_based_profiler.helpers.configuration_reconciliation import (
DEFAULT_RECONCILATION_DIRECTIVES,
)
from great_expectations.rule_based_profiler.parameter_builder import ParameterBuilder
from great_expectations.rule_based_profiler.rule import Rule
from great_expectations.rule_based_profiler.rule_based_profiler import (
BaseRuleBasedProfiler,
ReconciliationDirectives,
ReconciliationStrategy,
)
from great_expectations.rule_based_profiler.types import ParameterContainer
from great_expectations.types import ClassConfig
from great_expectations.util import load_class, verify_dynamic_loading_support
from great_expectations.validator.exception_info import ExceptionInfo
from great_expectations.validator.metric_configuration import MetricConfiguration
from great_expectations.validator.validation_graph import (
ExpectationValidationGraph,
MetricEdge,
ValidationGraph,
)
logger = logging.getLogger(__name__)
logging.captureWarnings(True)
try:
import pandas as pd
except ImportError:
pd = None
logger.debug(
"Unable to load pandas; install optional pandas dependency for support."
)
MAX_METRIC_COMPUTATION_RETRIES: int = 3
ValidationStatistics = namedtuple(
"ValidationStatistics",
[
"evaluated_expectations",
"successful_expectations",
"unsuccessful_expectations",
"success_percent",
"success",
],
)
def _calc_validation_statistics(
validation_results: List[ExpectationValidationResult],
) -> ValidationStatistics:
"""
Calculate summary statistics for the validation results and
return ``ExpectationStatistics``.
"""
# calc stats
successful_expectations = sum(exp.success for exp in validation_results)
evaluated_expectations = len(validation_results)
unsuccessful_expectations = evaluated_expectations - successful_expectations
success = successful_expectations == evaluated_expectations
try:
success_percent = successful_expectations / evaluated_expectations * 100
except ZeroDivisionError:
# success_percent = float("nan")
success_percent = None
return ValidationStatistics(
successful_expectations=successful_expectations,
evaluated_expectations=evaluated_expectations,
unsuccessful_expectations=unsuccessful_expectations,
success=success,
success_percent=success_percent,
)
class Validator:
DEFAULT_RUNTIME_CONFIGURATION = {
"include_config": True,
"catch_exceptions": False,
"result_format": "BASIC",
}
RUNTIME_KEYS = DEFAULT_RUNTIME_CONFIGURATION.keys()
# noinspection PyUnusedLocal
def __init__(
self,
execution_engine: ExecutionEngine,
interactive_evaluation: bool = True,
expectation_suite: Optional[ExpectationSuite] = None,
expectation_suite_name: Optional[str] = None,
data_context: Optional[
Any
] = None, # Cannot type DataContext due to circular import
batches: Optional[List[Batch]] = None,
**kwargs,
):
"""
Validator is the key object used to create Expectations, validate Expectations,
and get Metrics for Expectations.
Additionally, note that Validators are used by Checkpoints under-the-hood.
:param execution_engine (ExecutionEngine):
:param interactive_evaluation (bool):
:param expectation_suite (Optional[ExpectationSuite]):
:param expectation_suite_name (Optional[str]):
:param data_context (Optional[DataContext]):
:param batches (Optional[List[Batch]]):
"""
self._data_context = data_context
self._execution_engine = execution_engine
self._expose_dataframe_methods = False
if batches is None:
batches = []
self._batches = {}
self._active_batch_id = None
self.load_batch_list(batches)
if len(batches) > 1:
logger.debug(
f"{len(batches)} batches will be added to this Validator. The batch_identifiers for the active "
f"batch are {self.active_batch.batch_definition['batch_identifiers'].items()}"
)
self.interactive_evaluation = interactive_evaluation
self._initialize_expectations(
expectation_suite=expectation_suite,
expectation_suite_name=expectation_suite_name,
)
self._default_expectation_args = copy.deepcopy(
Validator.DEFAULT_RUNTIME_CONFIGURATION
)
# This special state variable tracks whether a validation run is going on, which will disable
# saving expectation config objects
self._active_validation = False
if self._data_context and hasattr(
self._data_context, "_expectation_explorer_manager"
):
# TODO: verify flow of default expectation arguments
self.set_default_expectation_argument("include_config", True)
def __dir__(self):
"""
This custom magic method is used to enable expectation tab completion on Validator objects.
It also allows users to call Pandas.DataFrame methods on Validator objects
"""
validator_attrs = set(super().__dir__())
class_expectation_impls = set(list_registered_expectation_implementations())
# execution_engine_expectation_impls = (
# {
# attr_name
# for attr_name in self.execution_engine.__dir__()
# if attr_name.startswith("expect_")
# }
# if self.execution_engine
# else set()
# )
combined_dir = (
validator_attrs
| class_expectation_impls
# | execution_engine_expectation_impls
)
if self._expose_dataframe_methods:
combined_dir | set(dir(pd.DataFrame))
return list(combined_dir)
@property
def data_context(self) -> Optional["DataContext"]: # noqa: F821
return self._data_context
@property
def expose_dataframe_methods(self) -> bool:
return self._expose_dataframe_methods
@expose_dataframe_methods.setter
def expose_dataframe_methods(self, value: bool) -> None:
self._expose_dataframe_methods = value
def __getattr__(self, name):
name = name.lower()
if name.startswith("expect_") and get_expectation_impl(name):
return self.validate_expectation(name)
elif (
self._expose_dataframe_methods
and isinstance(self.active_batch.data, PandasBatchData)
and hasattr(pd.DataFrame, name)
):
return getattr(self.active_batch.data.dataframe, name)
else:
raise AttributeError(
f"'{type(self).__name__}' object has no attribute '{name}'"
)
def validate_expectation(self, name: str) -> Callable:
"""
Given the name of an Expectation, obtains the Class-first Expectation implementation and utilizes the
expectation's validate method to obtain a validation result. Also adds in the runtime configuration
Args:
name (str): The name of the Expectation being validated
Returns:
The Expectation's validation result
"""
expectation_impl = get_expectation_impl(name)
def inst_expectation(*args, **kwargs):
# this is used so that exceptions are caught appropriately when they occur in expectation config
# TODO: JPC - THIS LOGIC DOES NOT RESPECT DEFAULTS SET BY USERS IN THE VALIDATOR VS IN THE EXPECTATION
# DEVREL has action to develop a new plan in coordination with MarioPod
expectation_kwargs: dict = recursively_convert_to_json_serializable(kwargs)
meta: dict = expectation_kwargs.pop("meta", None)
basic_default_expectation_args: dict = {
k: v
for k, v in self.default_expectation_args.items()
if k in Validator.RUNTIME_KEYS
}
basic_runtime_configuration: dict = copy.deepcopy(
basic_default_expectation_args
)
basic_runtime_configuration.update(
{k: v for k, v in kwargs.items() if k in Validator.RUNTIME_KEYS}
)
allowed_config_keys: Tuple[str] = expectation_impl.get_allowed_config_keys()
args_keys: Tuple[str] = expectation_impl.args_keys or tuple()
arg_name: str
idx: int
arg: Any
for idx, arg in enumerate(args):
try:
arg_name = args_keys[idx]
if arg_name in allowed_config_keys:
expectation_kwargs[arg_name] = arg
if arg_name == "meta":
logger.warning(
"Setting meta via args could be ambiguous; please use a kwarg instead."
)
meta = arg
except IndexError:
raise InvalidExpectationConfigurationError(
f"Invalid positional argument: {arg}"
)
configuration: ExpectationConfiguration = (
self._build_expectation_configuration(
expectation_type=name,
expectation_kwargs=expectation_kwargs,
meta=meta,
expectation_impl=expectation_impl,
)
)
exception_info: ExceptionInfo
if self.interactive_evaluation:
configuration.process_evaluation_parameters(
self._expectation_suite.evaluation_parameters,
True,
self._data_context,
)
try:
expectation = expectation_impl(configuration)
"""Given an implementation and a configuration for any Expectation, returns its validation result"""
if not self.interactive_evaluation and not self._active_validation:
validation_result = ExpectationValidationResult(
expectation_config=copy.deepcopy(expectation.configuration)
)
else:
validation_result = expectation.validate(
validator=self,
evaluation_parameters=self._expectation_suite.evaluation_parameters,
data_context=self._data_context,
runtime_configuration=basic_runtime_configuration,
)
# If validate has set active_validation to true, then we do not save the config to avoid
# saving updating expectation configs to the same suite during validation runs
if self._active_validation is True:
stored_config = configuration.get_raw_configuration()
else:
# Append the expectation to the config.
stored_config = self._expectation_suite._add_expectation(
expectation_configuration=configuration.get_raw_configuration(),
send_usage_event=False,
)
# If there was no interactive evaluation, success will not have been computed.
if validation_result.success is not None:
# Add a "success" object to the config
stored_config.success_on_last_run = validation_result.success
if self._data_context is not None:
validation_result = self._data_context.update_return_obj(
self, validation_result
)
except Exception as err:
if basic_runtime_configuration.get("catch_exceptions"):
exception_traceback = traceback.format_exc()
exception_message = f"{type(err).__name__}: {str(err)}"
exception_info = ExceptionInfo(
exception_traceback=exception_traceback,
exception_message=exception_message,
)
validation_result = ExpectationValidationResult(
success=False,
exception_info=exception_info,
expectation_config=configuration,
)
else:
raise err
return validation_result
inst_expectation.__name__ = name
inst_expectation.__doc__ = expectation_impl.__doc__
return inst_expectation
def _build_expectation_configuration(
self,
expectation_type: str,
expectation_kwargs: dict,
meta: dict,
expectation_impl: "Expectation", # noqa: F821
) -> ExpectationConfiguration:
auto: Optional[bool] = expectation_kwargs.get("auto")
profiler_config: Optional[RuleBasedProfilerConfig] = expectation_kwargs.get(
"profiler_config"
)
default_profiler_config: Optional[
RuleBasedProfilerConfig
] = expectation_impl.default_kwarg_values.get("profiler_config")
if auto and profiler_config is None and default_profiler_config is None:
raise ValueError(
"Automatic Expectation argument estimation requires a Rule-Based Profiler to be provided."
)
configuration: ExpectationConfiguration
profiler: Optional[
BaseRuleBasedProfiler
] = self.build_rule_based_profiler_for_expectation(
expectation_type=expectation_type
)(
*(), **expectation_kwargs
)
if profiler is not None:
profiler.run(
variables=None,
rules=None,
batch_list=list(self.batches.values()),
batch_request=None,
recompute_existing_parameter_values=False,
reconciliation_directives=DEFAULT_RECONCILATION_DIRECTIVES,
)
expectation_configurations: List[
ExpectationConfiguration
] = profiler.get_expectation_suite(
expectation_suite=None,
expectation_suite_name=None,
include_citation=True,
save_updated_expectation_suite=False,
).expectations
configuration = expectation_configurations[0]
# Reconcile explicitly provided "ExpectationConfiguration" success_kwargs as overrides to generated values.
success_keys: Tuple[str] = (
expectation_impl.success_keys
if hasattr(expectation_impl, "success_keys")
else tuple()
)
arg_keys: Tuple[str] = (
expectation_impl.arg_keys
if hasattr(expectation_impl, "arg_keys")
else tuple()
)
runtime_keys: Tuple[str] = (
expectation_impl.runtime_keys
if hasattr(expectation_impl, "runtime_keys")
else None
) or tuple()
# noinspection PyTypeChecker
override_keys: Tuple[str] = success_keys + arg_keys + runtime_keys
key: str
value: Any
expectation_kwargs_overrides: dict = {
key: value
for key, value in expectation_kwargs.items()
if key in override_keys
}
expectation_kwargs_overrides = convert_to_json_serializable(
data=expectation_kwargs_overrides
)
expectation_kwargs = configuration.kwargs
expectation_kwargs.update(expectation_kwargs_overrides)
if meta is None:
meta = {}
meta["profiler_config"] = profiler.to_json_dict()
configuration = ExpectationConfiguration(
expectation_type=expectation_type,
kwargs=expectation_kwargs,
meta=meta,
)
else:
configuration = ExpectationConfiguration(
expectation_type=expectation_type,
kwargs=expectation_kwargs,
meta=meta,
)
return configuration
def build_rule_based_profiler_for_expectation(
self, expectation_type: str
) -> Callable:
"""
Given name of Expectation ("expectation_type"), builds effective RuleBasedProfiler object from configuration.
Args:
expectation_type (str): Name of Expectation for which Rule-Based Profiler may be configured.
Returns:
Function that builds effective RuleBasedProfiler object (for specified "expectation_type").
"""
expectation_impl = get_expectation_impl(expectation_type)
def inst_rule_based_profiler(
*args, **kwargs
) -> Optional[BaseRuleBasedProfiler]:
if args is None:
args = tuple()
if kwargs is None:
kwargs = {}
expectation_kwargs: dict = recursively_convert_to_json_serializable(kwargs)
basic_default_expectation_args: dict = {
k: v
for k, v in self.default_expectation_args.items()
if k in Validator.RUNTIME_KEYS
}
basic_runtime_configuration: dict = copy.deepcopy(
basic_default_expectation_args
)
basic_runtime_configuration.update(
{k: v for k, v in kwargs.items() if k in Validator.RUNTIME_KEYS}
)
allowed_config_keys: Tuple[str] = expectation_impl.get_allowed_config_keys()
args_keys: Tuple[str] = expectation_impl.args_keys or tuple()
arg_name: str
idx: int
arg: Any
for idx, arg in enumerate(args):
try:
arg_name = args_keys[idx]
if arg_name in allowed_config_keys:
expectation_kwargs[arg_name] = arg
if arg_name == "meta":
logger.warning(
"Setting meta via args could be ambiguous; please use a kwarg instead."
)
except IndexError:
raise InvalidExpectationConfigurationError(
f"Invalid positional argument: {arg}"
)
success_keys: Tuple[str] = (
expectation_impl.success_keys
if hasattr(expectation_impl, "success_keys")
else tuple()
)
auto: Optional[bool] = expectation_kwargs.get("auto")
profiler_config: Optional[RuleBasedProfilerConfig] = expectation_kwargs.get(
"profiler_config"
)
default_profiler_config: Optional[
RuleBasedProfilerConfig
] = expectation_impl.default_kwarg_values.get("profiler_config")
if auto and profiler_config is None and default_profiler_config is None:
raise ValueError(
"Automatic Expectation argument estimation requires a Rule-Based Profiler to be provided."
)
profiler: Optional[BaseRuleBasedProfiler]
if auto:
# Save custom Rule-Based Profiler configuration for reconciling it with optionally-specified default
# Rule-Based Profiler configuration as an override argument to "BaseRuleBasedProfiler.run()" method.
override_profiler_config: Optional[RuleBasedProfilerConfig]
if default_profiler_config:
override_profiler_config = copy.deepcopy(profiler_config)
else:
override_profiler_config = None
"""
If default Rule-Based Profiler configuration exists, use it as base with custom Rule-Based Profiler
configuration as override; otherwise, use custom Rule-Based Profiler configuration with no override.
"""
profiler_config = default_profiler_config or profiler_config
profiler = self._build_rule_based_profiler_from_config_and_runtime_args(
expectation_type=expectation_type,
expectation_kwargs=expectation_kwargs,
success_keys=success_keys,
profiler_config=profiler_config,
override_profiler_config=override_profiler_config,
)
else:
profiler = None
return profiler
return inst_rule_based_profiler
def _build_rule_based_profiler_from_config_and_runtime_args(
self,
expectation_type: str,
expectation_kwargs: dict,
success_keys: Tuple[str],
profiler_config: RuleBasedProfilerConfig,
override_profiler_config: Optional[RuleBasedProfilerConfig] = None,
) -> BaseRuleBasedProfiler:
assert (
profiler_config.name == expectation_type
), "The name of profiler used to build an ExpectationConfiguration must equal to expectation_type of the expectation being invoked."
profiler: BaseRuleBasedProfiler = BaseRuleBasedProfiler(
profiler_config=profiler_config,
data_context=self.data_context,
)
rules: List[Rule] = profiler.rules
assert (
len(rules) == 1
), "A Rule-Based Profiler for an Expectation can have exactly one rule."
domain_type: MetricDomainTypes
if override_profiler_config is None:
override_profiler_config = {}
if isinstance(override_profiler_config, RuleBasedProfilerConfig):
override_profiler_config = override_profiler_config.to_json_dict()
override_profiler_config.pop("name", None)
override_profiler_config.pop("config_version", None)
override_variables: Dict[str, Any] = override_profiler_config.get(
"variables", {}
)
effective_variables: Optional[
ParameterContainer
] = profiler.reconcile_profiler_variables(
variables=override_variables,
reconciliation_strategy=ReconciliationStrategy.UPDATE,
)
profiler.variables = effective_variables
override_rules: Dict[str, Dict[str, Any]] = override_profiler_config.get(
"rules", {}
)
assert (
len(override_rules) <= 1
), "An override Rule-Based Profiler for an Expectation can have exactly one rule."
if override_rules:
profiler.rules[0].name = list(override_rules.keys())[0]
effective_rules: List[Rule] = profiler.reconcile_profiler_rules(
rules=override_rules,
reconciliation_directives=ReconciliationDirectives(
domain_builder=ReconciliationStrategy.UPDATE,
parameter_builder=ReconciliationStrategy.REPLACE,
expectation_configuration_builder=ReconciliationStrategy.REPLACE,
),
)
profiler.rules = effective_rules
self._validate_profiler_and_update_rules_properties(
profiler=profiler,
expectation_type=expectation_type,
expectation_kwargs=expectation_kwargs,
success_keys=success_keys,
)
return profiler
def _validate_profiler_and_update_rules_properties(
self,
profiler: BaseRuleBasedProfiler,
expectation_type: str,
expectation_kwargs: dict,
success_keys: Tuple[str],
) -> None:
rule: Rule = profiler.rules[0]
assert (
rule.expectation_configuration_builders[0].expectation_type
== expectation_type
), "ExpectationConfigurationBuilder in profiler used to build an ExpectationConfiguration must have the same expectation_type as the expectation being invoked."
# TODO: <Alex>Add "metric_domain_kwargs_override" when "Expectation" defines "domain_keys" separately.</Alex>
key: str
value: Any
metric_value_kwargs_override: dict = {
key: value
for key, value in expectation_kwargs.items()
if key in success_keys
and key not in BaseRuleBasedProfiler.EXPECTATION_SUCCESS_KEYS
}
domain_type: MetricDomainTypes = rule.domain_builder.domain_type
if domain_type not in MetricDomainTypes:
raise ValueError(
f'Domain type declaration "{domain_type}" in "MetricDomainTypes" does not exist.'
)
# TODO: <Alex>Handle future domain_type cases as they are defined.</Alex>
if domain_type == MetricDomainTypes.COLUMN:
column_name = expectation_kwargs.get("column")
rule.domain_builder.include_column_names = (
[column_name] if column_name else None
)
parameter_builders: List[ParameterBuilder] = rule.parameter_builders or []
parameter_builder: ParameterBuilder
for parameter_builder in parameter_builders:
self._update_metric_value_kwargs_for_success_keys(
parameter_builder=parameter_builder,
metric_value_kwargs=metric_value_kwargs_override,
)
expectation_configuration_builders: List[ExpectationConfigurationBuilder] = (
rule.expectation_configuration_builders or []
)
expectation_configuration_builder: ExpectationConfigurationBuilder
for expectation_configuration_builder in expectation_configuration_builders:
validation_parameter_builders: List[ParameterBuilder] = (
expectation_configuration_builder.validation_parameter_builders or []
)
for parameter_builder in validation_parameter_builders:
self._update_metric_value_kwargs_for_success_keys(
parameter_builder=parameter_builder,
metric_value_kwargs=metric_value_kwargs_override,
)
def _update_metric_value_kwargs_for_success_keys(
self,
parameter_builder: ParameterBuilder,
metric_value_kwargs: Optional[dict] = None,
):
if metric_value_kwargs is None:
metric_value_kwargs = {}
if hasattr(parameter_builder, "metric_name") and hasattr(
parameter_builder, "metric_value_kwargs"
):
parameter_builder_metric_value_kwargs: dict = (
parameter_builder.metric_value_kwargs or {}
)
parameter_builder_metric_value_kwargs = {
key: metric_value_kwargs.get(key) or value
for key, value in parameter_builder_metric_value_kwargs.items()
}
parameter_builder.metric_value_kwargs = (
parameter_builder_metric_value_kwargs
)
evaluation_parameter_builders: List[ParameterBuilder] = (
parameter_builder.evaluation_parameter_builders or []
)
evaluation_parameter_builder: ParameterBuilder
for evaluation_parameter_builder in evaluation_parameter_builders:
self._update_metric_value_kwargs_for_success_keys(
parameter_builder=evaluation_parameter_builder,
metric_value_kwargs=metric_value_kwargs,
)
@property
def execution_engine(self) -> ExecutionEngine:
"""Returns the execution engine being used by the validator at the given time"""
return self._execution_engine
def list_available_expectation_types(self) -> List[str]:
"""Returns a list of all expectations available to the validator"""
keys = dir(self)
return [
expectation for expectation in keys if expectation.startswith("expect_")
]
def compute_metrics(
self, metric_configurations: List[MetricConfiguration]
) -> Dict[Tuple[str, str, str], Any]:
"""
metrics: List of desired MetricConfiguration objects to be resolved.
Return Dictionary with requested metrics resolved, with unique metric ID as key and computed metric as value.
"""
graph: ValidationGraph = ValidationGraph()
metric_configuration: MetricConfiguration
for metric_configuration in metric_configurations:
provider_cls, _ = get_metric_provider(
metric_configuration.metric_name, self.execution_engine
)
self._get_default_domain_kwargs(
metric_provider_cls=provider_cls,
metric_configuration=metric_configuration,
)
self._get_default_value_kwargs(
metric_provider_cls=provider_cls,
metric_configuration=metric_configuration,
)
self.build_metric_dependency_graph(
graph=graph,
execution_engine=self._execution_engine,
metric_configuration=metric_configuration,
)
resolved_metrics: Dict[Tuple[str, str, str], Any] = {}
# updates graph with aborted metrics
self.resolve_validation_graph(
graph=graph,
metrics=resolved_metrics,
)
return resolved_metrics
def get_metrics(self, metrics: Dict[str, MetricConfiguration]) -> Dict[str, Any]:
"""
metrics: Dictionary of desired metrics to be resolved, with metric_name as key and MetricConfiguration as value.
Return Dictionary with requested metrics resolved, with metric_name as key and computed metric as value.
"""
resolved_metrics: Dict[Tuple[str, str, str], Any] = self.compute_metrics(
metric_configurations=list(metrics.values())
)
return {
metric_configuration.metric_name: resolved_metrics[metric_configuration.id]
for metric_configuration in metrics.values()
}
@staticmethod
def _get_default_domain_kwargs(
metric_provider_cls: "MetricProvider", # noqa: F821
metric_configuration: MetricConfiguration,
) -> None:
for key in metric_provider_cls.domain_keys:
if (
key not in metric_configuration.metric_domain_kwargs
and key in metric_provider_cls.default_kwarg_values
):
metric_configuration.metric_domain_kwargs[
key
] = metric_provider_cls.default_kwarg_values[key]
@staticmethod
def _get_default_value_kwargs(
metric_provider_cls: "MetricProvider", # noqa: F821
metric_configuration: MetricConfiguration,
) -> None:
for key in metric_provider_cls.value_keys:
if (
key not in metric_configuration.metric_value_kwargs
and key in metric_provider_cls.default_kwarg_values
):
metric_configuration.metric_value_kwargs[
key
] = metric_provider_cls.default_kwarg_values[key]
def get_metric(self, metric: MetricConfiguration) -> Any:
"""return the value of the requested metric."""
return self.get_metrics(metrics={metric.metric_name: metric})[
metric.metric_name
]
def graph_validate(
self,
configurations: List[ExpectationConfiguration],
metrics: Optional[Dict[Tuple[str, str, str], Any]] = None,
runtime_configuration: Optional[dict] = None,
) -> List[ExpectationValidationResult]:
"""Obtains validation dependencies for each metric using the implementation of their associated expectation,
then proceeds to add these dependencies to the validation graph, supply readily available metric implementations
to fulfill current metric requirements, and validate these metrics.
Args:
configurations(List[ExpectationConfiguration]): A list of needed Expectation Configurations that
will be used to supply domain and values for metrics.
metrics (dict): A list of currently registered metrics in the registry
runtime_configuration (dict): A dictionary of runtime keyword arguments, controlling semantics
such as the result_format.
Returns:
A list of Validations, validating that all necessary metrics are available.
"""
if runtime_configuration is None:
runtime_configuration = {}
if runtime_configuration.get("catch_exceptions", True):
catch_exceptions = True
else:
catch_exceptions = False
evrs: List[ExpectationValidationResult]
expectation_validation_graphs: List[ExpectationValidationGraph] = []
processed_configurations: List[ExpectationConfiguration] = []
(
evrs,
processed_configurations,
) = self._generate_metric_dependency_subgraphs_for_each_expectation_configuration(
expectation_configurations=configurations,
expectation_validation_graphs=expectation_validation_graphs,
processed_configurations=processed_configurations,
catch_exceptions=catch_exceptions,
runtime_configuration=runtime_configuration,
)
if metrics is None:
metrics = {}
graph: ValidationGraph = (
self._generate_suite_level_graph_from_expectation_level_sub_graphs(
expectation_validation_graphs=expectation_validation_graphs
)
)
try:
(
evrs,
processed_configurations,
) = self._resolve_suite_level_graph_and_process_metric_evaluation_errors(
validation_graph=graph,
metrics=metrics,
runtime_configuration=runtime_configuration,
expectation_validation_graphs=expectation_validation_graphs,
evrs=evrs,
processed_configurations=processed_configurations,
)
except Exception as err:
# If a general Exception occurs during the execution of "Validator.resolve_validation_graph()", then all
# expectations in the suite are impacted, because it is impossible to attribute the failure to a metric.
if catch_exceptions:
exception_traceback: str = traceback.format_exc()
evrs = self._catch_exceptions_in_failing_expectation_validations(
exception_traceback=exception_traceback,
exception=err,
failing_expectation_configurations=processed_configurations,
evrs=evrs,
)
return evrs
else:
raise err
configuration: ExpectationConfiguration
result: ExpectationValidationResult
for configuration in processed_configurations:
try:
result = configuration.metrics_validate(
metrics,
execution_engine=self._execution_engine,
runtime_configuration=runtime_configuration,
)
evrs.append(result)
except Exception as err:
if catch_exceptions:
exception_traceback: str = traceback.format_exc()
evrs = self._catch_exceptions_in_failing_expectation_validations(
exception_traceback=exception_traceback,
exception=err,
failing_expectation_configurations=[configuration],
evrs=evrs,
)
else:
raise err
return evrs
def _generate_metric_dependency_subgraphs_for_each_expectation_configuration(
self,
expectation_configurations: List[ExpectationConfiguration],
expectation_validation_graphs: List[ExpectationValidationGraph],
processed_configurations: List[ExpectationConfiguration],
catch_exceptions: bool,
runtime_configuration: Optional[dict] = None,
) -> Tuple[List[ExpectationValidationResult], List[ExpectationConfiguration]]:
# While evaluating expectation configurations, create sub-graph for every metric dependency and incorporate
# these sub-graphs under corresponding expectation-level sub-graph (state of ExpectationValidationGraph object).
evrs: List[ExpectationValidationResult] = []
configuration: ExpectationConfiguration
evaluated_config: ExpectationConfiguration
metric_configuration: MetricConfiguration
graph: ValidationGraph
for configuration in expectation_configurations:
# Validating
try:
assert (
configuration.expectation_type is not None
), "Given configuration should include expectation type"
except AssertionError as e:
raise InvalidExpectationConfigurationError(str(e))
evaluated_config = copy.deepcopy(configuration)
evaluated_config.kwargs.update({"batch_id": self.active_batch_id})
expectation_impl = get_expectation_impl(evaluated_config.expectation_type)