Skip to content

Commit a9f7dec

Browse files
author
ci bot
committed
Merge branch 'telemetry' into 'enterprise'
misc(analytics): add events for nav, execution, and dialogs See merge request dkinternal/testgen/dataops-testgen!209
2 parents 43ddea4 + df630cd commit a9f7dec

15 files changed

Lines changed: 167 additions & 54 deletions

testgen/__main__.py

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,19 @@ def cli(ctx: Context, verbose: bool):
113113
help="The identifier for the table group used during a profile run. Use a table_group_id shown in list-table-groups.",
114114
default=None,
115115
)
116-
def run_profile(configuration: Configuration, table_group_id: str):
116+
@click.option(
117+
"-s",
118+
"--source",
119+
required=False,
120+
type=click.STRING,
121+
default="cli",
122+
)
123+
def run_profile(configuration: Configuration, table_group_id: str, source: str):
117124
click.echo(f"run-profile with table_group_id: {table_group_id}")
118125
spinner = None
119126
if not configuration.verbose:
120127
spinner = MoonSpinner("Processing ... ")
121-
message = run_profiling_queries(table_group_id, spinner=spinner)
128+
message = run_profiling_queries(table_group_id, spinner=spinner, source=source)
122129
click.echo("\n" + message)
123130

124131

@@ -145,10 +152,17 @@ def run_profile(configuration: Configuration, table_group_id: str):
145152
required=False,
146153
default=None,
147154
)
155+
@click.option(
156+
"-s",
157+
"--source",
158+
required=False,
159+
type=click.STRING,
160+
default="cli",
161+
)
148162
@pass_configuration
149-
def run_test_generation(configuration: Configuration, table_group_id: str, test_suite_key: str, generation_set: str):
163+
def run_test_generation(configuration: Configuration, table_group_id: str, test_suite_key: str, generation_set: str, source: str):
150164
LOG.info("CurrentStep: Generate Tests - Main Procedure")
151-
message = run_test_gen_queries(table_group_id, test_suite_key, generation_set)
165+
message = run_test_gen_queries(table_group_id, test_suite_key, generation_set, source)
152166
LOG.info("Current Step: Generate Tests - Main Procedure Complete")
153167
click.echo("\n" + message)
154168

@@ -170,13 +184,20 @@ def run_test_generation(configuration: Configuration, table_group_id: str, test_
170184
required=False,
171185
default=settings.DEFAULT_TEST_SUITE_KEY,
172186
)
187+
@click.option(
188+
"-s",
189+
"--source",
190+
required=False,
191+
type=click.STRING,
192+
default="cli",
193+
)
173194
@pass_configuration
174-
def run_tests(configuration: Configuration, project_key: str, test_suite_key: str):
195+
def run_tests(configuration: Configuration, project_key: str, test_suite_key: str, source: str):
175196
click.echo(f"run-tests for suite: {test_suite_key}")
176197
spinner = None
177198
if not configuration.verbose:
178199
spinner = MoonSpinner("Processing ... ")
179-
message = run_execution_steps(project_key, test_suite_key, spinner=spinner)
200+
message = run_execution_steps(project_key, test_suite_key, spinner=spinner, source=source)
180201
click.echo("\n" + message)
181202

182203

testgen/commands/run_execute_cat_tests.py

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
from datetime import UTC, datetime
23

34
from testgen.commands.queries.execute_cat_tests_query import CCATExecutionSQL
45
from testgen.commands.run_refresh_score_cards_results import run_refresh_score_cards_results
@@ -9,6 +10,7 @@
910
WriteListToDB,
1011
date_service,
1112
)
13+
from testgen.common.mixpanel_service import MixpanelService
1214

1315
LOG = logging.getLogger("testgen")
1416

@@ -60,14 +62,26 @@ def ParseCATResults(clsCATExecute):
6062
RunActionQueryList("DKTG", [strQuery])
6163

6264

