Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

const ZERO_TENANT: &str = "00000000000000000000000000000000";
const AI_PERSONAL_HEX: &str = "00000000000000000001000000000050";
const AI_PERSONAL_TREND_HEX: &str = "00000000000000000001000000000051";
const AI_PERSONAL_COUNTERS_HEX: &str = "00000000000000000001000000000052";

const AI_TOOL_NAME_SQL: &str = "multiIf(tool = 'claude_code', 'Claude Code', tool = 'cursor', 'Cursor', tool = 'codex', 'Codex', tool = 'copilot', 'GitHub Copilot', tool = 'windsurf', 'Windsurf', tool)";
const AI_PERSON_COUNTER_VALUES_QR: &str = r#"SELECT metric_values.person_id AS person_id, p.org_unit_id AS org_unit_id, metric_values.metric_key AS metric_key, metric_values.value AS value FROM (SELECT person_id, kv.1 AS metric_key, kv.2 AS value FROM (SELECT person_id, if(countIf(ai_accepted_lines IS NOT NULL) > 0, sumIf(ai_accepted_lines, ai_accepted_lines IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_accepted_lines, if(countIf(ai_removed_lines IS NOT NULL) > 0, sumIf(ai_removed_lines, ai_removed_lines IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_removed_lines, if(countIf(ai_active_days IS NOT NULL) > 0, sumIf(ai_active_days, ai_active_days IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_active_days, if(countIf(ai_cost_cents IS NOT NULL) > 0, sumIf(ai_cost_cents, ai_cost_cents IS NOT NULL) / 100, CAST(NULL AS Nullable(Float64))) AS ai_cost, if(countIf(ai_accepted_edit_actions IS NOT NULL) > 0, sumIf(ai_accepted_edit_actions, ai_accepted_edit_actions IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_accepted_edit_actions, if(sumIf(ai_tool_acceptance_offered, ai_tool_acceptance_offered IS NOT NULL) > 0, 100 * sumIf(ai_tool_acceptance_accepted, ai_tool_acceptance_accepted IS NOT NULL) / sumIf(ai_tool_acceptance_offered, ai_tool_acceptance_offered IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_tool_acceptance_rate, if(countIf(ai_assistant_messages IS NOT NULL) > 0, sumIf(ai_assistant_messages, ai_assistant_messages IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_assistant_messages, if(countIf(ai_assistant_actions IS NOT NULL) > 0, sumIf(ai_assistant_actions, ai_assistant_actions IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_assistant_actions, if(countIf(ai_dev_agent_conversations IS NOT NULL) > 0, sumIf(ai_dev_agent_conversations, ai_dev_agent_conversations IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_dev_agent_conversations, if(countIf(ai_chat_assistant_conversations IS NOT NULL) > 0, sumIf(ai_chat_assistant_conversations, ai_chat_assistant_conversations IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS ai_chat_assistant_conversations FROM insight.ai_person_counter_daily GROUP BY person_id) d ARRAY JOIN [('ai_person_counter_daily.ai_accepted_lines', ai_accepted_lines), ('ai_person_counter_daily.ai_removed_lines', ai_removed_lines), ('ai_person_counter_daily.ai_active_days', ai_active_days), ('ai_person_counter_daily.ai_cost', ai_cost), ('ai_person_counter_daily.ai_accepted_edit_actions', ai_accepted_edit_actions), ('ai_person_counter_daily.ai_tool_acceptance_rate', ai_tool_acceptance_rate), ('ai_person_counter_daily.ai_assistant_messages', ai_assistant_messages), ('ai_person_counter_daily.ai_assistant_actions', ai_assistant_actions), ('ai_person_counter_daily.ai_dev_agent_conversations', ai_dev_agent_conversations), ('ai_person_counter_daily.ai_chat_assistant_conversations', ai_chat_assistant_conversations)] AS kv WHERE kv.2 IS NOT NULL) metric_values LEFT JOIN insight.people AS p ON metric_values.person_id = p.person_id"#;

