acryl-datahub-cloud 0.3.12rc3__py3-none-any.whl → 0.3.12rc4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of acryl-datahub-cloud might be problematic. Click here for more details.

@@ -0,0 +1,947 @@
1
+ import json
2
+ from datetime import datetime
3
+ from typing import Optional, Union
4
+
5
+ from acryl_datahub_cloud.sdk.assertion_input.assertion_input import (
6
+ DEFAULT_HOURLY_SCHEDULE,
7
+ HIGH_WATERMARK_ALLOWED_FIELD_TYPES,
8
+ AssertionIncidentBehavior,
9
+ AssertionInfoInputType,
10
+ DetectionMechanism,
11
+ DetectionMechanismInputTypes,
12
+ ExclusionWindowInputTypes,
13
+ FieldSpecType,
14
+ InferenceSensitivity,
15
+ _AllRowsQuery,
16
+ _AllRowsQueryDataHubDatasetProfile,
17
+ _AssertionInput,
18
+ _ChangedRowsQuery,
19
+ _DatasetProfile,
20
+ _HasSmartAssertionInputs,
21
+ _try_parse_and_validate_schema_classes_enum,
22
+ )
23
+ from acryl_datahub_cloud.sdk.entities.assertion import TagsInputType
24
+ from acryl_datahub_cloud.sdk.errors import (
25
+ SDKNotYetSupportedError,
26
+ SDKUsageError,
27
+ )
28
+ from datahub.emitter.enum_helpers import get_enum_options
29
+ from datahub.metadata import schema_classes as models
30
+ from datahub.metadata.urns import AssertionUrn, CorpUserUrn, DatasetUrn
31
+ from datahub.sdk.entity_client import EntityClient
32
+
33
+ # Keep this in sync with the frontend in getEligibleFieldColumns
34
+ # datahub-web-react/src/app/entityV2/shared/tabs/Dataset/Validations/assertion/builder/steps/field/utils.ts
35
+ ALLOWED_COLUMN_TYPES_FOR_SMART_COLUMN_METRIC_ASSERTION = [
36
+ models.StringTypeClass(),
37
+ models.NumberTypeClass(),
38
+ models.BooleanTypeClass(),
39
+ models.DateTypeClass(),
40
+ models.TimeTypeClass(),
41
+ models.NullTypeClass(),
42
+ ]
43
+
44
+ # Keep this in sync with FIELD_VALUES_OPERATOR_CONFIG in the frontend
45
+ # datahub-web-react/src/app/entityV2/shared/tabs/Dataset/Validations/assertion/builder/steps/field/utils.ts
46
+ FIELD_VALUES_OPERATOR_CONFIG = {
47
+ "StringTypeClass": [
48
+ models.AssertionStdOperatorClass.NULL,
49
+ models.AssertionStdOperatorClass.NOT_NULL,
50
+ models.AssertionStdOperatorClass.EQUAL_TO,
51
+ models.AssertionStdOperatorClass.IN,
52
+ models.AssertionStdOperatorClass.GREATER_THAN_OR_EQUAL_TO,
53
+ models.AssertionStdOperatorClass.REGEX_MATCH,
54
+ models.AssertionStdOperatorClass.GREATER_THAN,
55
+ models.AssertionStdOperatorClass.LESS_THAN,
56
+ models.AssertionStdOperatorClass.BETWEEN,
57
+ ],
58
+ "NumberTypeClass": [
59
+ models.AssertionStdOperatorClass.GREATER_THAN,
60
+ models.AssertionStdOperatorClass.LESS_THAN,
61
+ models.AssertionStdOperatorClass.BETWEEN,
62
+ models.AssertionStdOperatorClass.NULL,
63
+ models.AssertionStdOperatorClass.NOT_NULL,
64
+ models.AssertionStdOperatorClass.EQUAL_TO,
65
+ models.AssertionStdOperatorClass.IN,
66
+ models.AssertionStdOperatorClass.GREATER_THAN_OR_EQUAL_TO,
67
+ models.AssertionStdOperatorClass.NOT_EQUAL_TO,
68
+ ],
69
+ "BooleanTypeClass": [
70
+ models.AssertionStdOperatorClass.IS_TRUE,
71
+ models.AssertionStdOperatorClass.IS_FALSE,
72
+ models.AssertionStdOperatorClass.NULL,
73
+ models.AssertionStdOperatorClass.NOT_NULL,
74
+ ],
75
+ "DateTypeClass": [
76
+ models.AssertionStdOperatorClass.NULL,
77
+ models.AssertionStdOperatorClass.NOT_NULL,
78
+ ],
79
+ "TimeTypeClass": [
80
+ models.AssertionStdOperatorClass.NULL,
81
+ models.AssertionStdOperatorClass.NOT_NULL,
82
+ ],
83
+ "NullTypeClass": [
84
+ models.AssertionStdOperatorClass.NULL,
85
+ models.AssertionStdOperatorClass.NOT_NULL,
86
+ ],
87
+ }
88
+
89
+ # Operators that require a single value parameter
90
+ SINGLE_VALUE_OPERATORS = [
91
+ models.AssertionStdOperatorClass.EQUAL_TO,
92
+ models.AssertionStdOperatorClass.NOT_EQUAL_TO,
93
+ models.AssertionStdOperatorClass.GREATER_THAN,
94
+ models.AssertionStdOperatorClass.LESS_THAN,
95
+ models.AssertionStdOperatorClass.GREATER_THAN_OR_EQUAL_TO,
96
+ models.AssertionStdOperatorClass.LESS_THAN_OR_EQUAL_TO,
97
+ models.AssertionStdOperatorClass.CONTAIN,
98
+ models.AssertionStdOperatorClass.END_WITH,
99
+ models.AssertionStdOperatorClass.START_WITH,
100
+ models.AssertionStdOperatorClass.REGEX_MATCH,
101
+ models.AssertionStdOperatorClass.IN,
102
+ models.AssertionStdOperatorClass.NOT_IN,
103
+ ]
104
+
105
+ # Operators that require a range parameter
106
+ RANGE_OPERATORS = [
107
+ models.AssertionStdOperatorClass.BETWEEN,
108
+ ]
109
+
110
+ # Operators that require no parameters
111
+ NO_PARAMETER_OPERATORS = [
112
+ models.AssertionStdOperatorClass.NULL,
113
+ models.AssertionStdOperatorClass.NOT_NULL,
114
+ models.AssertionStdOperatorClass.IS_TRUE,
115
+ models.AssertionStdOperatorClass.IS_FALSE,
116
+ ]
117
+
118
+ # Keep this in sync with FIELD_METRIC_TYPE_CONFIG in the frontend
119
+ # datahub-web-react/src/app/entityV2/shared/tabs/Dataset/Validations/assertion/builder/steps/field/utils.ts
120
+ FIELD_METRIC_TYPE_CONFIG = {
121
+ "StringTypeClass": [
122
+ models.FieldMetricTypeClass.NULL_COUNT,
123
+ models.FieldMetricTypeClass.NULL_PERCENTAGE,
124
+ models.FieldMetricTypeClass.UNIQUE_COUNT,
125
+ models.FieldMetricTypeClass.UNIQUE_PERCENTAGE,
126
+ models.FieldMetricTypeClass.MAX_LENGTH,
127
+ models.FieldMetricTypeClass.MIN_LENGTH,
128
+ models.FieldMetricTypeClass.EMPTY_COUNT,
129
+ models.FieldMetricTypeClass.EMPTY_PERCENTAGE,
130
+ ],
131
+ "NumberTypeClass": [
132
+ models.FieldMetricTypeClass.NULL_COUNT,
133
+ models.FieldMetricTypeClass.NULL_PERCENTAGE,
134
+ models.FieldMetricTypeClass.UNIQUE_COUNT,
135
+ models.FieldMetricTypeClass.UNIQUE_PERCENTAGE,
136
+ models.FieldMetricTypeClass.MAX,
137
+ models.FieldMetricTypeClass.MIN,
138
+ models.FieldMetricTypeClass.MEAN,
139
+ models.FieldMetricTypeClass.MEDIAN,
140
+ models.FieldMetricTypeClass.STDDEV,
141
+ models.FieldMetricTypeClass.NEGATIVE_COUNT,
142
+ models.FieldMetricTypeClass.NEGATIVE_PERCENTAGE,
143
+ models.FieldMetricTypeClass.ZERO_COUNT,
144
+ models.FieldMetricTypeClass.ZERO_PERCENTAGE,
145
+ ],
146
+ "BooleanTypeClass": [
147
+ models.FieldMetricTypeClass.NULL_COUNT,
148
+ models.FieldMetricTypeClass.NULL_PERCENTAGE,
149
+ models.FieldMetricTypeClass.UNIQUE_COUNT,
150
+ models.FieldMetricTypeClass.UNIQUE_PERCENTAGE,
151
+ ],
152
+ "DateTypeClass": [
153
+ models.FieldMetricTypeClass.NULL_COUNT,
154
+ models.FieldMetricTypeClass.NULL_PERCENTAGE,
155
+ models.FieldMetricTypeClass.UNIQUE_COUNT,
156
+ models.FieldMetricTypeClass.UNIQUE_PERCENTAGE,
157
+ ],
158
+ "TimeTypeClass": [
159
+ models.FieldMetricTypeClass.NULL_COUNT,
160
+ models.FieldMetricTypeClass.NULL_PERCENTAGE,
161
+ models.FieldMetricTypeClass.UNIQUE_COUNT,
162
+ models.FieldMetricTypeClass.UNIQUE_PERCENTAGE,
163
+ ],
164
+ "NullTypeClass": [
165
+ models.FieldMetricTypeClass.NULL_COUNT,
166
+ models.FieldMetricTypeClass.NULL_PERCENTAGE,
167
+ models.FieldMetricTypeClass.UNIQUE_COUNT,
168
+ models.FieldMetricTypeClass.UNIQUE_PERCENTAGE,
169
+ ],
170
+ }
171
+
172
+
173
+ MetricInputType = Union[models.FieldMetricTypeClass, str]
174
+ ValueInputType = Union[str, int, float]
175
+ ValueTypeInputType = Union[str, models.AssertionStdParameterTypeClass]
176
+ RangeInputType = tuple[ValueInputType, ValueInputType]
177
+ RangeTypeInputType = Union[
178
+ str,
179
+ tuple[str, str],
180
+ ValueTypeInputType,
181
+ tuple[ValueTypeInputType, ValueTypeInputType],
182
+ ]
183
+ RangeTypeParsedType = tuple[ValueTypeInputType, ValueTypeInputType]
184
+ OperatorInputType = Union[str, models.AssertionStdOperatorClass]
185
+
186
+ DEFAULT_DETECTION_MECHANISM_SMART_COLUMN_METRIC_ASSERTION = (
187
+ DetectionMechanism.ALL_ROWS_QUERY
188
+ )
189
+
190
+
191
+ class _SmartColumnMetricAssertionInput(_AssertionInput, _HasSmartAssertionInputs):
192
+ """
193
+ Input used to create a smart column metric assertion.
194
+
195
+ This assertion is used to validate the value of a common field / column metric (e.g. aggregation) such as null count + percentage,
196
+ min, max, median, and more. It uses AI to infer the assertion parameters.
197
+
198
+ Example using the entity models, not comprehensive for all options:
199
+
200
+ ```python
201
+ models.AssertionInfoClass(
202
+ type=models.AssertionTypeClass.FIELD,
203
+ fieldAssertion=FieldAssertionInfoClass(
204
+ type=models.FieldAssertionTypeClass.FIELD_METRIC,
205
+ entity=str(self.dataset_urn),
206
+ filter=DatasetFilterClass(
207
+ type=models.DatasetFilterTypeClass.SQL,
208
+ sql="SELECT * FROM dataset WHERE column_name = 'value'", # Example filter
209
+ ),
210
+ fieldMetricAssertion=FieldMetricAssertionClass(
211
+ field=SchemaFieldSpecClass(
212
+ path="column_name", # The column name to validate
213
+ type="string", # The type of the column
214
+ nativeType="string", # The native type of the column
215
+ ),
216
+ metric=models.FieldMetricTypeClass.NULL_COUNT_PERCENTAGE, # The metric to validate
217
+ operator=models.AssertionStdOperatorClass.GREATER_THAN, # The operator to use
218
+ parameters=models.AssertionStdParametersClass(
219
+ value=models.AssertionStdParameterClass(
220
+ value=10, # The value to validate
221
+ type=models.AssertionStdParameterTypeClass.NUMBER, # The type of the value
222
+ ),
223
+ ),
224
+ ),
225
+ ),
226
+ source=models.AssertionSourceClass(
227
+ type=models.AssertionSourceTypeClass.INFERRED, # Smart assertions are of type inferred, not native
228
+ created=AuditStampClass(
229
+ time=1717929600,
230
+ actor="urn:li:corpuser:jdoe", # The actor who created the assertion
231
+ ),
232
+ ),
233
+ lastUpdated=AuditStampClass(
234
+ time=1717929600,
235
+ actor="urn:li:corpuser:jdoe", # The actor who last updated the assertion
236
+ ),
237
+ description="This assertion validates the null count percentage of the column 'column_name' is greater than 10.", # Optional description of the assertion
238
+ )
239
+ ```
240
+
241
+ ```python
242
+ models.MonitorInfoClass(
243
+ type=models.MonitorTypeClass.ASSERTION,
244
+ status=models.MonitorStatusClass(
245
+ mode=models.MonitorModeClass.ACTIVE, # Active or Inactive
246
+ ),
247
+ assertionMonitor=AssertionMonitorClass(
248
+ assertions=AssertionEvaluationSpecClass(
249
+ assertion="urn:li:assertion:123", # The assertion to monitor
250
+ schedule=models.CronScheduleClass(
251
+ cron="0 0 * * *", # The cron schedule
252
+ timezone="America/New_York", # The timezone
253
+ ),
254
+ parameters=models.AssertionEvaluationParametersClass(
255
+ type=models.AssertionEvaluationParametersTypeClass.DATASET_FIELD,
256
+ datasetFieldParameters=models.DatasetFieldAssertionParametersClass(
257
+ sourceType=models.DatasetFieldAssertionSourceTypeClass.CHANGED_ROWS_QUERY, # This can be ALL_ROWS_QUERY, CHANGED_ROWS_QUERY or DATAHUB_DATASET_PROFILE
258
+ changedRowsField=models.FreshnessFieldSpecClass(
259
+ path="column_name",
260
+ type="string",
261
+ nativeType="string",
262
+ kind=models.FreshnessFieldKindClass.HIGH_WATERMARK, # This can be LAST_MODIFIED or HIGH_WATERMARK
263
+ ),
264
+ ),
265
+ ),
266
+ ),
267
+ settings=models.AssertionMonitorSettingsClass(
268
+ adjustmentSettings=models.AssertionAdjustmentSettingsClass(
269
+ algorithm=models.AdjustmentAlgorithmClass.CUSTOM, # TODO: Do we need to set this in the SDK?
270
+ algorithmName="stddev", # TODO: Do we need to set this in the SDK? What are acceptable values?
271
+ context={
272
+ "stdDev": "1.0", # TODO: Do we need to set this in the SDK? What are acceptable values?
273
+ },
274
+ exclusionWindows=[models.AssertionExclusionWindowClass(
275
+ type=models.AssertionExclusionWindowTypeClass.FIXED_RANGE,
276
+ start=1717929600,
277
+ end=1717929600,
278
+ )],
279
+ trainingDataLookbackWindowDays=10, # The number of days to look back for training data
280
+ sensitivity=models.AssertionMonitorSensitivityClass(
281
+ level=1, # The sensitivity level
282
+ ),
283
+ ),
284
+ ),
285
+ ),
286
+ )
287
+ ```
288
+ """
289
+
290
+ def __init__(
291
+ self,
292
+ *,
293
+ # Required parameters
294
+ dataset_urn: Union[str, DatasetUrn],
295
+ entity_client: EntityClient,
296
+ column_name: str,
297
+ metric_type: MetricInputType,
298
+ operator: OperatorInputType,
299
+ # Optional parameters
300
+ value: Optional[ValueInputType] = None,
301
+ value_type: Optional[ValueTypeInputType] = None,
302
+ range: Optional[RangeInputType] = None,
303
+ range_type: Optional[RangeTypeInputType] = None,
304
+ urn: Optional[Union[str, AssertionUrn]] = None,
305
+ display_name: Optional[str] = None,
306
+ enabled: bool = True,
307
+ schedule: Optional[Union[str, models.CronScheduleClass]] = None,
308
+ detection_mechanism: DetectionMechanismInputTypes = None,
309
+ sensitivity: Optional[Union[str, InferenceSensitivity]] = None,
310
+ exclusion_windows: Optional[ExclusionWindowInputTypes] = None,
311
+ training_data_lookback_days: Optional[int] = None,
312
+ incident_behavior: Optional[
313
+ Union[AssertionIncidentBehavior, list[AssertionIncidentBehavior]]
314
+ ] = None,
315
+ tags: Optional[TagsInputType] = None,
316
+ created_by: Union[str, CorpUserUrn],
317
+ created_at: datetime,
318
+ updated_by: Union[str, CorpUserUrn],
319
+ updated_at: datetime,
320
+ ):
321
+ """
322
+ Initialize a smart column metric assertion input.
323
+
324
+ Args:
325
+ dataset_urn: The dataset urn.
326
+ entity_client: The entity client.
327
+ column_name: The name of the column to validate.
328
+ metric_type: The metric type to validate.
329
+ operator: The operator to use.
330
+ value: The value to validate.
331
+ value_type: The type of the value.
332
+ range: The range to validate.
333
+ range_type: The type of the range. If single value, we assume the same type for start and end.
334
+ urn: The urn of the assertion.
335
+ display_name: The display name of the assertion.
336
+ enabled: Whether the assertion is enabled.
337
+ schedule: The schedule of the assertion.
338
+ detection_mechanism: The detection mechanism of the assertion.
339
+ sensitivity: The sensitivity of the assertion.
340
+ exclusion_windows: The exclusion windows of the assertion.
341
+ training_data_lookback_days: The training data lookback days of the assertion.
342
+ incident_behavior: The incident behavior of the assertion.
343
+ tags: The tags of the assertion.
344
+ created_by: The creator of the assertion.
345
+ created_at: The creation time of the assertion.
346
+ updated_by: The updater of the assertion.
347
+ updated_at: The update time of the assertion.
348
+ """
349
+ # Parent will handle validation of common parameters:
350
+ _AssertionInput.__init__(
351
+ self,
352
+ dataset_urn=dataset_urn,
353
+ entity_client=entity_client,
354
+ urn=urn,
355
+ display_name=display_name,
356
+ enabled=enabled,
357
+ schedule=schedule,
358
+ detection_mechanism=detection_mechanism,
359
+ incident_behavior=incident_behavior,
360
+ tags=tags,
361
+ source_type=models.AssertionSourceTypeClass.INFERRED, # Smart assertions are of type inferred, not native
362
+ created_by=created_by,
363
+ created_at=created_at,
364
+ updated_by=updated_by,
365
+ updated_at=updated_at,
366
+ default_detection_mechanism=DEFAULT_DETECTION_MECHANISM_SMART_COLUMN_METRIC_ASSERTION,
367
+ )
368
+ _HasSmartAssertionInputs.__init__(
369
+ self,
370
+ sensitivity=sensitivity,
371
+ exclusion_windows=exclusion_windows,
372
+ training_data_lookback_days=training_data_lookback_days,
373
+ )
374
+
375
+ # Validate Smart Column Metric Assertion specific parameters
376
+ self.metric_type = _try_parse_and_validate_schema_classes_enum(
377
+ metric_type, models.FieldMetricTypeClass
378
+ )
379
+ self.column_name = self._try_parse_and_validate_column_name_is_valid_type(
380
+ column_name
381
+ )
382
+ self.operator = _try_parse_and_validate_schema_classes_enum(
383
+ operator, models.AssertionStdOperatorClass
384
+ )
385
+
386
+ # Set type annotations for both raw input or parsed parameters
387
+ self.value_type: Optional[ValueTypeInputType] = None
388
+ self.value: Optional[ValueInputType] = None
389
+ if _is_value_required_for_operator(self.operator):
390
+ self.value_type = _try_parse_and_validate_value_type(value_type)
391
+ self.value = _try_parse_and_validate_value(value, self.value_type)
392
+ else:
393
+ # Set these to what was input for later validation, and skip parsing and validation
394
+ self.value_type = value_type
395
+ self.value = value
396
+
397
+ # Set type annotations for both raw input or parsed parameters
398
+ self.range_type: Optional[Union[RangeTypeInputType, RangeTypeParsedType]] = None
399
+ self.range: Optional[RangeInputType] = None
400
+ if _is_range_required_for_operator(self.operator):
401
+ self.range_type = _try_parse_and_validate_range_type(range_type)
402
+ self.range = _try_parse_and_validate_range(
403
+ range, self.range_type, self.operator
404
+ )
405
+ else:
406
+ # Set these to what was input for later validation, and skip parsing and validation
407
+ self.range_type = range_type
408
+ self.range = range
409
+
410
+ _validate_operator_and_input_parameters(
411
+ operator=self.operator,
412
+ value=self.value,
413
+ value_type=_try_parse_and_validate_value_type(self.value_type)
414
+ if self.value_type is not None
415
+ else None,
416
+ range=self.range,
417
+ range_type=_try_parse_and_validate_range_type(self.range_type)
418
+ if self.range_type is not None
419
+ else None,
420
+ )
421
+
422
+ # Validate compatibility:
423
+ self._validate_field_type_and_operator_compatibility(
424
+ self.column_name, self.operator
425
+ )
426
+ self._validate_field_type_and_metric_type_compatibility(
427
+ self.column_name, self.metric_type
428
+ )
429
+ self._validate_operator_and_range_or_value_compatibility(
430
+ self.operator,
431
+ self.value,
432
+ _try_parse_and_validate_value_type(self.value_type)
433
+ if self.value_type is not None
434
+ else None,
435
+ self.range,
436
+ _try_parse_and_validate_range_type(self.range_type)
437
+ if self.range_type is not None
438
+ else None,
439
+ )
440
+
441
+ def _create_monitor_info(
442
+ self,
443
+ assertion_urn: AssertionUrn,
444
+ status: models.MonitorStatusClass,
445
+ schedule: models.CronScheduleClass,
446
+ source_type: Union[str, models.DatasetFreshnessSourceTypeClass],
447
+ field: Optional[FieldSpecType],
448
+ ) -> models.MonitorInfoClass:
449
+ """
450
+ Create a MonitorInfoClass with all the necessary components.
451
+ """
452
+ return models.MonitorInfoClass(
453
+ type=models.MonitorTypeClass.ASSERTION,
454
+ status=status,
455
+ assertionMonitor=models.AssertionMonitorClass(
456
+ assertions=[
457
+ models.AssertionEvaluationSpecClass(
458
+ assertion=str(assertion_urn),
459
+ schedule=schedule,
460
+ parameters=self._get_assertion_evaluation_parameters(
461
+ str(source_type), field
462
+ ),
463
+ ),
464
+ ],
465
+ settings=models.AssertionMonitorSettingsClass(
466
+ adjustmentSettings=models.AssertionAdjustmentSettingsClass(
467
+ sensitivity=self._convert_sensitivity(),
468
+ exclusionWindows=self._convert_exclusion_windows(),
469
+ trainingDataLookbackWindowDays=self.training_data_lookback_days,
470
+ ),
471
+ ),
472
+ ),
473
+ )
474
+
475
+ def _create_assertion_info(
476
+ self, filter: Optional[models.DatasetFilterClass]
477
+ ) -> AssertionInfoInputType:
478
+ """
479
+ Create a FieldAssertionInfoClass for a smart column metric assertion.
480
+
481
+ Args:
482
+ filter: Optional filter to apply to the assertion.
483
+
484
+ Returns:
485
+ A FieldAssertionInfoClass configured for smart column metric.
486
+ """
487
+ # Get the field spec for the column
488
+ field_spec = self._get_schema_field_spec(self.column_name)
489
+
490
+ # Create the field metric assertion
491
+ field_metric_assertion = models.FieldMetricAssertionClass(
492
+ field=field_spec,
493
+ metric=self.metric_type,
494
+ operator=self.operator,
495
+ parameters=self._create_assertion_parameters(),
496
+ )
497
+
498
+ # Create the field assertion info
499
+ return models.FieldAssertionInfoClass(
500
+ type=models.FieldAssertionTypeClass.FIELD_METRIC,
501
+ entity=str(self.dataset_urn),
502
+ filter=filter,
503
+ fieldMetricAssertion=field_metric_assertion,
504
+ fieldValuesAssertion=None, # Explicitly set to None since this is a field metric assertion
505
+ )
506
+
507
+ def _convert_schedule(self) -> models.CronScheduleClass:
508
+ """
509
+ Create a schedule for a smart column metric assertion.
510
+
511
+ Returns:
512
+ A CronScheduleClass with appropriate schedule settings.
513
+ """
514
+ if self.schedule is None:
515
+ return DEFAULT_HOURLY_SCHEDULE
516
+
517
+ return models.CronScheduleClass(
518
+ cron=self.schedule.cron,
519
+ timezone=self.schedule.timezone,
520
+ )
521
+
522
+ def _convert_schema_field_spec_to_freshness_field_spec(
523
+ self, field_spec: models.SchemaFieldSpecClass
524
+ ) -> models.FreshnessFieldSpecClass:
525
+ """
526
+ Convert a SchemaFieldSpecClass to a FreshnessFieldSpecClass.
527
+ """
528
+ return models.FreshnessFieldSpecClass(
529
+ path=field_spec.path,
530
+ type=field_spec.type,
531
+ nativeType=field_spec.nativeType,
532
+ kind=models.FreshnessFieldKindClass.HIGH_WATERMARK,
533
+ )
534
+
535
+ def _get_assertion_evaluation_parameters(
536
+ self, source_type: str, field: Optional[FieldSpecType]
537
+ ) -> models.AssertionEvaluationParametersClass:
538
+ """
539
+ Get evaluation parameters for a smart column metric assertion.
540
+ Converts SchemaFieldSpecClass to FreshnessFieldSpecClass if needed.
541
+ """
542
+ if field is not None:
543
+ if isinstance(field, models.SchemaFieldSpecClass):
544
+ field = self._convert_schema_field_spec_to_freshness_field_spec(field)
545
+ assert isinstance(field, models.FreshnessFieldSpecClass), (
546
+ "Field must be FreshnessFieldSpecClass for monitor info"
547
+ )
548
+ return models.AssertionEvaluationParametersClass(
549
+ type=models.AssertionEvaluationParametersTypeClass.DATASET_FIELD,
550
+ datasetFieldParameters=models.DatasetFieldAssertionParametersClass(
551
+ sourceType=source_type,
552
+ changedRowsField=field,
553
+ ),
554
+ )
555
+
556
+ def _convert_assertion_source_type_and_field(
557
+ self,
558
+ ) -> tuple[str, Optional[FieldSpecType]]:
559
+ """
560
+ Convert detection mechanism into source type and field specification for column metric assertions.
561
+
562
+ Returns:
563
+ A tuple of (source_type, field) where field may be None.
564
+ Note that the source_type is a string, not a models.DatasetFieldAssertionSourceTypeClass (or other assertion source type) since
565
+ the source type is not a enum in the code generated from the DatasetFieldSourceType enum in the PDL.
566
+
567
+ Raises:
568
+ SDKNotYetSupportedError: If the detection mechanism is not supported.
569
+ SDKUsageError: If the field (column) is not found in the dataset,
570
+ and the detection mechanism requires a field. Also if the field
571
+ is not an allowed type for the detection mechanism.
572
+ """
573
+ source_type = models.DatasetFieldAssertionSourceTypeClass.ALL_ROWS_QUERY
574
+ field = None
575
+
576
+ if isinstance(self.detection_mechanism, _ChangedRowsQuery):
577
+ source_type = models.DatasetFieldAssertionSourceTypeClass.CHANGED_ROWS_QUERY
578
+ column_name = self._try_parse_and_validate_column_name_is_valid_type(
579
+ self.detection_mechanism.column_name, # The high watermark column name
580
+ allowed_column_types=HIGH_WATERMARK_ALLOWED_FIELD_TYPES,
581
+ )
582
+ field = self._get_schema_field_spec(column_name)
583
+ elif isinstance(self.detection_mechanism, _AllRowsQuery):
584
+ source_type = models.DatasetFieldAssertionSourceTypeClass.ALL_ROWS_QUERY
585
+ # For query-based detection, we don't need a field specification
586
+ # as the query itself defines what data to analyze
587
+ elif isinstance(
588
+ self.detection_mechanism,
589
+ (_AllRowsQueryDataHubDatasetProfile, _DatasetProfile),
590
+ ):
591
+ source_type = (
592
+ models.DatasetFieldAssertionSourceTypeClass.DATAHUB_DATASET_PROFILE
593
+ )
594
+ # Note: This is only valid on the all rows query
595
+ else:
596
+ raise SDKNotYetSupportedError(
597
+ f"Detection mechanism {self.detection_mechanism} is not supported"
598
+ )
599
+
600
+ return source_type, field
601
+
602
+ def _validate_single_value_operator(
603
+ self,
604
+ operator: models.AssertionStdOperatorClass,
605
+ value: Optional[ValueInputType],
606
+ value_type: Optional[models.AssertionStdParameterTypeClass],
607
+ range: Optional[RangeInputType],
608
+ range_type: Optional[RangeTypeParsedType],
609
+ ) -> None:
610
+ """Validate parameters for a single value operator."""
611
+ if value is None:
612
+ raise SDKUsageError(f"Value is required for operator {operator}")
613
+ if value_type is None:
614
+ raise SDKUsageError(f"Value type is required for operator {operator}")
615
+ if range is not None or range_type is not None:
616
+ raise SDKUsageError(
617
+ f"Range parameters should not be provided for operator {operator}"
618
+ )
619
+
620
+ def _validate_range_operator(
621
+ self,
622
+ operator: models.AssertionStdOperatorClass,
623
+ value: Optional[ValueInputType],
624
+ value_type: Optional[models.AssertionStdParameterTypeClass],
625
+ range: Optional[RangeInputType],
626
+ range_type: Optional[RangeTypeParsedType],
627
+ ) -> None:
628
+ """Validate parameters for a range operator."""
629
+ if range is None:
630
+ raise SDKUsageError(f"Range is required for operator {operator}")
631
+ if range_type is None:
632
+ raise SDKUsageError(f"Range type is required for operator {operator}")
633
+ if value is not None or value_type is not None:
634
+ raise SDKUsageError(
635
+ f"Value parameters should not be provided for operator {operator}"
636
+ )
637
+
638
+ def _validate_no_parameter_operator(
639
+ self,
640
+ operator: models.AssertionStdOperatorClass,
641
+ value: Optional[ValueInputType],
642
+ value_type: Optional[models.AssertionStdParameterTypeClass],
643
+ range: Optional[RangeInputType],
644
+ range_type: Optional[RangeTypeParsedType],
645
+ ) -> None:
646
+ """Validate parameters for a no-parameter operator."""
647
+ if value is not None or value_type is not None:
648
+ raise SDKUsageError(
649
+ f"Value parameters should not be provided for operator {operator}"
650
+ )
651
+ if range is not None or range_type is not None:
652
+ raise SDKUsageError(
653
+ f"Range parameters should not be provided for operator {operator}"
654
+ )
655
+
656
+ def _validate_operator_and_range_or_value_compatibility(
657
+ self,
658
+ operator: models.AssertionStdOperatorClass,
659
+ value: Optional[ValueInputType] = None,
660
+ value_type: Optional[models.AssertionStdParameterTypeClass] = None,
661
+ range: Optional[RangeInputType] = None,
662
+ range_type: Optional[RangeTypeParsedType] = None,
663
+ ) -> None:
664
+ """
665
+ Validate that the operator has the appropriate parameters (range or value) based on its type.
666
+
667
+ Args:
668
+ operator: The operator to validate.
669
+ value: Optional value parameter.
670
+ value_type: Optional value type parameter.
671
+ range: Optional range parameter.
672
+ range_type: Optional range type parameter.
673
+
674
+ Raises:
675
+ SDKUsageError: If the operator parameters are not compatible with the operator type.
676
+ """
677
+ if operator in SINGLE_VALUE_OPERATORS:
678
+ self._validate_single_value_operator(
679
+ operator, value, value_type, range, range_type
680
+ )
681
+ elif operator in RANGE_OPERATORS:
682
+ self._validate_range_operator(
683
+ operator, value, value_type, range, range_type
684
+ )
685
+ elif operator in NO_PARAMETER_OPERATORS:
686
+ self._validate_no_parameter_operator(
687
+ operator, value, value_type, range, range_type
688
+ )
689
+ else:
690
+ raise SDKUsageError(f"Unsupported operator type: {operator}")
691
+
692
+ def _create_assertion_parameters(self) -> models.AssertionStdParametersClass:
693
+ """
694
+ Create assertion parameters based on the operator type and provided values.
695
+
696
+ Returns:
697
+ An AssertionStdParametersClass with the appropriate parameters.
698
+
699
+ Raises:
700
+ SDKUsageError: If the parameters are invalid for the operator type.
701
+ """
702
+ if self.operator in SINGLE_VALUE_OPERATORS:
703
+ if self.value is None:
704
+ raise SDKUsageError(f"Value is required for operator {self.operator}")
705
+ if self.value_type is None:
706
+ raise SDKUsageError(
707
+ f"Value type is required for operator {self.operator}"
708
+ )
709
+ return models.AssertionStdParametersClass(
710
+ value=models.AssertionStdParameterClass(
711
+ value=str(self.value),
712
+ type=self.value_type,
713
+ ),
714
+ )
715
+ elif self.operator in RANGE_OPERATORS:
716
+ if self.range is None:
717
+ raise SDKUsageError(f"Range is required for operator {self.operator}")
718
+ if self.range_type is None:
719
+ raise SDKUsageError(
720
+ f"Range type is required for operator {self.operator}"
721
+ )
722
+ # Ensure we have the parsed range type
723
+ parsed_range_type = _try_parse_and_validate_range_type(self.range_type)
724
+ return models.AssertionStdParametersClass(
725
+ minValue=models.AssertionStdParameterClass(
726
+ value=str(self.range[0]),
727
+ type=parsed_range_type[0],
728
+ ),
729
+ maxValue=models.AssertionStdParameterClass(
730
+ value=str(self.range[1]),
731
+ type=parsed_range_type[1],
732
+ ),
733
+ )
734
+ elif self.operator in NO_PARAMETER_OPERATORS:
735
+ return models.AssertionStdParametersClass()
736
+ else:
737
+ raise SDKUsageError(f"Unsupported operator type: {self.operator}")
738
+
739
+ def _try_parse_and_validate_column_name_is_valid_type(
740
+ self,
741
+ column_name: str,
742
+ allowed_column_types: list[
743
+ models.DictWrapper
744
+ ] = ALLOWED_COLUMN_TYPES_FOR_SMART_COLUMN_METRIC_ASSERTION,
745
+ ) -> str:
746
+ """
747
+ Parse and validate a column name. Determine from the field spec if the column exists and is of the appropriate type for the metric type.
748
+ Validate that this is a column that is valid for the metric type, see also getEligibleFieldColumns and related functions in the frontend
749
+ """
750
+ field_spec = self._get_schema_field_spec(column_name)
751
+ self._validate_field_type(
752
+ field_spec,
753
+ column_name,
754
+ allowed_column_types,
755
+ "smart column metric assertion",
756
+ )
757
+ return column_name
758
+
759
+ def _assertion_type(self) -> str:
760
+ """Get the assertion type."""
761
+ return models.AssertionTypeClass.FIELD
762
+
763
+ def _validate_field_type_and_operator_compatibility(
764
+ self, column_name: str, operator: models.AssertionStdOperatorClass
765
+ ) -> None:
766
+ """Validate that the field type is compatible with the operator.
767
+
768
+ See FIELD_VALUES_OPERATOR_CONFIG in the frontend for the allowed operators for each field type.
769
+
770
+ Args:
771
+ column_name: The name of the column to validate.
772
+ operator: The operator to validate against.
773
+
774
+ Raises:
775
+ SDKUsageError: If the field type is not compatible with the operator.
776
+ """
777
+ field_spec = self._get_schema_field_spec(column_name)
778
+ allowed_operators = FIELD_VALUES_OPERATOR_CONFIG.get(field_spec.type, [])
779
+ if operator not in allowed_operators:
780
+ raise SDKUsageError(
781
+ f"Operator {operator} is not allowed for field type {field_spec.type} for column '{column_name}'. Allowed operators: {', '.join(str(op) for op in allowed_operators)}"
782
+ )
783
+
784
+ def _validate_field_type_and_metric_type_compatibility(
785
+ self, column_name: str, metric_type: models.FieldMetricTypeClass
786
+ ) -> None:
787
+ """Validate that the metric type is compatible with the field type.
788
+
789
+ See FIELD_METRIC_TYPE_CONFIG in the frontend for the allowed metric types for each field type.
790
+
791
+ Args:
792
+ column_name: The name of the column to validate.
793
+ metric_type: The metric type to validate.
794
+
795
+ Raises:
796
+ SDKUsageError: If the metric type is not compatible with the field type.
797
+ """
798
+ field_spec = self._get_schema_field_spec(column_name)
799
+ field_type = field_spec.type
800
+
801
+ if field_type not in FIELD_METRIC_TYPE_CONFIG:
802
+ raise SDKUsageError(
803
+ f"Column {column_name} is of type {field_type}, which is not supported for smart column metric assertions"
804
+ )
805
+
806
+ allowed_metric_types = FIELD_METRIC_TYPE_CONFIG[field_type]
807
+ if metric_type not in allowed_metric_types:
808
+ raise SDKUsageError(
809
+ f"Metric type {metric_type} is not allowed for field type {field_type}. Allowed metric types: {', '.join(str(mt) for mt in allowed_metric_types)}"
810
+ )
811
+
812
+
813
+ def _try_parse_and_validate_value_type(
814
+ value_type: Optional[ValueTypeInputType],
815
+ ) -> models.AssertionStdParameterTypeClass:
816
+ if value_type is None:
817
+ raise SDKUsageError("Value type is required")
818
+ if isinstance(value_type, models.AssertionStdParameterTypeClass):
819
+ return value_type
820
+ if value_type not in get_enum_options(models.AssertionStdParameterTypeClass):
821
+ raise SDKUsageError(
822
+ f"Invalid value type: {value_type}, valid options are {get_enum_options(models.AssertionStdParameterTypeClass)}"
823
+ )
824
+ return getattr(models.AssertionStdParameterTypeClass, value_type)
825
+
826
+
827
+ def _try_parse_and_validate_value(
828
+ value: Optional[ValueInputType],
829
+ value_type: ValueTypeInputType,
830
+ ) -> ValueInputType:
831
+ if value is None:
832
+ raise SDKUsageError("Value parameter is required for the chosen operator")
833
+ # Accept both Python types and JSON strings
834
+ if isinstance(value, str):
835
+ # Try to parse as JSON, but if it fails, treat as a raw string
836
+ try:
837
+ deserialized_value = json.loads(value)
838
+ except json.JSONDecodeError:
839
+ deserialized_value = value
840
+ else:
841
+ deserialized_value = value
842
+ # Validate that the value is of the correct type
843
+ if value_type == models.AssertionStdParameterTypeClass.NUMBER:
844
+ if not isinstance(deserialized_value, (int, float)):
845
+ raise SDKUsageError(f"Invalid value: {value}, must be a number")
846
+ elif value_type == models.AssertionStdParameterTypeClass.STRING:
847
+ if not isinstance(deserialized_value, str):
848
+ raise SDKUsageError(f"Invalid value: {value}, must be a string")
849
+ elif (
850
+ value_type == models.AssertionStdParameterTypeClass.LIST
851
+ or value_type == models.AssertionStdParameterTypeClass.SET
852
+ ):
853
+ raise SDKNotYetSupportedError(
854
+ "List and set value types are not supported for smart column metric assertions"
855
+ )
856
+ elif value_type == models.AssertionStdParameterTypeClass.UNKNOWN:
857
+ pass # TODO: What to do with unknown?
858
+ else:
859
+ raise SDKUsageError(
860
+ f"Invalid value type: {value_type}, valid options are {get_enum_options(models.AssertionStdParameterTypeClass)}"
861
+ )
862
+ return deserialized_value
863
+
864
+
865
+ def _is_range_required_for_operator(operator: models.AssertionStdOperatorClass) -> bool:
866
+ return operator in RANGE_OPERATORS
867
+
868
+
869
+ def _is_value_required_for_operator(operator: models.AssertionStdOperatorClass) -> bool:
870
+ return operator in SINGLE_VALUE_OPERATORS
871
+
872
+
873
+ def _is_no_parameter_operator(operator: models.AssertionStdOperatorClass) -> bool:
874
+ return operator in NO_PARAMETER_OPERATORS
875
+
876
+
877
+ def _validate_operator_and_input_parameters(
878
+ operator: models.AssertionStdOperatorClass,
879
+ value: Optional[ValueInputType] = None,
880
+ value_type: Optional[models.AssertionStdParameterTypeClass] = None,
881
+ range: Optional[RangeInputType] = None,
882
+ range_type: Optional[RangeTypeParsedType] = None,
883
+ ) -> None:
884
+ if _is_value_required_for_operator(operator):
885
+ if value is None:
886
+ raise SDKUsageError(f"Value is required for operator {operator}")
887
+ if value_type is None:
888
+ raise SDKUsageError(f"Value type is required for operator {operator}")
889
+ elif _is_range_required_for_operator(operator):
890
+ if range is None:
891
+ raise SDKUsageError(f"Range is required for operator {operator}")
892
+ if range_type is None:
893
+ raise SDKUsageError(f"Range type is required for operator {operator}")
894
+ elif _is_no_parameter_operator(operator):
895
+ if value is not None or value_type is not None:
896
+ raise SDKUsageError(
897
+ f"Value parameters should not be provided for operator {operator}"
898
+ )
899
+ if range is not None or range_type is not None:
900
+ raise SDKUsageError(
901
+ f"Range parameters should not be provided for operator {operator}"
902
+ )
903
+ else:
904
+ raise SDKUsageError(f"Unsupported operator type: {operator}")
905
+
906
+
907
+ def _try_parse_and_validate_range_type(
908
+ range_type: Optional[RangeTypeInputType] = None,
909
+ ) -> RangeTypeParsedType:
910
+ if range_type is None:
911
+ return (
912
+ models.AssertionStdParameterTypeClass.UNKNOWN,
913
+ models.AssertionStdParameterTypeClass.UNKNOWN,
914
+ )
915
+ if isinstance(range_type, tuple):
916
+ return (
917
+ _try_parse_and_validate_schema_classes_enum(
918
+ range_type[0], models.AssertionStdParameterTypeClass
919
+ ),
920
+ _try_parse_and_validate_schema_classes_enum(
921
+ range_type[1], models.AssertionStdParameterTypeClass
922
+ ),
923
+ )
924
+ # Single value, we assume the same type for start and end:
925
+ parsed_range_type = _try_parse_and_validate_schema_classes_enum(
926
+ range_type, models.AssertionStdParameterTypeClass
927
+ )
928
+ return parsed_range_type, parsed_range_type
929
+
930
+
931
+ def _try_parse_and_validate_range(
932
+ range: Optional[RangeInputType],
933
+ range_type: RangeTypeParsedType,
934
+ operator: models.AssertionStdOperatorClass,
935
+ ) -> RangeInputType:
936
+ if (range is None or range_type is None) and _is_range_required_for_operator(
937
+ operator
938
+ ):
939
+ raise SDKUsageError(f"Range is required for operator {operator}")
940
+
941
+ if range is None:
942
+ raise SDKUsageError(f"Range is required for operator {operator}")
943
+
944
+ range_start = _try_parse_and_validate_value(range[0], range_type[0])
945
+ range_end = _try_parse_and_validate_value(range[1], range_type[1])
946
+
947
+ return (range_start, range_end)