detectkit 0.71.0__tar.gz → 0.73.0__tar.gz

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.
Files changed (212) hide show
  1. {detectkit-0.71.0/detectkit.egg-info → detectkit-0.73.0}/PKG-INFO +1 -1
  2. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/__init__.py +1 -1
  3. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/cli.md +5 -2
  4. detectkit-0.73.0/detectkit/control/events.py +335 -0
  5. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/queries.py +172 -54
  6. detectkit-0.73.0/detectkit/control/relations.py +111 -0
  7. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/mcp/__init__.py +1 -1
  8. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/mcp/descriptions.py +29 -0
  9. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/mcp/server.py +18 -2
  10. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/mcp/tools.py +2 -0
  11. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/api_v1.py +25 -0
  12. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/mcp_app.py +32 -2
  13. detectkit-0.73.0/detectkit/ui/assets/ui.js +607 -0
  14. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/ui/server.py +16 -0
  15. {detectkit-0.71.0 → detectkit-0.73.0/detectkit.egg-info}/PKG-INFO +1 -1
  16. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit.egg-info/SOURCES.txt +2 -0
  17. detectkit-0.71.0/detectkit/ui/assets/ui.js +0 -569
  18. {detectkit-0.71.0 → detectkit-0.73.0}/LICENSE +0 -0
  19. {detectkit-0.71.0 → detectkit-0.73.0}/MANIFEST.in +0 -0
  20. {detectkit-0.71.0 → detectkit-0.73.0}/README.md +0 -0
  21. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/__init__.py +0 -0
  22. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/__init__.py +0 -0
  23. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/base.py +0 -0
  24. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/branding.py +0 -0
  25. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/discord.py +0 -0
  26. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/email.py +0 -0
  27. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/factory.py +0 -0
  28. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/googlechat.py +0 -0
  29. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/mattermost.py +0 -0
  30. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/ntfy.py +0 -0
  31. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/slack.py +0 -0
  32. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/teams.py +0 -0
  33. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/telegram.py +0 -0
  34. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/channels/webhook.py +0 -0
  35. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/__init__.py +0 -0
  36. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_base.py +0 -0
  37. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_cooldown.py +0 -0
  38. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_decision.py +0 -0
  39. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_dispatch.py +0 -0
  40. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_recovery.py +0 -0
  41. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_replay.py +0 -0
  42. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/_types.py +0 -0
  43. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/alerting/orchestrator/orchestrator.py +0 -0
  44. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/__init__.py +0 -0
  45. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/_base.py +0 -0
  46. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/_types.py +0 -0
  47. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/alert_sim.py +0 -0
  48. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/autotuner.py +0 -0
  49. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/axis_spec.py +0 -0
  50. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/config_emitter.py +0 -0
  51. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/crossval.py +0 -0
  52. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/detector_select.py +0 -0
  53. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/distribution.py +0 -0
  54. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/grid_search.py +0 -0
  55. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/key_select.py +0 -0
  56. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/labels.py +0 -0
  57. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/profile_engine.py +0 -0
  58. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/result.py +0 -0
  59. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/runner.py +0 -0
  60. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/scoring.py +0 -0
  61. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/seasonality_search.py +0 -0
  62. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/settings.py +0 -0
  63. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/autotune/window_select.py +0 -0
  64. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/__init__.py +0 -0
  65. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/_output.py +0 -0
  66. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/CLAUDE.section.md +0 -0
  67. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/alerting.md +0 -0
  68. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/autotune.md +0 -0
  69. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/detectors.md +0 -0
  70. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/metrics.md +0 -0
  71. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/overview.md +0 -0
  72. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/rules/project.md +0 -0
  73. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/skills/dtk-autotune/SKILL.md +0 -0
  74. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/skills/dtk-feedback/SKILL.md +0 -0
  75. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/skills/dtk-new-metric/SKILL.md +0 -0
  76. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/skills/dtk-setup-project/SKILL.md +0 -0
  77. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/assets/claude/skills/dtk-tune/SKILL.md +0 -0
  78. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/__init__.py +0 -0
  79. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/autotune.py +0 -0
  80. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/clean.py +0 -0
  81. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/init.py +0 -0
  82. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/init_claude.py +0 -0
  83. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/lineage.py +0 -0
  84. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/mcp.py +0 -0
  85. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/osi.py +0 -0
  86. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/run.py +0 -0
  87. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/serve.py +0 -0
  88. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/test_alert.py +0 -0
  89. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/tune.py +0 -0
  90. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/ui.py +0 -0
  91. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/commands/unlock.py +0 -0
  92. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/cli/main.py +0 -0
  93. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/__init__.py +0 -0
  94. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/lineage.py +0 -0
  95. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/metric_config.py +0 -0
  96. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/metric_io.py +0 -0
  97. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/profile.py +0 -0
  98. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/project_config.py +0 -0
  99. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/config/validator.py +0 -0
  100. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/__init__.py +0 -0
  101. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/actions.py +0 -0
  102. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/actor.py +0 -0
  103. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/advise.py +0 -0
  104. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/commands.py +0 -0
  105. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/confirm.py +0 -0
  106. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/drafts.py +0 -0
  107. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/errors.py +0 -0
  108. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/health.py +0 -0
  109. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/jobs.py +0 -0
  110. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/metric_files.py +0 -0
  111. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/overview.py +0 -0
  112. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/project.py +0 -0
  113. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/proposals.py +0 -0
  114. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/registry.py +0 -0
  115. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/roles.py +0 -0
  116. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/serialize.py +0 -0
  117. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/control/yaml_patch.py +0 -0
  118. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/core/__init__.py +0 -0
  119. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/core/interval.py +0 -0
  120. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/core/models.py +0 -0
  121. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/__init__.py +0 -0
  122. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/_sql_manager.py +0 -0
  123. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/bigquery_manager.py +0 -0
  124. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/clickhouse_manager.py +0 -0
  125. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/duckdb_manager.py +0 -0
  126. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/__init__.py +0 -0
  127. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_alert_states.py +0 -0
  128. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_autotune_runs.py +0 -0
  129. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_base.py +0 -0
  130. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_datapoints.py +0 -0
  131. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_detections.py +0 -0
  132. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_maintenance.py +0 -0
  133. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_metrics.py +0 -0
  134. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_platform.py +0 -0
  135. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_schema.py +0 -0
  136. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/_tasks.py +0 -0
  137. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/internal_tables/manager.py +0 -0
  138. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/manager.py +0 -0
  139. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/mysql_manager.py +0 -0
  140. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/postgres_manager.py +0 -0
  141. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/snowflake_manager.py +0 -0
  142. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/source_manager.py +0 -0
  143. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/database/tables.py +0 -0
  144. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/__init__.py +0 -0
  145. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/base.py +0 -0
  146. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/factory.py +0 -0
  147. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/seasonality.py +0 -0
  148. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/__init__.py +0 -0
  149. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/_baseline.py +0 -0
  150. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/_windowed.py +0 -0
  151. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/autoreg.py +0 -0
  152. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/iqr.py +0 -0
  153. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/mad.py +0 -0
  154. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/manual_bounds.py +0 -0
  155. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/detectors/statistical/zscore.py +0 -0
  156. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/loaders/__init__.py +0 -0
  157. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/loaders/errors.py +0 -0
  158. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/loaders/metric_loader.py +0 -0
  159. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/loaders/query_template.py +0 -0
  160. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/mcp/context.py +0 -0
  161. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/mcp/errors.py +0 -0
  162. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/__init__.py +0 -0
  163. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/error_dispatch.py +0 -0
  164. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/__init__.py +0 -0
  165. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/_alert_step.py +0 -0
  166. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/_base.py +0 -0
  167. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/_detect_step.py +0 -0
  168. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/_load_step.py +0 -0
  169. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/_types.py +0 -0
  170. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/orchestration/task_manager/manager.py +0 -0
  171. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/reporting/__init__.py +0 -0
  172. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/reporting/assets/report.js +0 -0
  173. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/reporting/builder.py +0 -0
  174. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/reporting/html_report.py +0 -0
  175. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/__init__.py +0 -0
  176. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/errors.py +0 -0
  177. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/exporter.py +0 -0
  178. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/importer.py +0 -0
  179. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/osi_model.py +0 -0
  180. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/query_gen.py +0 -0
  181. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/semantic/sources.py +0 -0
  182. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/__init__.py +0 -0
  183. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/app.py +0 -0
  184. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/errors.py +0 -0
  185. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/forge.py +0 -0
  186. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/platform.py +0 -0
  187. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/projects.py +0 -0
  188. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/server.py +0 -0
  189. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/settings.py +0 -0
  190. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/web.py +0 -0
  191. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/serve/write_tools.py +0 -0
  192. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/tuning/__init__.py +0 -0
  193. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/tuning/assets/tune.js +0 -0
  194. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/tuning/config_writer.py +0 -0
  195. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/tuning/html.py +0 -0
  196. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/tuning/payload.py +0 -0
  197. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/tuning/server.py +0 -0
  198. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/ui/__init__.py +0 -0
  199. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/ui/html.py +0 -0
  200. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/utils/__init__.py +0 -0
  201. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/utils/datetime_utils.py +0 -0
  202. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/utils/env_interpolation.py +0 -0
  203. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/utils/json_utils.py +0 -0
  204. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit/utils/stats.py +0 -0
  205. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit.egg-info/dependency_links.txt +0 -0
  206. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit.egg-info/entry_points.txt +0 -0
  207. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit.egg-info/requires.txt +0 -0
  208. {detectkit-0.71.0 → detectkit-0.73.0}/detectkit.egg-info/top_level.txt +0 -0
  209. {detectkit-0.71.0 → detectkit-0.73.0}/pyproject.toml +0 -0
  210. {detectkit-0.71.0 → detectkit-0.73.0}/requirements.txt +0 -0
  211. {detectkit-0.71.0 → detectkit-0.73.0}/setup.cfg +0 -0
  212. {detectkit-0.71.0 → detectkit-0.73.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: detectkit
3
- Version: 0.71.0
3
+ Version: 0.73.0
4
4
  Summary: Metric monitoring with automatic anomaly detection
5
5
  Author: detectkit team
6
6
  License: MIT
@@ -4,7 +4,7 @@ detectk - Anomaly Detection for Time-Series Metrics
4
4
  A Python library for data analysts and engineers to monitor metrics with automatic anomaly detection.
5
5
  """
6
6
 
7
- __version__ = "0.71.0"
7
+ __version__ = "0.73.0"
8
8
 
9
9
  from detectkit.core.interval import Interval
10
10
  from detectkit.core.models import ColumnDefinition, TableModel
@@ -12,7 +12,7 @@ Run all commands from a project directory (the one containing
12
12
  | `dtk run --select <sel>` | Run the load → detect → alert pipeline |
13
13
  | `dtk autotune --select <sel>` | Auto-configure a metric's detector (see `autotune.md`) |
14
14
  | `dtk tune --select <sel>` | Interactively tune a detector on real data, write it back in place |
15
- | `dtk ui` | Project-wide live overview + browser pipeline control panel + create/edit/delete metric YAMLs + per-metric Clean stale |
15
+ | `dtk ui` | Project-wide live overview + an **Events** view (what broke together, grouped by `lineage` family and shared source table) + browser pipeline control panel + create/edit/delete metric YAMLs + per-metric Clean stale |
16
16
  | `dtk test-alert <metric>` | Send a mock alert to the metric's channels |
17
17
  | `dtk unlock --select <sel>` | Clear a stuck pipeline lock |
18
18
  | `dtk clean --select <sel>` | Prune internal data that no longer matches the config |
@@ -404,12 +404,15 @@ server, exposing a project to *another* AI assistant (an MCP client — Claude
404
404
  Code, Claude Desktop, an IDE extension) rather than being one itself. It is a
405
405
  separate, additive command (needs `pip install 'detectkit[mcp]'`) that
406
406
  contains **zero write paths**: no config edits, no label writes, no pipeline
407
- runs, no schema creation. Eleven tools: `list_metrics`, `get_metric`,
407
+ runs, no schema creation. Thirteen tools: `list_metrics`, `get_metric`,
408
408
  `get_metric_status`, `get_project_status`, `query_datapoints`,
409
409
  `query_detections`, `replay_alerts` (reconstructs the alert timeline the same
410
410
  way `dtk run --report` does — never reads `_dtk_alert_states`, never
411
411
  dispatches), `get_autotune_history`, `get_incidents`, `get_related_metrics`
412
412
  (a metric's family by declared `lineage` + metrics reading the same table),
413
+ `list_anomaly_events` / `get_anomaly_event` (what broke, grouped into events
414
+ across metrics by `lineage` and shared source tables — metrics that only
415
+ overlapped in time are listed as `also_anomalous`, never merged),
413
416
  `get_server_info`.
414
417
  Channel connection details/secrets in `profiles.yml` are never exposed —
415
418
  `get_metric` lists alerting channels by name only.
@@ -0,0 +1,335 @@
1
+ """Anomaly events: one product event across metrics, computed on read (RFC 0002 phase 2).
2
+
3
+ An **episode** is a maximal anomaly streak of one metric (its alert quorum met, one
4
+ missing grid point bridged) or a no-data streak. An **event** groups episodes that
5
+ overlap in time *and* are related by structure:
6
+
7
+ - ``lineage``: one family (a total and its slices, siblings) or a ratio and its parts;
8
+ - ``same_source``: their SQL reads a common table that isn't a shared dimension.
9
+
10
+ Overlap alone never merges (the correlation audit: "merge whatever overlaps" fell to
11
+ precision 0.18 as the pool grew). Episodes that merely overlap an event are listed on
12
+ it as ``also_anomalous``, visible but not merged. Learned co-anomaly links (phase 3)
13
+ will add a third kind of edge.
14
+
15
+ Within a family the **headline** is the highest anomalous node (the total when it is
16
+ in the event), and each slice carries its share of the headline's deviation — which
17
+ slice the event lives in. Everything is computed from stored detections, like the
18
+ alert replay: no state, no writes.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import hashlib
24
+ from collections.abc import Iterable
25
+ from dataclasses import dataclass, field
26
+ from datetime import datetime, timedelta
27
+ from typing import Any
28
+
29
+ import numpy as np
30
+
31
+ TOLERANCE_POINTS = 2 # grid points of slack when two episodes "overlap"
32
+
33
+
34
+ @dataclass
35
+ class Episode:
36
+ metric: str
37
+ kind: str # "anomaly" | "no_data"
38
+ start: datetime
39
+ end: datetime # the last point, inclusive
40
+ interval_seconds: int
41
+ points: int
42
+ direction: str | None = None # "up" | "down" | "mixed"
43
+ deviation: float | None = None # median (value - center) / |center| over the streak
44
+ abs_deviation: float | None = None # sum (value - center): the size, in value units
45
+ alerted: bool = False
46
+ open: bool = False # still running at the window's end
47
+
48
+ def overlaps(self, other: Episode) -> bool:
49
+ slack = timedelta(
50
+ seconds=TOLERANCE_POINTS * max(self.interval_seconds, other.interval_seconds)
51
+ )
52
+ return self.start - slack <= other.end and other.start - slack <= self.end
53
+
54
+
55
+ # ── episodes from one metric's rows ─────────────────────────────────────────
56
+
57
+
58
+ def _quorum_ok(records: list[Any], min_detectors: int, direction: str) -> tuple[bool, str | None]:
59
+ """Does this timestamp's set of detection records meet the alert quorum?"""
60
+ hits = [r for r in records if r.is_anomaly]
61
+ if direction in ("up", "down"):
62
+ hits = [r for r in hits if r.direction == direction]
63
+ if direction == "same":
64
+ ups = [r for r in hits if r.direction == "up"]
65
+ downs = [r for r in hits if r.direction == "down"]
66
+ best = ups if len(ups) >= len(downs) else downs
67
+ return len(best) >= min_detectors, (best[0].direction if best else None)
68
+ if len(hits) < min_detectors:
69
+ return False, None
70
+ dirs = {r.direction for r in hits if r.direction in ("up", "down")}
71
+ return True, (dirs.pop() if len(dirs) == 1 else "mixed" if dirs else None)
72
+
73
+
74
+ def _runs(times: list[np.datetime64], step: np.timedelta64) -> list[tuple[int, int]]:
75
+ """Index runs over sorted *times*, bridging one missing grid point."""
76
+ runs: list[tuple[int, int]] = []
77
+ if not times:
78
+ return runs
79
+ start = 0
80
+ for i in range(1, len(times)):
81
+ if times[i] - times[i - 1] > 2 * step:
82
+ runs.append((start, i - 1))
83
+ start = i
84
+ runs.append((start, len(times) - 1))
85
+ return runs
86
+
87
+
88
+ def _to_dt(t: np.datetime64) -> datetime:
89
+ return t.astype("datetime64[ms]").astype(datetime)
90
+
91
+
92
+ def metric_episodes(
93
+ *,
94
+ metric: str,
95
+ interval_seconds: int,
96
+ records: list[Any],
97
+ timestamps: np.ndarray,
98
+ values: np.ndarray,
99
+ min_detectors: int,
100
+ direction: str,
101
+ alert_times: Iterable[datetime],
102
+ window_end: datetime | None,
103
+ ) -> list[Episode]:
104
+ """One metric's anomaly and no-data episodes over the loaded window."""
105
+ step = np.timedelta64(interval_seconds, "s")
106
+ by_ts: dict[np.datetime64, list[Any]] = {}
107
+ for r in records:
108
+ by_ts.setdefault(r.timestamp, []).append(r)
109
+ hits: list[np.datetime64] = []
110
+ info: dict[np.datetime64, tuple[str | None, float | None, float | None]] = {}
111
+ for ts in sorted(by_ts):
112
+ ok, d = _quorum_ok(by_ts[ts], min_detectors, direction)
113
+ if not ok:
114
+ continue
115
+ hits.append(ts)
116
+ rel = absdev = None
117
+ for r in by_ts[ts]:
118
+ if r.is_anomaly and r.confidence_lower is not None and r.confidence_upper is not None:
119
+ center = (r.confidence_lower + r.confidence_upper) / 2
120
+ if np.isfinite(r.value):
121
+ absdev = r.value - center
122
+ rel = absdev / abs(center) if center else None
123
+ break
124
+ info[ts] = (d, rel, absdev)
125
+
126
+ alerts = sorted(np.datetime64(t, "ms") for t in alert_times)
127
+ end_mark = np.datetime64(window_end, "ms") if window_end is not None else None
128
+ out: list[Episode] = []
129
+ for a, b in _runs(hits, step):
130
+ span = hits[a : b + 1]
131
+ dirs = {info[t][0] for t in span if info[t][0] in ("up", "down")}
132
+ rels = [info[t][1] for t in span if info[t][1] is not None]
133
+ abss = [info[t][2] for t in span if info[t][2] is not None]
134
+ out.append(
135
+ Episode(
136
+ metric=metric,
137
+ kind="anomaly",
138
+ start=_to_dt(span[0]),
139
+ end=_to_dt(span[-1]),
140
+ interval_seconds=interval_seconds,
141
+ points=len(span),
142
+ direction=dirs.pop() if len(dirs) == 1 else ("mixed" if dirs else None),
143
+ deviation=float(np.median(rels)) if rels else None,
144
+ abs_deviation=float(np.sum(abss)) if abss else None,
145
+ alerted=bool(
146
+ any(span[0] <= t <= span[-1] + TOLERANCE_POINTS * step for t in alerts)
147
+ ),
148
+ open=bool(end_mark is not None and span[-1] >= end_mark - step),
149
+ )
150
+ )
151
+
152
+ missing = [
153
+ np.datetime64(t, "ms")
154
+ for t, v in zip(timestamps, values, strict=False)
155
+ if v is None or (isinstance(v, float) and not np.isfinite(v))
156
+ ]
157
+ for a, b in _runs(missing, step):
158
+ span = missing[a : b + 1]
159
+ out.append(
160
+ Episode(
161
+ metric=metric,
162
+ kind="no_data",
163
+ start=_to_dt(span[0]),
164
+ end=_to_dt(span[-1]),
165
+ interval_seconds=interval_seconds,
166
+ points=len(span),
167
+ alerted=bool(
168
+ any(span[0] <= t <= span[-1] + TOLERANCE_POINTS * step for t in alerts)
169
+ ),
170
+ open=bool(end_mark is not None and span[-1] >= end_mark - step),
171
+ )
172
+ )
173
+ return sorted(out, key=lambda e: (e.start, e.metric))
174
+
175
+
176
+ # ── events from everyone's episodes ─────────────────────────────────────────
177
+
178
+
179
+ @dataclass
180
+ class Event:
181
+ id: str
182
+ start: datetime
183
+ end: datetime
184
+ open: bool
185
+ headline: str
186
+ members: list[dict[str, Any]] = field(default_factory=list)
187
+ edges: list[dict[str, Any]] = field(default_factory=list)
188
+ also_anomalous: list[dict[str, Any]] = field(default_factory=list)
189
+
190
+
191
+ class _Union:
192
+ def __init__(self, n: int) -> None:
193
+ self.parent = list(range(n))
194
+
195
+ def find(self, i: int) -> int:
196
+ while self.parent[i] != i:
197
+ self.parent[i] = self.parent[self.parent[i]]
198
+ i = self.parent[i]
199
+ return i
200
+
201
+ def join(self, i: int, j: int) -> None:
202
+ self.parent[self.find(i)] = self.find(j)
203
+
204
+
205
+ def _event_id(episodes: list[Episode]) -> str:
206
+ start = min(e.start for e in episodes).isoformat()
207
+ names = ",".join(sorted({e.metric for e in episodes}))
208
+ return hashlib.sha256(f"{start}|{names}".encode()).hexdigest()[:12]
209
+
210
+
211
+ def build_events(
212
+ episodes: list[Episode],
213
+ pairs: dict[frozenset[str], dict[str, Any]],
214
+ roles: dict[str, dict[str, str]],
215
+ totals: set[str],
216
+ ) -> list[Event]:
217
+ """Group *episodes* into events along structural edges; newest first.
218
+
219
+ *pairs* is :func:`~detectkit.control.relations.relation_pairs`; *roles* maps a
220
+ metric to ``{other: relation}`` from its own point of view (``total``, ``slice``,
221
+ ``sibling``, …); *totals* are the metrics that are a family's total.
222
+ """
223
+ n = len(episodes)
224
+ uf = _Union(n)
225
+ edges: list[tuple[int, int, dict[str, Any]]] = []
226
+ for i in range(n):
227
+ for j in range(i + 1, n):
228
+ a, b = episodes[i], episodes[j]
229
+ if a.metric == b.metric or not a.overlaps(b):
230
+ continue
231
+ rel = pairs.get(frozenset({a.metric, b.metric}))
232
+ if rel is None:
233
+ continue
234
+ uf.join(i, j)
235
+ edges.append((i, j, rel))
236
+ groups: dict[int, list[int]] = {}
237
+ for i in range(n):
238
+ groups.setdefault(uf.find(i), []).append(i)
239
+
240
+ events: list[Event] = []
241
+ comp_of = {i: root for root, idx in groups.items() for i in idx}
242
+ for root, idx in groups.items():
243
+ eps = [episodes[i] for i in idx]
244
+ metrics = {e.metric for e in eps}
245
+
246
+ def size(e: Episode) -> float:
247
+ return abs(e.deviation) if e.deviation is not None else -1.0
248
+
249
+ anomalies = [e for e in eps if e.kind == "anomaly"]
250
+ tops = [e for e in anomalies if e.metric in totals]
251
+ lead = tops or anomalies or eps
252
+ headline = (
253
+ max(lead, key=size).metric
254
+ if tops or anomalies
255
+ else min(eps, key=lambda e: e.start).metric
256
+ )
257
+ head_abs = sum(
258
+ e.abs_deviation or 0.0 for e in eps if e.metric == headline and e.kind == "anomaly"
259
+ )
260
+ members = []
261
+ for e in sorted(eps, key=lambda e: (e.metric != headline, e.start, e.metric)):
262
+ member: dict[str, Any] = {
263
+ "metric": e.metric,
264
+ "role": (
265
+ "headline"
266
+ if e.metric == headline
267
+ else roles.get(headline, {}).get(e.metric)
268
+ or pairs.get(frozenset({headline, e.metric}), {}).get("reason", "related")
269
+ ),
270
+ "kind": e.kind,
271
+ "start": e.start,
272
+ "end": e.end,
273
+ "points": e.points,
274
+ "direction": e.direction,
275
+ "deviation": e.deviation,
276
+ "alerted": e.alerted,
277
+ "open": e.open,
278
+ }
279
+ if (
280
+ e.metric != headline
281
+ and member["role"] == "slice"
282
+ and head_abs
283
+ and e.abs_deviation is not None
284
+ ):
285
+ member["share_of_headline_deviation"] = e.abs_deviation / head_abs
286
+ members.append(member)
287
+ edge_list = [
288
+ {"a": episodes[i].metric, "b": episodes[j].metric, **rel}
289
+ for i, j, rel in edges
290
+ if comp_of[i] == root
291
+ ]
292
+ seen_edges: set[tuple[str, str]] = set()
293
+ unique_edges = []
294
+ for edge in edge_list:
295
+ key = tuple(sorted((edge["a"], edge["b"])))
296
+ if key not in seen_edges:
297
+ seen_edges.add(key) # type: ignore[arg-type]
298
+ unique_edges.append(edge)
299
+ start = min(e.start for e in eps)
300
+ end = max(e.end for e in eps)
301
+ neighbours = []
302
+ for k, other in enumerate(episodes):
303
+ if comp_of[k] == root or other.metric in metrics:
304
+ continue
305
+ if any(other.overlaps(e) for e in eps):
306
+ neighbours.append(
307
+ {
308
+ "metric": other.metric,
309
+ "kind": other.kind,
310
+ "start": other.start,
311
+ "end": other.end,
312
+ }
313
+ )
314
+ events.append(
315
+ Event(
316
+ id=_event_id(eps),
317
+ start=start,
318
+ end=end,
319
+ open=any(e.open for e in eps),
320
+ headline=headline,
321
+ members=members,
322
+ edges=unique_edges,
323
+ also_anomalous=neighbours,
324
+ )
325
+ )
326
+ # fill neighbour event ids once every event exists
327
+ owner: dict[tuple[str, datetime], str] = {}
328
+ for ev in events:
329
+ for m in ev.members:
330
+ owner[(m["metric"], m["start"])] = ev.id
331
+ for ev in events:
332
+ for nb in ev.also_anomalous:
333
+ nb["event"] = owner.get((nb["metric"], nb["start"]))
334
+ events.sort(key=lambda ev: (ev.start, ev.id), reverse=True)
335
+ return events
@@ -502,77 +502,195 @@ def get_incidents(project: ProjectHandle, metric: str) -> dict[str, Any]:
502
502
  # ---------------------------------------------------------------------------
503
503
  # get_related_metrics (RFC 0002 phase 1: structural relations only)
504
504
  # ---------------------------------------------------------------------------
505
- # A table read by more than this share of the in-scope metrics (and by at least
506
- # _SHARED_TABLE_MIN of them) is a shared dimension — a calendar grid, a users
507
- # table — not a common cause, so it doesn't relate metrics.
508
- _SHARED_TABLE_SHARE = 0.5
509
- _SHARED_TABLE_MIN = 3
510
-
511
-
512
- def _source_dialect(project: ProjectHandle, config: Any) -> str | None:
513
- from detectkit.semantic.sources import dialect_for # noqa: PLC0415
514
-
515
- profiles = project.profiles_config
516
- if profiles is None:
517
- return None
518
- name = (
519
- resolve_source_profile(config.source_profile, project.project_config.source_profile)
520
- or project.profile_name
521
- or profiles.default_profile
522
- )
523
- try:
524
- return dialect_for(profiles.get_profile(name).type)
525
- except Exception: # noqa: BLE001 - an unknown profile just means "generic SQL"
526
- return None
527
-
528
-
529
- def metric_sources(project: ProjectHandle, config: Any) -> tuple[list[str] | None, str | None]:
530
- """The tables *config*'s SQL reads, or ``(None, why not)``."""
531
- from detectkit.semantic.sources import SourcesUnavailable, source_tables # noqa: PLC0415
532
-
533
- try:
534
- sql = config.get_query_text(project.project_root)
535
- except Exception as exc: # noqa: BLE001 - surfaced as a field
536
- return None, f"the query can't be read: {exc}"
537
- try:
538
- return source_tables(sql, _source_dialect(project, config)), None
539
- except SourcesUnavailable as exc:
540
- return None, str(exc)
541
-
542
-
543
505
  def get_related_metrics(project: ProjectHandle, name: str) -> dict[str, Any]:
544
506
  """How the other in-scope metrics relate to *name* by structure (declared + SQL)."""
545
507
  from detectkit.config.lineage import structural_relations # noqa: PLC0415
508
+ from detectkit.control.relations import source_index # noqa: PLC0415
546
509
 
547
510
  _path, me = project.require_metric(name)
548
511
  configs = [config for _p, config in project.metrics]
549
- sources = {config.name: metric_sources(project, config) for config in configs}
550
- readers: dict[str, set[str]] = {}
551
- for metric, (tables, _err) in sources.items():
552
- for table in tables or []:
553
- readers.setdefault(table, set()).add(metric)
554
- threshold = max(_SHARED_TABLE_MIN, _SHARED_TABLE_SHARE * len(configs))
555
- shared = sorted(t for t, who in readers.items() if len(who) > threshold)
556
- my_tables, my_error = sources[name]
557
- same_source = []
558
- for other in sorted(sources):
559
- if other == name:
560
- continue
561
- common = sorted(set(my_tables or []) & set(sources[other][0] or []) - set(shared))
562
- if common:
563
- same_source.append({"metric": other, "tables": common})
512
+ index = source_index(project, configs)
513
+ my_tables, my_error = index.sources[name]
514
+ same_source = [
515
+ {"metric": other, "tables": tables} for other, tables in index.same_source(name).items()
516
+ ]
564
517
  return {
565
518
  "metric": name,
566
519
  "lineage": me.lineage.to_public() if me.lineage else None,
567
520
  "structural": structural_relations(name, configs),
568
521
  "sources": my_tables,
569
522
  "sources_error": my_error,
570
- "shared_tables": [t for t in shared if t in set(my_tables or [])],
523
+ "shared_tables": [t for t in index.shared if t in set(my_tables or [])],
571
524
  "same_source": same_source,
572
525
  "scope_metrics": len(configs),
573
526
  }
574
527
 
575
528
 
529
+ # ---------------------------------------------------------------------------
530
+ # list_anomaly_events / get_anomaly_event (RFC 0002 phase 2: events on read)
531
+ # ---------------------------------------------------------------------------
532
+ _EVENTS_DEFAULT_LIMIT = 50
533
+ _EVENTS_HARD_CAP = 500
534
+
535
+
536
+ def _event_episodes(
537
+ project: ProjectHandle, window: str, selector: str
538
+ ) -> tuple[list[Any], list[Any], int]:
539
+ """Every in-scope (and selected) enabled metric's episodes over *window*."""
540
+ from detectkit.control.events import metric_episodes # noqa: PLC0415
541
+ from detectkit.control.overview import ( # noqa: PLC0415
542
+ _configured_detector_ids,
543
+ _load_window_detections,
544
+ _resolve_metric_window,
545
+ )
546
+
547
+ internal = project.require_internal()
548
+ _require_window(window)
549
+ try:
550
+ matched = select_metrics(selector, project.project_root)
551
+ except ValueError as exc:
552
+ raise InvalidRequestError(f"Error in selector {selector!r}: {exc}") from exc
553
+ chosen = {c.name for _p, c in matched if c.name in project.metric_names}
554
+ configs = [config for _p, config in project.metrics]
555
+ now = now_utc_naive()
556
+ episodes: list[Any] = []
557
+ scanned = 0
558
+ for config in configs:
559
+ if config.name not in chosen or not config.enabled:
560
+ continue
561
+ interval = config.get_interval().seconds
562
+ with project.lock:
563
+ start, end = _resolve_metric_window(internal, config.name, interval, window, now)
564
+ if start is None or end is None:
565
+ continue
566
+ to_exclusive = end + timedelta(seconds=interval)
567
+ dp = internal.load_datapoints(config.name, start, to_exclusive)
568
+ ids = _configured_detector_ids(config)
569
+ rows = _load_window_detections(internal, config.name, ids, start, to_exclusive)
570
+ scanned += 1
571
+ records = [record_from_row(r) for r in rows]
572
+ value_at = {
573
+ np.datetime64(t, "ms"): num_or_none(v)
574
+ for t, v in zip(dp["timestamp"], dp["value"], strict=False)
575
+ }
576
+ replayed = replay_alert_events(
577
+ config,
578
+ internal,
579
+ records,
580
+ value_at,
581
+ start,
582
+ end,
583
+ project.project_config.name,
584
+ loading_delay_seconds=resolve_loading_delay_seconds(
585
+ config.loading_delay, project.project_config.loading_delay
586
+ ),
587
+ )
588
+ alert_times = [ev.timestamp for _cid, ev in replayed if ev.kind in ("anomaly", "no_data")]
589
+ block = next((a for a in (config.alerting or []) if a.enabled), None)
590
+ episodes.extend(
591
+ metric_episodes(
592
+ metric=config.name,
593
+ interval_seconds=interval,
594
+ records=records,
595
+ timestamps=dp["timestamp"],
596
+ values=np.array([num_or_none(v) for v in dp["value"]], dtype=object),
597
+ min_detectors=block.min_detectors if block else 1,
598
+ direction=block.direction if block else "any",
599
+ alert_times=alert_times,
600
+ window_end=end,
601
+ )
602
+ )
603
+ return episodes, configs, scanned
604
+
605
+
606
+ def _anomaly_events(project: ProjectHandle, window: str, selector: str) -> tuple[list[Any], int]:
607
+ from detectkit.config.lineage import structural_relations # noqa: PLC0415
608
+ from detectkit.control.events import build_events # noqa: PLC0415
609
+ from detectkit.control.relations import relation_pairs # noqa: PLC0415
610
+
611
+ episodes, configs, scanned = _event_episodes(project, window, selector)
612
+ pairs = relation_pairs(project, configs)
613
+ roles = {
614
+ c.name: {r["metric"]: r["relation"] for r in structural_relations(c.name, configs)}
615
+ for c in configs
616
+ }
617
+ totals = {
618
+ c.name
619
+ for c in configs
620
+ if c.lineage is not None and c.lineage.measure is not None and not c.lineage.slice
621
+ }
622
+ return build_events(episodes, pairs, roles, totals), scanned
623
+
624
+
625
+ def _event_public(event: Any, *, full: bool) -> dict[str, Any]:
626
+ def member(m: dict[str, Any]) -> dict[str, Any]:
627
+ out = {k: v for k, v in m.items() if k not in ("start", "end")}
628
+ out["start"], out["end"] = to_iso(m["start"]), to_iso(m["end"])
629
+ for key in ("deviation", "share_of_headline_deviation"):
630
+ if key in out:
631
+ out[key] = num_or_none(out[key])
632
+ return out
633
+
634
+ base: dict[str, Any] = {
635
+ "id": event.id,
636
+ "start": to_iso(event.start),
637
+ "end": to_iso(event.end),
638
+ "open": event.open,
639
+ "headline": event.headline,
640
+ "metric_count": len({m["metric"] for m in event.members}),
641
+ "alerted": any(m["alerted"] for m in event.members),
642
+ }
643
+ if not full:
644
+ base["members"] = [
645
+ {k: m[k] for k in ("metric", "role", "kind", "alerted")} for m in event.members
646
+ ]
647
+ base["also_anomalous"] = sorted({n["metric"] for n in event.also_anomalous})
648
+ return base
649
+ base["members"] = [member(m) for m in event.members]
650
+ base["edges"] = event.edges
651
+ base["also_anomalous"] = [
652
+ {**n, "start": to_iso(n["start"]), "end": to_iso(n["end"])} for n in event.also_anomalous
653
+ ]
654
+ return base
655
+
656
+
657
+ def list_anomaly_events(
658
+ project: ProjectHandle,
659
+ window: str = "7d",
660
+ selector: str = "*",
661
+ limit: int = _EVENTS_DEFAULT_LIMIT,
662
+ multi_metric: bool = False,
663
+ include_unalerted: bool = False,
664
+ ) -> dict[str, Any]:
665
+ events, scanned = _anomaly_events(project, window, selector)
666
+ if not include_unalerted:
667
+ # An event no member alerted on is a blip the alert rule already judged
668
+ # too small; its episodes still joined the grouping above.
669
+ events = [e for e in events if any(m["alerted"] for m in e.members)]
670
+ if multi_metric:
671
+ events = [e for e in events if len({m["metric"] for m in e.members}) > 1]
672
+ effective = clamp_limit(limit, default=_EVENTS_DEFAULT_LIMIT, hard_cap=_EVENTS_HARD_CAP)
673
+ return {
674
+ "window": window,
675
+ "selector": selector,
676
+ "metrics_scanned": scanned,
677
+ "events_total": len(events),
678
+ "returned": min(len(events), effective),
679
+ "events": [_event_public(e, full=False) for e in events[:effective]],
680
+ }
681
+
682
+
683
+ def get_anomaly_event(project: ProjectHandle, event_id: str, window: str = "7d") -> dict[str, Any]:
684
+ events, _scanned = _anomaly_events(project, window, "*")
685
+ for event in events:
686
+ if event.id == event_id:
687
+ return {"window": window, **_event_public(event, full=True)}
688
+ raise NotFoundError(
689
+ f"no anomaly event {event_id!r} in window {window!r}. An id depends on the "
690
+ "event's start and members, so list_anomaly_events with the same window again."
691
+ )
692
+
693
+
576
694
  def get_server_info(project: ProjectHandle) -> dict[str, Any]:
577
695
  profiles = project.profiles_config
578
696
  profile = profiles.get_profile(project.profile_name) if profiles is not None else None