Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
//! Seed the `metric_catalog` + product-default `metric_threshold` row for the
//! Zulip chat counter `collab_bullet_rows.zulip_messages_sent` introduced in
//! `m20260624_000001_collab_zulip_chat` (paired gold branch in
//! `20260518000000_collab-bullet-rewrite.sql`, Branch 4b).
//!
//! One `metric_key`, routed through the existing `collab_bullet_rows` section,
//! `source_tags = ["zulip-proxy"]`. Mirrors `m20260620_000002_seed_wiki_catalog`
//! (additive catalog seed). The threshold is a product-default placeholder;
//! tune per tenant via the admin CRUD API.

use sea_orm::{ConnectionTrait, Statement, Value};
use sea_orm_migration::prelude::*;
use uuid::Uuid;

#[derive(DeriveMigrationName)]
pub struct Migration;

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,
is_member_scale: bool,
source_tags: &'static [&'static str],
good: f64,
warn: f64,
}

fn source_tags_json(tags: &[&'static str]) -> String {
let mut out = String::from("[");
for (i, tag) in tags.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push('"');
for c in tag.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
_ => out.push(c),
}
}
out.push('"');
}
out.push(']');
out
}

const SEEDS: &[SeedRow] = &[SeedRow {
metric_key: "collab_bullet_rows.zulip_messages_sent",
label: "Zulip Messages",
sublabel: Some("Zulip \u{b7} chat messages sent \u{b7} period total"),
description: Some("Chat messages sent by the person in the period (Zulip)."),
unit: Some("messages"),
format: None,
higher_is_better: true,
is_member_scale: false,
source_tags: &["zulip-proxy"],
good: 50.0,
warn: 20.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, ?, ?, ?, ?, ?, ?, ?, ?, ?, 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)";

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();
let threshold_id = Uuid::now_v7();
let source_tags_json_str = source_tags_json(row.source_tags);

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(row.is_member_scale),
Value::from(source_tags_json_str.as_str()),
],
))
.await?;

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?;
}

tracing::info!(seeded = SEEDS.len(), "zulip collab metric_catalog seed applied");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Ok(())
}

async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {
Err(DbErr::Custom(
"m20260624_000002_seed_zulip_collab_catalog is irreversible: \
delete the collab_bullet_rows.zulip_messages_sent catalog row manually if needed."
.to_string(),
))
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn one_seed_routed_to_collab_bullet_rows() {
assert_eq!(SEEDS.len(), 1);
assert!(SEEDS[0]
.metric_key
.starts_with("collab_bullet_rows."));
assert_eq!(SEEDS[0].source_tags, &["zulip-proxy"]);
}
}
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 m20260624_000001_collab_zulip_chat;
mod m20260624_000002_seed_zulip_collab_catalog;