fn ai_personal_qr() -> String {
format!(
"SELECT person_id, tool, {AI_TOOL_NAME_SQL} AS tool_name, sum(accepted_lines_added) AS accepted_lines_added, sum(accepted_lines_removed) AS accepted_lines_removed, if(countIf(cost_cents IS NOT NULL) > 0, sumIf(cost_cents, cost_cents IS NOT NULL), CAST(NULL AS Nullable(Float64))) AS cost_cents, uniqExact(metric_date) AS active_days FROM insight.ai_dev_tool_daily GROUP BY person_id, tool"
)
}

fn ai_personal_trend_qr() -> String {
format!(
"SELECT person_id, metric_date, tool, {AI_TOOL_NAME_SQL} AS tool_name, sum(accepted_lines_added) AS accepted_lines_added FROM insight.ai_dev_tool_trend GROUP BY person_id, metric_date, tool"
)
}

fn ai_personal_counters_qr() -> String {
format!(
"SELECT p.person_id AS person_id, p.org_unit_id AS org_unit_id, p.metric_key AS metric_key, p.value AS value, c.team_median AS median, c.team_p25 AS p25, c.team_p75 AS p75, c.team_n AS n, c.team_min AS range_min, c.team_max AS range_max FROM ({AI_PERSON_COUNTER_VALUES_QR}) p LEFT JOIN (SELECT metric_key, org_unit_id, quantileExact(0.5)(value) AS team_median, quantileExact(0.25)(value) AS team_p25, quantileExact(0.75)(value) AS team_p75, toFloat64(count()) AS team_n, min(value) AS team_min, max(value) AS team_max FROM ({AI_PERSON_COUNTER_VALUES_QR}) person_values GROUP BY metric_key, org_unit_id) c ON c.metric_key = p.metric_key AND c.org_unit_id = p.org_unit_id"
)
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
let db = manager.get_connection();
let ai_personal_counters_qr = ai_personal_counters_qr();
let ai_personal_qr = ai_personal_qr();
let ai_personal_trend_qr = ai_personal_trend_qr();
for (hex, name, description, query) in [
(
AI_PERSONAL_HEX,
"AI Tool Summary",
"Per-person AI tool summary rows.",
ai_personal_qr,
),
(
AI_PERSONAL_TREND_HEX,
"AI Tool Trend",
"Per-person daily AI accepted-lines rows by tool.",
ai_personal_trend_qr,
),
(
AI_PERSONAL_COUNTERS_HEX,
"AI Personal Peer Counters",
"Per-person AI peer counter rows.",
ai_personal_counters_qr,
),
] {
db.execute_unprepared(&format!(
"INSERT INTO metrics (id, insight_tenant_id, name, description, query_ref, is_enabled) \
VALUES (UNHEX('{hex}'), UNHEX('{ZERO_TENANT}'), '{name}', '{description}', '{qr}', 1) \
ON DUPLICATE KEY UPDATE name=VALUES(name), description=VALUES(description), query_ref=VALUES(query_ref), is_enabled=1",
qr = query.replace('\'', "''"),
))
.await?;
}
Ok(())
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.get_connection()
.execute_unprepared(&format!(
"DELETE FROM metrics WHERE id IN (UNHEX('{AI_PERSONAL_HEX}'), UNHEX('{AI_PERSONAL_TREND_HEX}'), UNHEX('{AI_PERSONAL_COUNTERS_HEX}'))"
))
.await?;
Ok(())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
use sea_orm::{ConnectionTrait, Statement, Value};
use sea_orm_migration::prelude::*;
use uuid::Uuid;

#[derive(DeriveMigrationName)]
pub struct Migration;

const AI_PERSONAL_COUNTERS_HEX: &str = "00000000000000000001000000000052";

struct SeedRow {
metric_key: &'static str,
label: &'static str,
sublabel: Option<&'static str>,
description: Option<&'static str>,
unit: Option<&'static str>,
format: Option<&'static str>,
higher_is_better: bool,
good: f64,
warn: f64,
}

const SEEDS: &[SeedRow] = &[
SeedRow {
metric_key: "ai_person_counter_daily.ai_accepted_lines",
label: "AI-added lines",
sublabel: Some("Accepted added coding output"),
description: Some("Accepted AI-generated added lines across coding AI tools."),
unit: Some("lines"),
format: Some("integer"),
higher_is_better: true,
good: 1000.0,
warn: 100.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_active_days",
label: "AI active days",
sublabel: Some("Days with coding AI activity"),
description: Some("Distinct days with person-attributed coding AI activity."),
unit: Some("days"),
format: None,
higher_is_better: true,
good: 10.0,
warn: 3.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_removed_lines",
label: "AI-removed lines",
sublabel: Some("Accepted deleted coding output"),
description: Some("Accepted AI-generated removed lines across coding AI tools."),
unit: Some("lines"),
format: Some("integer"),
higher_is_better: true,
good: 0.0,
warn: 1000.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_cost",
label: "Reported AI cost",
sublabel: Some("Metered tool spend"),
description: Some("Person-attributed AI cost where the connector reports cost."),
unit: Some("$"),
format: Some("currency"),
higher_is_better: false,
good: 0.0,
warn: 50.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_accepted_edit_actions",
label: "Accepted AI edits",
sublabel: Some("Accepted tool/edit suggestions"),
description: Some("Accepted AI edit or tool suggestions across supported coding AI tools."),
unit: Some("actions"),
format: Some("integer"),
higher_is_better: true,
good: 50.0,
warn: 10.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_tool_acceptance_rate",
label: "AI tool acceptance",
sublabel: Some("Accepted ÷ offered AI edits"),
description: Some("Accepted AI edit/tool suggestions divided by offered suggestions."),
unit: Some("%"),
format: Some("percent"),
higher_is_better: true,
good: 50.0,
warn: 20.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_assistant_messages",
label: "AI assistant messages",
sublabel: Some("Chat and assistant messages"),
description: Some(
"Person-attributed assistant messages from supported AI assistant tools.",
),
unit: Some("messages"),
format: Some("integer"),
higher_is_better: true,
good: 50.0,
warn: 10.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_assistant_actions",
label: "AI assistant actions",
sublabel: Some("Assistant/cowork actions"),
description: Some("Person-attributed assistant actions from supported AI assistant tools."),
unit: Some("actions"),
format: Some("integer"),
higher_is_better: true,
good: 10.0,
warn: 1.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_dev_agent_conversations",
label: "AI dev conversations",
sublabel: Some("Claude Code sessions and Codex threads"),
description: Some("Person-attributed coding-agent conversations from supported AI dev tools."),
unit: Some("conversations"),
format: Some("integer"),
higher_is_better: true,
good: 20.0,
warn: 5.0,
},
SeedRow {
metric_key: "ai_person_counter_daily.ai_chat_assistant_conversations",
label: "AI chat conversations",
sublabel: Some("Chat assistant threads"),
description: Some("Person-attributed chat assistant conversations from supported AI chat tools."),
unit: Some("conversations"),
format: Some("integer"),
higher_is_better: true,
good: 20.0,
warn: 5.0,
},
];

const INSERT_CATALOG_SQL: &str = "\
INSERT INTO metric_catalog \
(id, tenant_id, metric_key, label, sublabel, description, unit, format, \
higher_is_better, is_member_scale, source_tags, is_enabled) \
VALUES (?, NULL, ?, ?, ?, ?, ?, ?, ?, FALSE, ?, TRUE) \
ON DUPLICATE KEY UPDATE \
label = VALUES(label), \
sublabel = VALUES(sublabel), \
description = VALUES(description), \
unit = VALUES(unit), \
format = VALUES(format), \
higher_is_better = VALUES(higher_is_better), \
is_member_scale = VALUES(is_member_scale), \
source_tags = VALUES(source_tags), \
is_enabled = VALUES(is_enabled)";

const INSERT_THRESHOLD_SQL: &str = "\
INSERT INTO metric_threshold \
(id, tenant_id, metric_key, scope, role_slug, team_id, good, warn, is_locked) \
VALUES (?, NULL, ?, 'product-default', '', '', ?, ?, FALSE) \
ON DUPLICATE KEY UPDATE \
good = VALUES(good), \
warn = VALUES(warn)";

const INSERT_LINK_SQL: &str = "\
INSERT IGNORE INTO metric_query_catalog \
(id, metrics_id, metric_catalog_id) \
SELECT UNHEX(REPLACE(UUID(),'-','')), UNHEX(?), c.id \
FROM metric_catalog c \
WHERE c.metric_key = ? AND c.tenant_id IS NULL";

fn nullable_str_value(v: Option<&str>) -> Value {
match v {
Some(s) => Value::from(s),
None => Value::String(None),
}
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
let conn = manager.get_connection();
let backend = manager.get_database_backend();

for row in SEEDS {
let catalog_id = Uuid::now_v7();
conn.execute(Statement::from_sql_and_values(
backend,
INSERT_CATALOG_SQL,
[
Value::Bytes(Some(Box::new(catalog_id.as_bytes().to_vec()))),
Value::from(row.metric_key),
Value::from(row.label),
nullable_str_value(row.sublabel),
nullable_str_value(row.description),
nullable_str_value(row.unit),
nullable_str_value(row.format),
Value::from(row.higher_is_better),
Value::from("[]"),
],
))
.await?;

let threshold_id = Uuid::now_v7();
conn.execute(Statement::from_sql_and_values(
backend,
INSERT_THRESHOLD_SQL,
[
Value::Bytes(Some(Box::new(threshold_id.as_bytes().to_vec()))),
Value::from(row.metric_key),
Value::from(row.good),
Value::from(row.warn),
],
))
.await?;

conn.execute(Statement::from_sql_and_values(
backend,
INSERT_LINK_SQL,
[
Value::from(AI_PERSONAL_COUNTERS_HEX),
Value::from(row.metric_key),
],
))
.await?;
}

Ok(())
}

async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {
Err(DbErr::Custom("we have only forward migrations".to_owned()))
}
}
4 changes: 4 additions & 0 deletions src/backend/services/analytics-api/src/migration/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ mod m20260618_000001_ai_claude_team_overage_metric;
mod m20260618_000002_seed_claude_team_overage_catalog;
mod m20260620_000001_seed_wiki_metrics;
mod m20260620_000002_seed_wiki_catalog;
mod m20260623_000001_ai_personal_queries;
mod m20260623_000002_seed_ai_personal_metric_catalog;
mod m20260624_000001_collab_zulip_chat;
mod m20260624_000002_seed_zulip_collab_catalog;
mod m20260624_000003_ic_chart_loc_git_breakdown;
Expand Down Expand Up @@ -95,6 +97,8 @@ impl MigratorTrait for Migrator {
Box::new(m20260618_000002_seed_claude_team_overage_catalog::Migration),
Box::new(m20260620_000001_seed_wiki_metrics::Migration),
Box::new(m20260620_000002_seed_wiki_catalog::Migration),
Box::new(m20260623_000001_ai_personal_queries::Migration),
Box::new(m20260623_000002_seed_ai_personal_metric_catalog::Migration),
Box::new(m20260624_000001_collab_zulip_chat::Migration),
Box::new(m20260624_000002_seed_zulip_collab_catalog::Migration),
Box::new(m20260624_000003_ic_chart_loc_git_breakdown::Migration),
Expand Down
11 changes: 11 additions & 0 deletions src/ingestion/scripts/create-bronze-placeholders.sh
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,10 @@ if ! ch_table_exists silver class_ai_dev_usage; then
run_ch <<'SQL'
CREATE TABLE IF NOT EXISTS silver.class_ai_dev_usage (
insight_tenant_id String,
source_id String,
unique_key String,
email String,
api_key_id Nullable(String),
day Date,
tool String,
is_active UInt8,
Expand All @@ -203,14 +206,22 @@ CREATE TABLE IF NOT EXISTS silver.class_ai_dev_usage (
tool_use_offered Nullable(Float64),
tool_use_accepted Nullable(Float64),
lines_added Nullable(Float64),
lines_removed Nullable(Float64),
total_lines_added Nullable(Float64),
total_lines_removed Nullable(Float64),
accepted_lines_added Nullable(Float64),
spec_lines Nullable(Float64),
session_count Nullable(Float64),
total_chat_messages Nullable(Float64),
cost_cents Nullable(UInt32),
commits_count Nullable(UInt32),
pull_requests_count Nullable(UInt32),
prs_with_cc_count Nullable(UInt32),
prs_total_count Nullable(UInt32),
tool_action_breakdown_json Nullable(String),
source String,
data_source String,
collected_at Nullable(DateTime64(3)),
_version UInt64
) ENGINE = ReplacingMergeTree(_version) ORDER BY (email, day) COMMENT 'INSIGHT_PLACEHOLDER_v1';
SQL
Expand Down
Loading
Loading