63-
def FinalizeTestRun(clsCATExecute: CCATExecutionSQL):
64-
lstQueries = [clsCATExecute.FinalizeTestResultsSQL(),
65-
clsCATExecute.PushTestRunStatusUpdateSQL(),
66-
clsCATExecute.FinalizeTestSuiteUpdateSQL(),
67-
clsCATExecute.CalcPrevalenceTestResultsSQL(),
68-
clsCATExecute.TestScoringRollupRunSQL(),
69-
clsCATExecute.TestScoringRollupTableGroupSQL()]
70-
RunActionQueryList(("DKTG"), lstQueries)
65+
def FinalizeTestRun(clsCATExecute: CCATExecutionSQL, source: str):
66+
_, row_counts = RunActionQueryList(("DKTG"), [
67+
clsCATExecute.FinalizeTestResultsSQL(),
68+
clsCATExecute.PushTestRunStatusUpdateSQL(),
69+
clsCATExecute.FinalizeTestSuiteUpdateSQL(),
70+
])
71+
72+
MixpanelService().send_event(
73+
"run-tests",
74+
source=source,
75+
sql_flavor=clsCATExecute.flavor,
76+
test_count=row_counts[0],
77+
duration=(datetime.now(UTC) - date_service.parse_now(clsCATExecute.run_date)).total_seconds(),
78+
)
79+
80+
RunActionQueryList(("DKTG"), [
81+
clsCATExecute.CalcPrevalenceTestResultsSQL(),
82+
clsCATExecute.TestScoringRollupRunSQL(),
83+
clsCATExecute.TestScoringRollupTableGroupSQL(),
84+
])
7185
run_refresh_score_cards_results(
7286
project_code=clsCATExecute.project_code,
7387
add_history_entry=True,
@@ -76,7 +90,7 @@ def FinalizeTestRun(clsCATExecute: CCATExecutionSQL):
7690

7791

7892
def run_cat_test_queries(
79-
dctParms, strTestRunID, strTestTime, strProjectCode, strTestSuite, error_msg, minutes_offset=0, spinner=None
93+
dctParms, strTestRunID, strTestTime, strProjectCode, strTestSuite, error_msg, minutes_offset=0, spinner=None, source=None
8094
):
8195
booErrors = False
8296

@@ -146,4 +160,4 @@ def run_cat_test_queries(
146160

147161
finally:
148162
LOG.info("Finalizing test run")
149-
FinalizeTestRun(clsCATExecute)
163+
FinalizeTestRun(clsCATExecute, source)

testgen/commands/run_execute_tests.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,8 @@ def run_execution_steps_in_background(project_code, test_suite):
103103
empty_cache()
104104
background_thread = threading.Thread(
105105
target=run_execution_steps,
106-
args=(
107-
project_code,
108-
test_suite
109-
),
106+
args=(project_code, test_suite),
107+
kwargs={"source": "ui"},
110108
)
111109
background_thread.start()
112110
else:
@@ -115,7 +113,13 @@ def run_execution_steps_in_background(project_code, test_suite):
115113
subprocess.Popen(script) # NOQA S603
116114

117115

118-
def run_execution_steps(project_code: str, test_suite: str, minutes_offset: int=0, spinner: Spinner=None) -> str:
116+
def run_execution_steps(
117+
project_code: str,
118+
test_suite: str,
119+
minutes_offset: int=0,
120+
spinner: Spinner=None,
121+
source: str | None=None,
122+
) -> str:
119123
# Initialize required parms for all steps
120124
has_errors = False
121125
error_msg = ""
@@ -165,7 +169,7 @@ def run_execution_steps(project_code: str, test_suite: str, minutes_offset: int=
165169

166170
LOG.info("CurrentStep: Execute Step - CAT Test Execution")
167171
if run_cat_test_queries(
168-
test_exec_params, test_run_id, test_time, project_code, test_suite, error_msg, minutes_offset, spinner
172+
test_exec_params, test_run_id, test_time, project_code, test_suite, error_msg, minutes_offset, spinner, source
169173
):
170174
has_errors = True
171175

testgen/commands/run_generate_tests.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
from testgen.commands.queries.generate_tests_query import CDeriveTestsSQL
44
from testgen.common import AssignConnectParms, RetrieveDBResultsToDictList, RetrieveTestGenParms, RunActionQueryList
5+
from testgen.common.mixpanel_service import MixpanelService
56

67
LOG = logging.getLogger("testgen")
78

89

9-
def run_test_gen_queries(strTableGroupsID, strTestSuite, strGenerationSet=None):
10+
def run_test_gen_queries(strTableGroupsID, strTestSuite, strGenerationSet=None, source=None):
1011
if strTableGroupsID is None:
1112
raise ValueError("Table Group ID was not specified")
1213

@@ -56,7 +57,8 @@ def run_test_gen_queries(strTableGroupsID, strTestSuite, strGenerationSet=None):
5657
LOG.info("CurrentStep: Creating new Test Suite")
5758
strQuery = clsTests.GetInsertTestSuiteSQL(booClean)
5859
if strQuery:
59-
clsTests.test_suite_id, = RunActionQueryList("DKTG", [strQuery])
60+
insert_ids, _ = RunActionQueryList("DKTG", [strQuery])
61+
clsTests.test_suite_id = insert_ids[0]
6062
else:
6163
raise ValueError("Test Suite not found and could not be created")
6264

@@ -104,6 +106,15 @@ def run_test_gen_queries(strTableGroupsID, strTestSuite, strGenerationSet=None):
104106
if lstQueries:
105107
LOG.info("Running Test Generation Template Queries")
106108
RunActionQueryList("DKTG", lstQueries)
107-
return "Test generation completed successfully."
109+
message = "Test generation completed successfully."
108110
else:
109-
return "No TestGen Queries were compiled."
111+
message = "No TestGen Queries were compiled."
112+
113+
MixpanelService().send_event(
114+
"generate-tests",
115+
source=source,
116+
sql_flavor=clsTests.sql_flavor,
117+
generation_set=clsTests.generation_set,
118+
)
119+
120+
return message

testgen/commands/run_profiling_bridge.py

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import subprocess
33
import threading
44
import uuid
5+
from datetime import UTC, datetime
56

67
import pandas as pd
78

@@ -20,6 +21,7 @@
2021
date_service,
2122
)
2223
from testgen.common.database.database_service import empty_cache
24+
from testgen.common.mixpanel_service import MixpanelService
2325

2426
booClean = True
2527
LOG = logging.getLogger("testgen")
@@ -234,15 +236,19 @@ def run_profiling_in_background(table_group_id):
234236
if settings.IS_DEBUG:
235237
LOG.info(msg + ". Running in debug mode (new thread instead of new process).")
236238
empty_cache()
237-
background_thread = threading.Thread(target=run_profiling_queries, args=(table_group_id,))
239+
background_thread = threading.Thread(
240+
target=run_profiling_queries,
241+
args=(table_group_id),
242+
kwargs={"source": "ui"},
243+
)
238244
background_thread.start()
239245
else:
240246
LOG.info(msg)
241247
script = ["testgen", "run-profile", "-tg", table_group_id]
242248
subprocess.Popen(script) # NOQA S603
243249

244250

245-
def run_profiling_queries(strTableGroupsID, spinner=None):
251+
def run_profiling_queries(strTableGroupsID, spinner=None, source=None):
246252
if strTableGroupsID is None:
247253
raise ValueError("Table Group ID was not specified")
248254

@@ -308,28 +314,29 @@ def run_profiling_queries(strTableGroupsID, spinner=None):
308314
if spinner:
309315
spinner.next()
310316

317+
table_count = 0
318+
column_count = 0
311319
try:
312320
# Retrieve Column Metadata
313321
LOG.info("CurrentStep: Getting DDF from project")
314322

315323
strQuery = clsProfiling.GetDDFQuery()
316324
lstResult = RetrieveDBResultsToDictList("PROJECT", strQuery)
317-
318-
if len(lstResult) == 0:
319-
LOG.warning("SQL retrieved 0 records")
325+
column_count = len(lstResult)
320326

321327
if lstResult:
322-
if clsProfiling.profile_use_sampling == "Y":
323-
# Get distinct tables
324-
distinct_tables = set()
325-
for item in lstResult:
326-
schema_name = item["table_schema"]
327-
table_name = item["table_name"]
328-
distinct_tables.add(f"{schema_name}.{table_name}")
328+
# Get distinct tables
329+
distinct_tables = set()
330+
for item in lstResult:
331+
schema_name = item["table_schema"]
332+
table_name = item["table_name"]
333+
distinct_tables.add(f"{schema_name}.{table_name}")
329334

330-
# Convert the set to a list
331-
distinct_tables_list = list(distinct_tables)
335+
# Convert the set to a list
336+
distinct_tables_list = list(distinct_tables)
337+
table_count = len(distinct_tables_list)
332338

339+
if clsProfiling.profile_use_sampling == "Y":
333340
# Sampling tables
334341
lstQueries = []
335342
for parm_sampling_table in distinct_tables_list:
@@ -494,12 +501,24 @@ def run_profiling_queries(strTableGroupsID, spinner=None):
494501
raise
495502
finally:
496503
LOG.info("Updating the profiling run record")
497-
lstProfileRunQuery = [
504+
RunActionQueryList("DKTG", [
498505
clsProfiling.GetProfileRunInfoRecordUpdateQuery(),
506+
])
507+
508+
MixpanelService().send_event(
509+
"run-profiling",
510+
source=source,
511+
sql_flavor=clsProfiling.flavor,
512+
sampling=clsProfiling.profile_use_sampling == "Y",
513+
table_count=table_count,
514+
column_count=column_count,
515+
duration=(datetime.now(UTC) - date_service.parse_now(clsProfiling.run_date)).total_seconds(),
516+
)
517+
518+
RunActionQueryList("DKTG", [
499519
clsProfiling.GetAnomalyScoringRollupRunQuery(),
500520
clsProfiling.GetAnomalyScoringRollupTableGroupQuery(),
501-
]
502-
RunActionQueryList("DKTG", lstProfileRunQuery)
521+
])
503522
run_refresh_score_cards_results(
504523
project_code=dctParms["project_code"],
505524
add_history_entry=True,

testgen/common/database/database_service.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,8 @@ def RunActionQueryList(strCredentialSet, lstQueries, strAdminNDS="N", user_overr
393393
) as con:
394394
i = 0
395395
n = len(lstQueries)
396-
lstInsertedIds = []
396+
insert_ids = []
397+
row_counts = []
397398
if n == 0:
398399
LOG.info("No queries to process")
399400
for q in lstQueries:
@@ -402,20 +403,21 @@ def RunActionQueryList(strCredentialSet, lstQueries, strAdminNDS="N", user_overr
402403
LOG.info(f"(Processing {i} of {n})")
403404
tx = con.begin()
404405
exQ = con.execute(text(q))
406+
row_counts.append(exQ.rowcount)
405407
if exQ.rowcount == -1:
406408
strMsg = "Action query processed no records."
407409
else:
408410
strMsg = str(exQ.rowcount) + " records processed."
409411

410412
try:
411-
lstInsertedIds.append(exQ.fetchone()[0])
413+
insert_ids.append(exQ.fetchone()[0])
412414
except Exception:
413-
lstInsertedIds.append(None)
415+
insert_ids.append(None)
414416

415417
tx.commit()
416418
LOG.info(strMsg)
417419

418-
return lstInsertedIds
420+
return insert_ids, row_counts
419421

420422

421423

testgen/common/mixpanel_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def instance_id(self):
3535

3636
@cached_property
3737
def distinct_id(self):
38-
return self._hash_value(session.username)
38+
return self._hash_value(session.username or self.instance_id)
3939

4040
def _hash_value(self, value: bytes | str, digest_size: int = 8) -> str:
4141
if isinstance(value, str):

testgen/ui/navigation/router.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import streamlit as st
77

88
import testgen.ui.navigation.page
9+
from testgen.common.mixpanel_service import MixpanelService
910
from testgen.ui.session import session
1011
from testgen.utils.singleton import Singleton
1112

@@ -83,6 +84,8 @@ def navigate(self, /, to: str, with_args: dict = {}) -> None: # noqa: B006
8384
len((st.query_params or {}).keys()) != len(final_args.keys())
8485
or any(st.query_params.get(name) != value for name, value in final_args.items())
8586
)
87+
if is_different_page:
88+
MixpanelService().send_event(f"nav-{to}")
8689
if is_different_page or query_params_changed:
8790
route = self._routes[to]
8891
session.page_args_pending_router = {

testgen/ui/views/dialogs/generate_tests_dialog.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def generate_tests_dialog(test_suite: pd.Series) -> None:
7171
status_container.info("Starting test generation ...")
7272

7373
try:
74-
run_test_gen_queries(table_group_id, test_suite_name, selected_set)
74+
run_test_gen_queries(table_group_id, test_suite_name, selected_set, "ui")
7575
except Exception as e:
7676
status_container.error(f"Test generation encountered errors: {e!s}.")
7777

0 commit comments

Comments
 (0)