#[cfg(test)]
mod live_tests;
Expand Down Expand Up @@ -92,6 +94,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(m20260624_000001_collab_zulip_chat::Migration),
Box::new(m20260624_000002_seed_zulip_collab_catalog::Migration),
]
}
}
Expand Down
49 changes: 49 additions & 0 deletions src/ingestion/scripts/create-bronze-placeholders.sh
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ CREATE DATABASE IF NOT EXISTS bronze_cursor;
CREATE DATABASE IF NOT EXISTS bronze_slack;
CREATE DATABASE IF NOT EXISTS bronze_bamboohr;
CREATE DATABASE IF NOT EXISTS bronze_bitbucket_cloud;
CREATE DATABASE IF NOT EXISTS bronze_zulip_proxy;
SQL

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -986,4 +987,52 @@ CREATE TABLE IF NOT EXISTS bronze_slack.users_details (
SQL
fi

# bronze_zulip_proxy.messages — per-(sender, bucket) aggregated chat counts
# from the Zulip proxy. zulip_proxy__collab_chat_activity dedups by `uniq`,
# joins users on sender_id = id, and sums `count` per (sender email, date).
# The real Airbyte connector overwrites this on first sync (full schema in
# src/ingestion/connectors/collaboration/zulip-proxy/connector.yaml).
if ! ch_table_exists bronze_zulip_proxy messages; then
echo " Creating placeholder: bronze_zulip_proxy.messages"
run_ch <<'SQL'
CREATE TABLE IF NOT EXISTS bronze_zulip_proxy.messages (
uniq String,
sender_id Nullable(Int64),
count Nullable(Int64),
created_at String,
tenant_id Nullable(String),
source_id Nullable(String),
unique_key String,
_airbyte_raw_id String DEFAULT toString(generateUUIDv4()),
_airbyte_extracted_at DateTime64(3) DEFAULT now64(3),
_airbyte_meta String DEFAULT '{}',
_airbyte_generation_id UInt32 DEFAULT 0
) ENGINE = ReplacingMergeTree(_airbyte_extracted_at) ORDER BY unique_key;
SQL
fi

# bronze_zulip_proxy.users — Zulip user directory (full-refresh each sync).
# Joined by id = messages.sender_id to attach the sender email.
if ! ch_table_exists bronze_zulip_proxy users; then
echo " Creating placeholder: bronze_zulip_proxy.users"
run_ch <<'SQL'
CREATE TABLE IF NOT EXISTS bronze_zulip_proxy.users (
id Nullable(Int64),
uuid Nullable(String),
email Nullable(String),
full_name Nullable(String),
role Nullable(Int64),
is_active Nullable(Bool),
recipient_id Nullable(Int64),
tenant_id Nullable(String),
source_id Nullable(String),
unique_key String,
_airbyte_raw_id String DEFAULT toString(generateUUIDv4()),
_airbyte_extracted_at DateTime64(3) DEFAULT now64(3),
_airbyte_meta String DEFAULT '{}',
_airbyte_generation_id UInt32 DEFAULT 0
) ENGINE = ReplacingMergeTree(_airbyte_extracted_at) ORDER BY unique_key;
SQL
fi

echo "=== Placeholders: done ==="
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,11 @@
-- ARRAY JOIN (sumIf per source)
-- 3. `class_collab_chat_activity` M365 → 1 key
-- 4. `class_collab_chat_activity` Slack → 3 keys via ARRAY JOIN
-- 4b. `class_collab_chat_activity` Zulip → 1 key (zulip_messages_sent)
-- 5. `class_collab_document_activity` → 3 keys via ARRAY JOIN
-- 6. cross-class CTE → 1 key (m365_active_days)
--
-- 18 distinct metric_keys after rewrite (down from 20). The two
-- 19 distinct metric_keys after the Zulip add (was 18). The two
-- composite-ratio keys (`slack_msgs_per_active_day`, `slack_dm_ratio`)
-- visible on the FE live ONLY in the `query_ref` projection — they are
-- not emitted by the view.
Expand Down Expand Up @@ -194,6 +195,24 @@ WHERE s.data_source = 'insight_slack'

UNION ALL

-- ─── Branch 4b: class_collab_chat_activity — Zulip ───────────────────
-- Single key (zulip_messages_sent), no ARRAY JOIN needed. Mirrors the
-- m365 Teams branch: one silver row per (person, date) where
-- data_source = 'insight_zulip_proxy' → period-summed chat messages.
SELECT
lower(z.email) AS person_id,
p.org_unit_id AS org_unit_id,
z.date AS metric_date,
'zulip_messages_sent' AS metric_key,
toFloat64(ifNull(z.total_chat_messages, 0)) AS metric_value
FROM silver.class_collab_chat_activity AS z
LEFT JOIN insight.people AS p ON lower(z.email) = p.person_id
WHERE z.data_source = 'insight_zulip_proxy'
AND z.email IS NOT NULL
AND z.email != ''
Comment on lines +198 to +212

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major

🧩 Analysis chain

🌐 Web query:

ClickHouse ReplacingMergeTree SELECT without FINAL duplicate rows before background merges

💡 Result:

In ClickHouse, the ReplacingMergeTree engine does not automatically deduplicate rows during a standard SELECT query [1][2]. The engine is designed for eventual consistency; deduplication is a background process that occurs only when ClickHouse decides to merge data parts [1][3]. If you perform a SELECT query without the FINAL modifier, ClickHouse will return all versions of the rows currently present in the table, including duplicates that have not yet been processed by a background merge [1][2][3]. To ensure you receive only deduplicated results (i.e., only the latest version of each unique record based on the ORDER BY key), you must use one of the following approaches: 1. Use the FINAL modifier: Adding FINAL to your SELECT query forces ClickHouse to perform the deduplication logic at query time [1][2]. While this ensures correctness, it carries a performance cost because it requires extra processing during the query [1][4][5]. 2. Use a Session/Query Setting: For convenience, you can enable the final setting at the session or profile level (e.g., SETTINGS final = 1), which applies this logic to all relevant queries without needing to rewrite every SQL statement [6]. 3. Query Optimization: If using FINAL, you can improve performance by using the setting do_not_merge_across_partitions_select_final=1, which allows partitions to be processed independently [1][6][5]. Additionally, filtering on columns present in the ORDER BY or partition key can significantly reduce the amount of data processed during a FINAL query [1][6][7]. 4. Alternative Query Patterns: For performance-critical applications, some users prefer to avoid FINAL entirely by using aggregation functions like argMax in a GROUP BY clause to manually select the latest version of records [8][7]. Because background merges are unpredictable, you should never rely on the table being fully deduplicated for query correctness unless you explicitly use FINAL or handle deduplication in your query logic [1][2][4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the migration and the source table definition(s)
git ls-files | rg '20260518000000_collab-bullet-rewrite\.sql|class_collab_chat_activity|class_collab|zulip|ReplacingMergeTree|unique_key|_version' -n

# Show the relevant section of the migration with line numbers
sed -n '180,235p' src/ingestion/scripts/migrations/20260518000000_collab-bullet-rewrite.sql

# Search for the silver table definition and any upstream dedup logic
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'CREATE TABLE .*class_collab_chat_activity|class_collab_chat_activity|ReplacingMergeTree|FINAL|unique_key|_version|zulip_messages_sent|insight_zulip_proxy' .

Repository: constructorfabric/insight

Length of output: 50382


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find any table DDL or transformation around the silver.class_collab_chat_activity source
fd -a 'class_collab_chat_activity' .

Repository: constructorfabric/insight

Length of output: 248


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect relevant files and definitions with minimal output.
echo "=== migration snippet ==="
nl -ba src/ingestion/scripts/migrations/20260518000000_collab-bullet-rewrite.sql | sed -n '198,212p'

echo
echo "=== matching table definitions / references ==="
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'CREATE TABLE .*class_collab_chat_activity|ENGINE = ReplacingMergeTree|class_collab_chat_activity|zulip_messages_sent|insight_zulip_proxy|unique_key|_version|FINAL' \
  src . | sed -n '1,220p'

Repository: constructorfabric/insight

Length of output: 229


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== migration excerpt ==="
sed -n '198,212p' src/ingestion/scripts/migrations/20260518000000_collab-bullet-rewrite.sql

echo
echo "=== silver table definition ==="
sed -n '1,220p' /home/jailuser/git/src/ingestion/silver/collaboration/class_collab_chat_activity.sql

echo
echo "=== related joins / dedup patterns ==="
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'FROM silver\.class_collab_chat_activity|FINAL|ReplacingMergeTree|unique_key|zulip_messages_sent|insight_zulip_proxy' \
  src/ingestion | sed -n '1,220p'

Repository: constructorfabric/insight

Length of output: 28140


Read the Zulip branch with FINAL or dedupe upstream.
silver.class_collab_chat_activity is a ReplacingMergeTree(_version) table keyed by unique_key, so a plain SELECT can surface duplicate versions before merges and overcount zulip_messages_sent.

Proposed fix
-FROM silver.class_collab_chat_activity AS z
+FROM silver.class_collab_chat_activity AS z FINAL
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
-- ─── Branch 4b: class_collab_chat_activity — Zulip ───────────────────
-- Single key (zulip_messages_sent), no ARRAY JOIN needed. Mirrors the
-- m365 Teams branch: one silver row per (person, date) where
-- data_source = 'insight_zulip_proxy' → period-summed chat messages.
SELECT
lower(z.email) AS person_id,
p.org_unit_id AS org_unit_id,
z.date AS metric_date,
'zulip_messages_sent' AS metric_key,
toFloat64(ifNull(z.total_chat_messages, 0)) AS metric_value
FROM silver.class_collab_chat_activity AS z
LEFT JOIN insight.people AS p ON lower(z.email) = p.person_id
WHERE z.data_source = 'insight_zulip_proxy'
AND z.email IS NOT NULL
AND z.email != ''
-- ─── Branch 4b: class_collab_chat_activity — Zulip ───────────────────
-- Single key (zulip_messages_sent), no ARRAY JOIN needed. Mirrors the
-- m365 Teams branch: one silver row per (person, date) where
-- data_source = 'insight_zulip_proxy' → period-summed chat messages.
SELECT
lower(z.email) AS person_id,
p.org_unit_id AS org_unit_id,
z.date AS metric_date,
'zulip_messages_sent' AS metric_key,
toFloat64(ifNull(z.total_chat_messages, 0)) AS metric_value
FROM silver.class_collab_chat_activity AS z FINAL
LEFT JOIN insight.people AS p ON lower(z.email) = p.person_id
WHERE z.data_source = 'insight_zulip_proxy'
AND z.email IS NOT NULL
AND z.email != ''
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ingestion/scripts/migrations/20260518000000_collab-bullet-rewrite.sql`
around lines 198 - 212, The Zulip branch in the migration reads from
silver.class_collab_chat_activity without deduplication, so it can overcount
versions from ReplacingMergeTree(unique_key). Update the Branch 4b SELECT to
read the FINALized view of that table or otherwise dedupe upstream before
aggregating, and keep the existing filter on data_source = 'insight_zulip_proxy'
while preserving the metric mapping in the Zulip branch.


UNION ALL

-- ─── Branch 5: class_collab_document_activity (M365 OneDrive/SharePoint) ─
-- ARRAY JOIN emits 3 raw counters.
SELECT
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
-- depends_on: {{ ref('m365__collab_chat_activity') }}
-- depends_on: {{ ref('slack__collab_chat_activity') }}
-- depends_on: {{ ref('zulip_proxy__collab_chat_activity') }}
{{ config(
materialized='incremental',
unique_key='unique_key',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ cases:
find: { metric_key: m365_emails_sent }
equal: { value: 40, median: 20, range_min: 10, range_max: 40 }
- in: collaboration
assert: "size(items) == 20"
assert: "size(items) == 21" # 20 base collab keys + zulip_messages_sent (Branch 4b)
- in: collaboration
find: { metric_key: slack_dm_ratio }
equal: { value: null }
80 changes: 80 additions & 0 deletions src/ingestion/tests/e2e/specs/collab_zulip_chat.test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
spec_version: 1
description: >-
Zulip chat activity flows bronze → silver class_collab_chat_activity (via
union_by_tag) → gold insight.collab_bullet_rows (Branch 4b,
data_source='insight_zulip_proxy') → IC Bullet Collaboration metric_key
`zulip_messages_sent`. Mirrors collab_emails_sent: alice's own value vs her
team's median/range, with a bronze duplicate that must dedup.

# bronze — seed fixture. Key = TABLE NAME. People (org_unit) come from
# bamboohr; Zulip users supply the emails that join to them; Zulip messages
# carry the per-sender counts. alice 40, bob 20, carol 10 (all Engineering →
# one team) → value(alice)=40, team median=20, range [10,40]. alice has a
# duplicate `uniq` row (Airbyte re-emit) that must dedup → 40, not 80.
bronze:
bronze_bamboohr.employees:
- $ref: templates/people.yaml#/templates/alice
- $ref: templates/people.yaml#/templates/bob
- $ref: templates/people.yaml#/templates/carol

bronze_zulip_proxy.users:
- $ref: templates/zulip.yaml#/templates/alice_user
- $ref: templates/zulip.yaml#/templates/bob_user
- $ref: templates/zulip.yaml#/templates/carol_user

bronze_zulip_proxy.messages:
- $ref: templates/zulip.yaml#/templates/alice_message
uniq: z-alice-20260105
unique_key: zulip-msg-alice-20260105
count: 40

- $ref: templates/zulip.yaml#/templates/alice_message # duplicate uniq → must dedup, NOT sum to 80
uniq: z-alice-20260105
unique_key: zulip-msg-alice-20260105
count: 40

- $ref: templates/zulip.yaml#/templates/bob_message
uniq: z-bob-20260105
unique_key: zulip-msg-bob-20260105
count: 20

- $ref: templates/zulip.yaml#/templates/carol_message

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is carol in the same team as Alice and Bob?

@mitasovr mitasovr Jun 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes
and Carol is their manager )

uniq: z-carol-20260105
unique_key: zulip-msg-carol-20260105
count: 10

cases:
# IC Bullet Collaboration (…0012): value = the requested person's own value
# (from $filter); median/range = over their team (org_unit). All three are in
# Engineering → one team. zulip_messages_sent over the team = [alice 40,
# bob 20, carol 10]:
# value (alice) = 40 (the requested person)
# median = quantileExact(0.5)[10,20,40] = 20 (team median, NOT alice's)
# range (team) = [10, 40]
# alice is duplicated in bronze (same `uniq`) — her sum must stay 40 (dedup);
# otherwise the value, the median and the range would all drift.
- name: zulip_messages_sent — IC bullet (alice value vs team median, dedup)
request:
url: /v1/metrics/queries
method: POST
body:
queries:
- id: collaboration
metric_id: 00000000-0000-0000-0001-000000000012
$top: 50
$filter: "person_id eq 'alice@example.com' and metric_date ge '2026-01-01' and metric_date le '2026-01-31'"
$orderby: metric_key
expect:
- assert: "status == 200"
- in: collaboration
assert: "result.status == 'ok'"
- in: collaboration
find: { metric_key: zulip_messages_sent }
equal: { value: 40, median: 20, range_min: 10, range_max: 40 }
# The Zulip add raises the collaboration bullet from 20 to 21 FE-visible keys.
- in: collaboration
assert: "size(items) == 21"
# No Slack data seeded → the Slack-only DM ratio is null for this person.
- in: collaboration
find: { metric_key: slack_dm_ratio }
equal: { value: null }
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Reusable JSON schema for the table (all real placeholder columns). Resolved
# by table name. Mirrors bronze_zulip_proxy.messages in
# src/ingestion/scripts/create-bronze-placeholders.sh.
schemas:
bronze_zulip_proxy.messages:
$schema: http://json-schema.org/draft-07/schema#
type: object
additionalProperties: false
properties:
_airbyte_raw_id: { type: string }
_airbyte_extracted_at: { type: string, format: date-time }
_airbyte_meta: { type: string }
_airbyte_generation_id: { type: integer }
uniq: { type: string }
sender_id: { type: [number, "null"] }
count: { type: [number, "null"] }
created_at: { type: string }
tenant_id: { type: [string, "null"] }
source_id: { type: [string, "null"] }
unique_key: { type: string }
Loading
Loading