|
| 1 | +"""Monitor lifecycle: enable, update, and disable monitoring for a table group. |
| 2 | +
|
| 3 | +Shared by the MCP tools, the monitors dashboard, and the table-group creation |
| 4 | +wizard so all three drive monitoring through one path. Functions mutate the |
| 5 | +monitor ``TestSuite``, its ``JobSchedule``, and the table-group link, and raise |
| 6 | +stdlib exceptions — the MCP and UI layers translate those into their own |
| 7 | +user-facing errors. |
| 8 | +""" |
| 9 | + |
| 10 | +import logging |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +from sqlalchemy import func, select |
| 14 | + |
| 15 | +from testgen.commands.test_generation import run_monitor_generation |
| 16 | +from testgen.common.models import get_current_session |
| 17 | +from testgen.common.models.scheduler import RUN_MONITORS_JOB_KEY, JobSchedule |
| 18 | +from testgen.common.models.table_group import TableGroup |
| 19 | +from testgen.common.models.test_definition import TestDefinition |
| 20 | +from testgen.common.models.test_result import TestResult |
| 21 | +from testgen.common.models.test_run import TestRun |
| 22 | +from testgen.common.models.test_suite import TestSuite |
| 23 | + |
| 24 | +LOG = logging.getLogger("testgen") |
| 25 | + |
| 26 | +# Monitors generated when monitoring is first enabled. Freshness_Trend depends on |
| 27 | +# per-table freshness fingerprinting and is generated separately, so it is not part |
| 28 | +# of the initial bootstrap set. |
| 29 | +INITIAL_MONITOR_TYPES = ["Volume_Trend", "Schema_Drift"] |
| 30 | + |
| 31 | +# Default monitor configuration applied at bootstrap, mirroring the UI's setup form. |
| 32 | +_DEFAULT_SUITE_ATTRS: dict[str, Any] = { |
| 33 | + "monitor_lookback": 14, |
| 34 | + "monitor_regenerate_freshness": True, |
| 35 | + "predict_min_lookback": 30, |
| 36 | + "predict_sensitivity": "medium", |
| 37 | + "predict_exclude_weekends": False, |
| 38 | + "predict_holiday_codes": None, |
| 39 | +} |
| 40 | + |
| 41 | +# The monitor-configuration columns callers may set via ``suite_attrs``. Used as a |
| 42 | +# whitelist so a caller's dict (e.g. a UI form payload) can't write arbitrary suite columns. |
| 43 | +_MONITOR_SETTING_COLUMNS = tuple(_DEFAULT_SUITE_ATTRS) |
| 44 | + |
| 45 | + |
| 46 | +def enable_monitoring( |
| 47 | + table_group: TableGroup, |
| 48 | + cron_expr: str, |
| 49 | + cron_tz: str = "UTC", |
| 50 | + *, |
| 51 | + suite_attrs: dict[str, Any] | None = None, |
| 52 | + active: bool = True, |
| 53 | +) -> tuple[TestSuite, int]: |
| 54 | + """Bootstrap monitoring for a table group. |
| 55 | +
|
| 56 | + Creates the monitor test suite, generates the initial monitors, creates the |
| 57 | + run-monitors schedule, and links the suite to the table group. |
| 58 | +
|
| 59 | + ``suite_attrs`` overrides the default monitor configuration. |
| 60 | +
|
| 61 | + Returns ``(monitor_suite, monitor_count)``. Raises ``ValueError`` if the table |
| 62 | + group already has monitoring enabled. |
| 63 | + """ |
| 64 | + if table_group.monitor_test_suite_id: |
| 65 | + raise ValueError("Monitoring is already enabled for this table group.") |
| 66 | + |
| 67 | + provided = suite_attrs or {} |
| 68 | + attrs = dict(_DEFAULT_SUITE_ATTRS) |
| 69 | + for key in _MONITOR_SETTING_COLUMNS: |
| 70 | + if (value := provided.get(key)) is not None: |
| 71 | + attrs[key] = value |
| 72 | + |
| 73 | + monitor_suite = TestSuite( |
| 74 | + project_code=table_group.project_code, |
| 75 | + test_suite=f"{table_group.table_groups_name} Monitors", |
| 76 | + connection_id=table_group.connection_id, |
| 77 | + table_groups_id=table_group.id, |
| 78 | + export_to_observability=False, |
| 79 | + dq_score_exclude=True, |
| 80 | + is_monitor=True, |
| 81 | + **attrs, |
| 82 | + ) |
| 83 | + monitor_suite.save() |
| 84 | + |
| 85 | + JobSchedule( |
| 86 | + project_code=table_group.project_code, |
| 87 | + key=RUN_MONITORS_JOB_KEY, |
| 88 | + kwargs={"test_suite_id": str(monitor_suite.id)}, |
| 89 | + cron_expr=cron_expr, |
| 90 | + cron_tz=cron_tz, |
| 91 | + active=active, |
| 92 | + ).save() |
| 93 | + |
| 94 | + table_group.monitor_test_suite_id = monitor_suite.id |
| 95 | + table_group.save() |
| 96 | + |
| 97 | + # Commit needed to make the test suite visible to run_monitor_generation's separate DB connection. |
| 98 | + get_current_session().commit() |
| 99 | + run_monitor_generation(monitor_suite.id, INITIAL_MONITOR_TYPES) |
| 100 | + |
| 101 | + count = get_current_session().scalar( |
| 102 | + select(func.count()).select_from(TestDefinition).where(TestDefinition.test_suite_id == monitor_suite.id) |
| 103 | + ) |
| 104 | + return monitor_suite, count or 0 |
| 105 | + |
| 106 | + |
| 107 | +def update_monitoring( |
| 108 | + monitor_suite: TestSuite, |
| 109 | + schedule: JobSchedule, |
| 110 | + *, |
| 111 | + suite_attrs: dict[str, Any] | None = None, |
| 112 | + cron_expr: str | None = None, |
| 113 | + cron_tz: str | None = None, |
| 114 | + active: bool | None = None, |
| 115 | +) -> None: |
| 116 | + """Apply a partial update to monitor settings and/or schedule. |
| 117 | +
|
| 118 | + ``suite_attrs`` maps monitor ``TestSuite`` columns to new values; only the keys in |
| 119 | + ``_MONITOR_SETTING_COLUMNS`` that are present are applied (a present ``None`` clears |
| 120 | + the column). Supplied schedule fields are updated in place. Does not commit — the |
| 121 | + caller's session lifecycle does. |
| 122 | + """ |
| 123 | + provided = suite_attrs or {} |
| 124 | + for key in _MONITOR_SETTING_COLUMNS: |
| 125 | + if key in provided: |
| 126 | + setattr(monitor_suite, key, provided[key]) |
| 127 | + monitor_suite.save() |
| 128 | + |
| 129 | + if cron_expr is not None: |
| 130 | + schedule.cron_expr = cron_expr |
| 131 | + if cron_tz is not None: |
| 132 | + schedule.cron_tz = cron_tz |
| 133 | + if active is not None: |
| 134 | + schedule.active = active |
| 135 | + schedule.save() |
| 136 | + |
| 137 | + |
| 138 | +def disable_monitoring(monitor_suite: TestSuite) -> dict[str, int]: |
| 139 | + """Remove a monitor suite and all its monitors, runs, and history. |
| 140 | +
|
| 141 | + Counts what will be removed before cascading the delete. Returns counts keyed |
| 142 | + ``monitors`` (test definitions), ``events`` (test results), and ``runs``. |
| 143 | + """ |
| 144 | + session = get_current_session() |
| 145 | + suite_id = monitor_suite.id |
| 146 | + counts = { |
| 147 | + "monitors": session.scalar( |
| 148 | + select(func.count()).select_from(TestDefinition).where(TestDefinition.test_suite_id == suite_id) |
| 149 | + ) |
| 150 | + or 0, |
| 151 | + "events": session.scalar( |
| 152 | + select(func.count()).select_from(TestResult).where(TestResult.test_suite_id == suite_id) |
| 153 | + ) |
| 154 | + or 0, |
| 155 | + "runs": session.scalar( |
| 156 | + select(func.count()).select_from(TestRun).where(TestRun.test_suite_id == suite_id) |
| 157 | + ) |
| 158 | + or 0, |
| 159 | + } |
| 160 | + TestSuite.cascade_delete([suite_id]) |
| 161 | + return counts |
0 commit comments