-
Notifications
You must be signed in to change notification settings - Fork 5
feat: add anomaly detection logic #117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Levosilimo
wants to merge
4
commits into
main
Choose a base branch
from
cwv-109-anomaly-detection-logic
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
apps/monitor-app/clickhouse/migrations/007_anomaly_detection.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| CREATE TABLE IF NOT EXISTS cwv_stats_hourly | ||
| ( | ||
| project_id UUID, | ||
| route String, | ||
| device_type LowCardinality(String), | ||
| metric_name LowCardinality(String), | ||
| hour DateTime, | ||
| avg_state AggregateFunction(avg, Float64), | ||
| var_state AggregateFunction(varSampStable, Float64), | ||
| count_state AggregateFunction(count, UInt64) | ||
| ) | ||
| ENGINE = AggregatingMergeTree | ||
| PARTITION BY toYYYYMM(hour) | ||
| ORDER BY (project_id, hour, route, device_type, metric_name) | ||
| TTL hour + INTERVAL 30 DAY; | ||
|
|
||
| CREATE MATERIALIZED VIEW IF NOT EXISTS mv_cwv_stats_hourly | ||
| TO cwv_stats_hourly | ||
| AS | ||
| SELECT | ||
| project_id, | ||
| route, | ||
| device_type, | ||
| metric_name, | ||
| toStartOfHour(recorded_at) AS hour, | ||
| avgState(log1p(metric_value)) AS avg_state, | ||
| varSampStableState(log1p(metric_value)) AS var_state, | ||
| countState() AS count_state | ||
| FROM cwv_events | ||
| GROUP BY project_id, hour, route, device_type, metric_name; | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| INSERT INTO cwv_stats_hourly | ||
| SELECT | ||
| project_id, | ||
| route, | ||
| device_type, | ||
| metric_name, | ||
| toStartOfHour(recorded_at) AS hour, | ||
| avgState(log1p(metric_value)) AS avg_state, | ||
| varSampStableState(log1p(metric_value)) AS var_state, | ||
| countState() AS count_state | ||
| FROM cwv_events | ||
| WHERE recorded_at >= toStartOfHour(now()) - INTERVAL 7 DAY | ||
| GROUP BY project_id, hour, route, device_type, metric_name; | ||
|
|
||
| CREATE VIEW IF NOT EXISTS v_cwv_anomalies AS | ||
| WITH | ||
| toStartOfHour(now()) AS current_hour_mark, | ||
| current_hour_mark - INTERVAL 1 HOUR AS gap_hour, | ||
| current_hour_mark - INTERVAL 7 DAY AS baseline_start | ||
| SELECT | ||
| lower(hex(MD5(concat( | ||
| toString(project_id), '\0', route, '\0', metric_name, '\0', device_type, '\0', toString(current_hour_mark) | ||
| )))) AS anomaly_id, | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| project_id, route, metric_name, device_type, | ||
| current_hour_mark AS detection_time, | ||
|
|
||
| avgMergeIf(avg_state, hour = current_hour_mark) AS log_avg_curr, | ||
| avgMergeIf(avg_state, hour >= baseline_start AND hour < gap_hour) AS log_avg_base, | ||
| sqrt(varSampStableMergeIf(var_state, hour >= baseline_start AND hour < gap_hour)) AS log_stddev_base, | ||
|
|
||
| exp(log_avg_curr) - 1 AS current_avg_raw, | ||
| exp(log_avg_base) - 1 AS baseline_avg_raw, | ||
|
|
||
| countMergeIf(count_state, hour = current_hour_mark) AS sample_size, | ||
| countMergeIf(count_state, hour >= baseline_start AND hour < gap_hour) AS baseline_n, | ||
|
|
||
| (log_avg_curr - log_avg_base) / IF(log_stddev_base = 0, 0.00001, log_stddev_base) AS z_score | ||
| FROM cwv_stats_hourly | ||
| WHERE hour >= baseline_start | ||
| GROUP BY project_id, route, device_type, metric_name | ||
| HAVING sample_size >= 20 AND baseline_n >= 100; | ||
|
|
||
| CREATE TABLE IF NOT EXISTS processed_anomalies | ||
| ( | ||
| anomaly_id String, | ||
| project_id UUID, | ||
| metric_name LowCardinality(String), | ||
| route String, | ||
| device_type LowCardinality(String), | ||
| last_z_score Float64, | ||
| notified_at DateTime DEFAULT now(), | ||
| status Enum8('new' = 1, 'notified' = 2, 'acknowledged' = 3, 'resolved' = 4) DEFAULT 'new', | ||
| updated_at DateTime64(3) DEFAULT now64(3) | ||
| ) | ||
| ENGINE = ReplacingMergeTree(updated_at) | ||
| ORDER BY (project_id, anomaly_id); | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| CREATE SETTINGS PROFILE IF NOT EXISTS ai_analyst_profile SETTINGS | ||
| max_execution_time = 15, | ||
| max_memory_usage = 2000000000, | ||
| max_rows_to_read = 100000000; | ||
|
|
||
| CREATE ROLE IF NOT EXISTS r_ai_analyst; | ||
| GRANT SELECT ON cwv_events TO r_ai_analyst; | ||
| GRANT SELECT ON custom_events TO r_ai_analyst; | ||
| GRANT SELECT ON cwv_daily_aggregates TO r_ai_analyst; | ||
| GRANT SELECT ON cwv_stats_hourly TO r_ai_analyst; | ||
| GRANT SELECT ON v_cwv_anomalies TO r_ai_analyst; | ||
| GRANT SELECT ON projects TO r_ai_analyst; | ||
| GRANT SELECT, INSERT, ALTER UPDATE ON processed_anomalies TO r_ai_analyst; | ||
|
|
||
| CREATE USER IF NOT EXISTS ai_analyst_user | ||
| IDENTIFIED WITH no_password; | ||
| GRANT r_ai_analyst TO ai_analyst_user; | ||
Levosilimo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ALTER USER ai_analyst_user DEFAULT ROLE r_ai_analyst; | ||
| ALTER USER ai_analyst_user SETTINGS PROFILE ai_analyst_profile; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
apps/monitor-app/src/app/server/lib/clickhouse/bootstrap.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| import { sql } from "@/app/server/lib/clickhouse/client"; | ||
| import { env } from "@/env"; | ||
|
|
||
| export async function syncDatabaseRoles() { | ||
| const aiUser = env.AI_ANALYST_CLICKHOUSE_USER; | ||
| const aiPass = env.AI_ANALYST_CLICKHOUSE_PASSWORD; | ||
|
|
||
| if (!aiUser || !aiPass) return; | ||
|
|
||
| await sql` | ||
| ALTER USER IF EXISTS ${sql.identifier(aiUser)} IDENTIFIED WITH sha256_password BY ${aiPass} | ||
| `.command(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,7 @@ | ||
| import { syncDatabaseRoles } from "@/app/server/lib/clickhouse/bootstrap"; | ||
| import { provisionInitialUser } from "@/lib/provision-initial-user"; | ||
|
|
||
| export async function register() { | ||
| await provisionInitialUser(); | ||
| await syncDatabaseRoles(); | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.