acryl-datahub 1.1.0.4rc2__py3-none-any.whl → 1.1.0.4rc3__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 might be problematic. Click here for more details.

@@ -51,7 +51,11 @@ from datahub.ingestion.source.state.stale_entity_removal_handler import (
51
51
  from datahub.ingestion.source.state.stateful_ingestion_base import (
52
52
  StatefulIngestionSourceBase,
53
53
  )
54
- from datahub.ingestion.source_report.ingestion_stage import PROFILING
54
+ from datahub.ingestion.source_report.ingestion_stage import (
55
+ LINEAGE_EXTRACTION,
56
+ METADATA_EXTRACTION,
57
+ PROFILING,
58
+ )
55
59
  from datahub.metadata.com.linkedin.pegasus2avro.dataset import (
56
60
  DatasetLineageTypeClass,
57
61
  UpstreamClass,
@@ -89,6 +93,7 @@ class DremioSourceMapEntry:
89
93
  @capability(SourceCapability.LINEAGE_COARSE, "Enabled by default")
90
94
  @capability(SourceCapability.OWNERSHIP, "Enabled by default")
91
95
  @capability(SourceCapability.PLATFORM_INSTANCE, "Enabled by default")
96
+ @capability(SourceCapability.USAGE_STATS, "Enabled by default to get usage stats")
92
97
  class DremioSource(StatefulIngestionSourceBase):
93
98
  """
94
99
  This plugin integrates with Dremio to extract and ingest metadata into DataHub.
@@ -126,6 +131,13 @@ class DremioSource(StatefulIngestionSourceBase):
126
131
  self.default_db = "dremio"
127
132
  self.config = config
128
133
  self.report = DremioSourceReport()
134
+
135
+ # Set time window for query lineage extraction
136
+ self.report.window_start_time, self.report.window_end_time = (
137
+ self.config.start_time,
138
+ self.config.end_time,
139
+ )
140
+
129
141
  self.source_map: Dict[str, DremioSourceMapEntry] = dict()
130
142
 
131
143
  # Initialize API operations
@@ -154,6 +166,7 @@ class DremioSource(StatefulIngestionSourceBase):
154
166
  generate_operations=True,
155
167
  usage_config=self.config.usage,
156
168
  )
169
+ self.report.sql_aggregator = self.sql_parsing_aggregator.report
157
170
 
158
171
  # For profiling
159
172
  self.profiler = DremioProfiler(config, self.report, dremio_api)
@@ -190,84 +203,85 @@ class DremioSource(StatefulIngestionSourceBase):
190
203
 
191
204
  self.source_map = self._build_source_map()
192
205
 
193
- # Process Containers
194
- containers = self.dremio_catalog.get_containers()
195
- for container in containers:
196
- try:
197
- yield from self.process_container(container)
198
- logger.info(
199
- f"Dremio container {container.container_name} emitted successfully"
200
- )
201
- except Exception as exc:
202
- self.report.num_containers_failed += 1 # Increment failed containers
203
- self.report.report_failure(
204
- message="Failed to process Dremio container",
205
- context=f"{'.'.join(container.path)}.{container.container_name}",
206
- exc=exc,
207
- )
206
+ with self.report.new_stage(METADATA_EXTRACTION):
207
+ # Process Containers
208
+ containers = self.dremio_catalog.get_containers()
209
+ for container in containers:
210
+ try:
211
+ yield from self.process_container(container)
212
+ logger.info(
213
+ f"Dremio container {container.container_name} emitted successfully"
214
+ )
215
+ except Exception as exc:
216
+ self.report.num_containers_failed += 1
217
+ self.report.report_failure(
218
+ message="Failed to process Dremio container",
219
+ context=f"{'.'.join(container.path)}.{container.container_name}",
220
+ exc=exc,
221
+ )
208
222
 
209
- # Process Datasets
210
- datasets = self.dremio_catalog.get_datasets()
223
+ # Process Datasets
224
+ datasets = self.dremio_catalog.get_datasets()
211
225
 
212
- for dataset_info in datasets:
213
- try:
214
- yield from self.process_dataset(dataset_info)
215
- logger.info(
216
- f"Dremio dataset {'.'.join(dataset_info.path)}.{dataset_info.resource_name} emitted successfully"
217
- )
218
- except Exception as exc:
219
- self.report.num_datasets_failed += 1 # Increment failed datasets
220
- self.report.report_failure(
221
- message="Failed to process Dremio dataset",
222
- context=f"{'.'.join(dataset_info.path)}.{dataset_info.resource_name}",
223
- exc=exc,
224
- )
226
+ for dataset_info in datasets:
227
+ try:
228
+ yield from self.process_dataset(dataset_info)
229
+ logger.info(
230
+ f"Dremio dataset {'.'.join(dataset_info.path)}.{dataset_info.resource_name} emitted successfully"
231
+ )
232
+ except Exception as exc:
233
+ self.report.num_datasets_failed += 1 # Increment failed datasets
234
+ self.report.report_failure(
235
+ message="Failed to process Dremio dataset",
236
+ context=f"{'.'.join(dataset_info.path)}.{dataset_info.resource_name}",
237
+ exc=exc,
238
+ )
225
239
 
226
- # Optionally Process Query Lineage
227
- if self.config.include_query_lineage:
228
- self.get_query_lineage_workunits()
229
-
230
- # Process Glossary Terms
231
- glossary_terms = self.dremio_catalog.get_glossary_terms()
232
-
233
- for glossary_term in glossary_terms:
234
- try:
235
- yield from self.process_glossary_term(glossary_term)
236
- except Exception as exc:
237
- self.report.report_failure(
238
- message="Failed to process Glossary terms",
239
- context=f"{glossary_term.glossary_term}",
240
- exc=exc,
241
- )
240
+ # Process Glossary Terms
241
+ glossary_terms = self.dremio_catalog.get_glossary_terms()
242
242
 
243
- # Generate workunit for aggregated SQL parsing results
244
- for mcp in self.sql_parsing_aggregator.gen_metadata():
245
- self.report.report_workunit(mcp.as_workunit())
246
- yield mcp.as_workunit()
247
-
248
- # Profiling
249
- if self.config.is_profiling_enabled():
250
- with ThreadPoolExecutor(
251
- max_workers=self.config.profiling.max_workers
252
- ) as executor:
253
- future_to_dataset = {
254
- executor.submit(self.generate_profiles, dataset): dataset
255
- for dataset in datasets
256
- }
257
-
258
- for future in as_completed(future_to_dataset):
259
- dataset_info = future_to_dataset[future]
260
- try:
261
- yield from future.result()
262
- except Exception as exc:
263
- self.report.profiling_skipped_other[
264
- dataset_info.resource_name
265
- ] += 1
266
- self.report.report_failure(
267
- message="Failed to profile dataset",
268
- context=f"{'.'.join(dataset_info.path)}.{dataset_info.resource_name}",
269
- exc=exc,
270
- )
243
+ for glossary_term in glossary_terms:
244
+ try:
245
+ yield from self.process_glossary_term(glossary_term)
246
+ except Exception as exc:
247
+ self.report.report_failure(
248
+ message="Failed to process Glossary terms",
249
+ context=f"{glossary_term.glossary_term}",
250
+ exc=exc,
251
+ )
252
+
253
+ # Optionally Process Query Lineage
254
+ if self.config.include_query_lineage:
255
+ with self.report.new_stage(LINEAGE_EXTRACTION):
256
+ self.get_query_lineage_workunits()
257
+
258
+ # Generate workunit for aggregated SQL parsing results
259
+ for mcp in self.sql_parsing_aggregator.gen_metadata():
260
+ yield mcp.as_workunit()
261
+
262
+ # Profiling
263
+ if self.config.is_profiling_enabled():
264
+ with self.report.new_stage(PROFILING), ThreadPoolExecutor(
265
+ max_workers=self.config.profiling.max_workers
266
+ ) as executor:
267
+ future_to_dataset = {
268
+ executor.submit(self.generate_profiles, dataset): dataset
269
+ for dataset in datasets
270
+ }
271
+
272
+ for future in as_completed(future_to_dataset):
273
+ dataset_info = future_to_dataset[future]
274
+ try:
275
+ yield from future.result()
276
+ except Exception as exc:
277
+ self.report.profiling_skipped_other[
278
+ dataset_info.resource_name
279
+ ] += 1
280
+ self.report.report_failure(
281
+ message="Failed to profile dataset",
282
+ context=f"{'.'.join(dataset_info.path)}.{dataset_info.resource_name}",
283
+ exc=exc,
284
+ )
271
285
 
272
286
  def process_container(
273
287
  self, container_info: DremioContainer
@@ -388,8 +402,7 @@ class DremioSource(StatefulIngestionSourceBase):
388
402
  env=self.config.env,
389
403
  platform_instance=self.config.platform_instance,
390
404
  )
391
- with self.report.new_stage(f"{dataset_info.resource_name}: {PROFILING}"):
392
- yield from self.profiler.get_workunits(dataset_info, dataset_urn)
405
+ yield from self.profiler.get_workunits(dataset_info, dataset_urn)
393
406
 
394
407
  def generate_view_lineage(
395
408
  self, dataset_urn: str, parents: List[str]
@@ -1,3 +1,7 @@
1
+ from datetime import datetime, timedelta
2
+ from typing import Optional
3
+
4
+
1
5
  class DremioSQLQueries:
2
6
  QUERY_DATASETS_CE = """
3
7
  SELECT* FROM
@@ -235,28 +239,83 @@ class DremioSQLQueries:
235
239
  TABLE_NAME ASC
236
240
  """
237
241
 
238
- # Dremio Documentation: https://docs.dremio.com/current/reference/sql/system-tables/jobs_recent/
239
- # queried_datasets incorrectly documented as [varchar]. Observed as varchar.
240
- # LENGTH used as opposed to ARRAY_SIZE
241
- QUERY_ALL_JOBS = """
242
- SELECT
243
- job_id,
244
- user_name,
245
- submitted_ts,
246
- query,
247
- queried_datasets
248
- FROM
249
- SYS.JOBS_RECENT
250
- WHERE
251
- STATUS = 'COMPLETED'
252
- AND LENGTH(queried_datasets)>0
253
- AND user_name != '$dremio$'
254
- AND query_type not like '%INTERNAL%'
255
- """
242
+ @staticmethod
243
+ def _get_default_start_timestamp_millis() -> str:
244
+ """Get default start timestamp (1 day ago) in milliseconds precision format"""
245
+ one_day_ago = datetime.now() - timedelta(days=1)
246
+ return one_day_ago.strftime("%Y-%m-%d %H:%M:%S.%f")[
247
+ :-3
248
+ ] # Truncate to milliseconds
249
+
250
+ @staticmethod
251
+ def _get_default_end_timestamp_millis() -> str:
252
+ """Get default end timestamp (now) in milliseconds precision format"""
253
+ now = datetime.now()
254
+ return now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] # Truncate to milliseconds
255
+
256
+ @staticmethod
257
+ def get_query_all_jobs(
258
+ start_timestamp_millis: Optional[str] = None,
259
+ end_timestamp_millis: Optional[str] = None,
260
+ ) -> str:
261
+ """
262
+ Get query for all jobs with optional time filtering.
263
+
264
+ Args:
265
+ start_timestamp_millis: Start timestamp in format 'YYYY-MM-DD HH:MM:SS.mmm' (defaults to 1 day ago)
266
+ end_timestamp_millis: End timestamp in format 'YYYY-MM-DD HH:MM:SS.mmm' (defaults to now)
267
+
268
+ Returns:
269
+ SQL query string with time filtering applied
270
+ """
271
+ if start_timestamp_millis is None:
272
+ start_timestamp_millis = (
273
+ DremioSQLQueries._get_default_start_timestamp_millis()
274
+ )
275
+ if end_timestamp_millis is None:
276
+ end_timestamp_millis = DremioSQLQueries._get_default_end_timestamp_millis()
277
+
278
+ return f"""
279
+ SELECT
280
+ job_id,
281
+ user_name,
282
+ submitted_ts,
283
+ query,
284
+ queried_datasets
285
+ FROM
286
+ SYS.JOBS_RECENT
287
+ WHERE
288
+ STATUS = 'COMPLETED'
289
+ AND LENGTH(queried_datasets)>0
290
+ AND user_name != '$dremio$'
291
+ AND query_type not like '%INTERNAL%'
292
+ AND submitted_ts >= TIMESTAMP '{start_timestamp_millis}'
293
+ AND submitted_ts <= TIMESTAMP '{end_timestamp_millis}'
294
+ """
295
+
296
+ @staticmethod
297
+ def get_query_all_jobs_cloud(
298
+ start_timestamp_millis: Optional[str] = None,
299
+ end_timestamp_millis: Optional[str] = None,
300
+ ) -> str:
301
+ """
302
+ Get query for all jobs in Dremio Cloud with optional time filtering.
303
+
304
+ Args:
305
+ start_timestamp_millis: Start timestamp in format 'YYYY-MM-DD HH:MM:SS.mmm' (defaults to 7 days ago)
306
+ end_timestamp_millis: End timestamp in format 'YYYY-MM-DD HH:MM:SS.mmm' (defaults to now)
307
+
308
+ Returns:
309
+ SQL query string with time filtering applied
310
+ """
311
+ if start_timestamp_millis is None:
312
+ start_timestamp_millis = (
313
+ DremioSQLQueries._get_default_start_timestamp_millis()
314
+ )
315
+ if end_timestamp_millis is None:
316
+ end_timestamp_millis = DremioSQLQueries._get_default_end_timestamp_millis()
256
317
 
257
- # Dremio Documentation: https://docs.dremio.com/cloud/reference/sql/system-tables/jobs-historical
258
- # queried_datasets correctly documented as [varchar]
259
- QUERY_ALL_JOBS_CLOUD = """
318
+ return f"""
260
319
  SELECT
261
320
  job_id,
262
321
  user_name,
@@ -270,6 +329,8 @@ class DremioSQLQueries:
270
329
  AND ARRAY_SIZE(queried_datasets)>0
271
330
  AND user_name != '$dremio$'
272
331
  AND query_type not like '%INTERNAL%'
332
+ AND submitted_ts >= TIMESTAMP '{start_timestamp_millis}'
333
+ AND submitted_ts <= TIMESTAMP '{end_timestamp_millis}'
273
334
  """
274
335
 
275
336
  QUERY_TYPES = [
@@ -120,7 +120,6 @@ SNOWFLAKE = "snowflake"
120
120
  BIGQUERY = "bigquery"
121
121
  REDSHIFT = "redshift"
122
122
  DATABRICKS = "databricks"
123
- TRINO = "trino"
124
123
 
125
124
  # Type names for Databricks, to match Title Case types in sqlalchemy
126
125
  ProfilerTypeMapping.INT_TYPE_NAMES.append("Integer")
@@ -206,6 +205,17 @@ def get_column_unique_count_dh_patch(self: SqlAlchemyDataset, column: str) -> in
206
205
  )
207
206
  )
208
207
  return convert_to_json_serializable(element_values.fetchone()[0])
208
+ elif (
209
+ self.engine.dialect.name.lower() == GXSqlDialect.AWSATHENA
210
+ or self.engine.dialect.name.lower() == GXSqlDialect.TRINO
211
+ ):
212
+ return convert_to_json_serializable(
213
+ self.engine.execute(
214
+ sa.select(sa.func.approx_distinct(sa.column(column))).select_from(
215
+ self._table
216
+ )
217
+ ).scalar()
218
+ )
209
219
  return convert_to_json_serializable(
210
220
  self.engine.execute(
211
221
  sa.select([sa.func.count(sa.func.distinct(sa.column(column)))]).select_from(
@@ -734,11 +744,41 @@ class _SingleDatasetProfiler(BasicDatasetProfilerBase):
734
744
  def _get_dataset_column_distinct_value_frequencies(
735
745
  self, column_profile: DatasetFieldProfileClass, column: str
736
746
  ) -> None:
737
- if self.config.include_field_distinct_value_frequencies:
747
+ if not self.config.include_field_distinct_value_frequencies:
748
+ return
749
+ try:
750
+ results = self.dataset.engine.execute(
751
+ sa.select(
752
+ [
753
+ sa.column(column),
754
+ sa.func.count(sa.column(column)),
755
+ ]
756
+ )
757
+ .select_from(self.dataset._table)
758
+ .where(sa.column(column).is_not(None))
759
+ .group_by(sa.column(column))
760
+ ).fetchall()
761
+
738
762
  column_profile.distinctValueFrequencies = [
739
- ValueFrequencyClass(value=str(value), frequency=count)
740
- for value, count in self.dataset.get_column_value_counts(column).items()
763
+ ValueFrequencyClass(value=str(value), frequency=int(count))
764
+ for value, count in results
741
765
  ]
766
+ # sort so output is deterministic. don't do it in SQL because not all column
767
+ # types are sortable in SQL (such as JSON data types on Athena/Trino).
768
+ column_profile.distinctValueFrequencies = sorted(
769
+ column_profile.distinctValueFrequencies, key=lambda x: x.value
770
+ )
771
+ except Exception as e:
772
+ logger.debug(
773
+ f"Caught exception while attempting to get distinct value frequencies for column {column}. {e}"
774
+ )
775
+
776
+ self.report.report_warning(
777
+ title="Profiling: Unable to Calculate Distinct Value Frequencies",
778
+ message="Distinct value frequencies for the column will not be accessible",
779
+ context=f"{self.dataset_name}.{column}",
780
+ exc=e,
781
+ )
742
782
 
743
783
  @_run_with_query_combiner
744
784
  def _get_dataset_column_histogram(
@@ -1395,12 +1435,12 @@ class DatahubGEProfiler:
1395
1435
  )
1396
1436
  return None
1397
1437
  finally:
1398
- if batch is not None and self.base_engine.engine.name.upper() in [
1399
- "TRINO",
1400
- "AWSATHENA",
1438
+ if batch is not None and self.base_engine.engine.name.lower() in [
1439
+ GXSqlDialect.TRINO,
1440
+ GXSqlDialect.AWSATHENA,
1401
1441
  ]:
1402
1442
  if (
1403
- self.base_engine.engine.name.upper() == "TRINO"
1443
+ self.base_engine.engine.name.lower() == GXSqlDialect.TRINO
1404
1444
  or temp_view is not None
1405
1445
  ):
1406
1446
  self._drop_temp_table(batch)
@@ -10,6 +10,7 @@ import humanfriendly
10
10
  import pydantic
11
11
  import redshift_connector
12
12
 
13
+ from datahub.configuration.common import AllowDenyPattern
13
14
  from datahub.configuration.pattern_utils import is_schema_allowed
14
15
  from datahub.emitter.mce_builder import (
15
16
  make_data_platform_urn,
@@ -357,7 +358,23 @@ class RedshiftSource(StatefulIngestionSourceBase, TestableSource):
357
358
  ).workunit_processor,
358
359
  ]
359
360
 
361
+ def _warn_deprecated_configs(self):
362
+ if (
363
+ self.config.match_fully_qualified_names is not None
364
+ and not self.config.match_fully_qualified_names
365
+ and self.config.schema_pattern is not None
366
+ and self.config.schema_pattern != AllowDenyPattern.allow_all()
367
+ ):
368
+ self.report.report_warning(
369
+ message="Please update `schema_pattern` to match against fully qualified schema name `<database_name>.<schema_name>` and set config `match_fully_qualified_names : True`."
370
+ "Current default `match_fully_qualified_names: False` is only to maintain backward compatibility. "
371
+ "The config option `match_fully_qualified_names` will be removed in future and the default behavior will be like `match_fully_qualified_names: True`.",
372
+ context="Config option deprecation warning",
373
+ title="Config option deprecation warning",
374
+ )
375
+
360
376
  def get_workunits_internal(self) -> Iterable[Union[MetadataWorkUnit, SqlWorkUnit]]:
377
+ self._warn_deprecated_configs()
361
378
  connection = self._try_get_redshift_connection(self.config)
362
379
 
363
380
  if connection is None:
@@ -89,6 +89,7 @@ class ClickHouseUsageConfig(ClickHouseConfig, BaseUsageConfig, EnvConfigMixin):
89
89
  SourceCapability.DELETION_DETECTION, "Enabled by default via stateful ingestion"
90
90
  )
91
91
  @capability(SourceCapability.DATA_PROFILING, "Optionally enabled via configuration")
92
+ @capability(SourceCapability.USAGE_STATS, "Enabled by default to get usage stats")
92
93
  @dataclasses.dataclass
93
94
  class ClickHouseUsageSource(Source):
94
95
  """
@@ -15,7 +15,9 @@ from sqlalchemy.engine import Engine
15
15
  import datahub.emitter.mce_builder as builder
16
16
  from datahub.configuration.time_window_config import get_time_bucket
17
17
  from datahub.ingestion.api.decorators import (
18
+ SourceCapability,
18
19
  SupportStatus,
20
+ capability,
19
21
  config_class,
20
22
  platform_name,
21
23
  support_status,
@@ -112,6 +114,7 @@ class TrinoUsageReport(SourceReport):
112
114
  @platform_name("Trino")
113
115
  @config_class(TrinoUsageConfig)
114
116
  @support_status(SupportStatus.CERTIFIED)
117
+ @capability(SourceCapability.USAGE_STATS, "Enabled by default to get usage stats")
115
118
  @dataclasses.dataclass
116
119
  class TrinoUsageSource(Source):
117
120
  """
@@ -56,3 +56,7 @@ class TopKDict(DefaultDict[_KT, _VT]):
56
56
 
57
57
  def int_top_k_dict() -> TopKDict[str, int]:
58
58
  return TopKDict(int)
59
+
60
+
61
+ def float_top_k_dict() -> TopKDict[str, float]:
62
+ return TopKDict(float)