Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

[BOT-1406] Fix & backport metabot IP & embed_url (#73613)

Tyler Pludebbc5af48c4c6
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj
index f8320f13d6b..6ef759d6bb6 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj
@@ -41,6 +41,10 @@
[:search_count ms/IntGreaterThanOrEqualToZero]
[:query_count ms/IntGreaterThanOrEqualToZero]
[:ip_address [:maybe :string]]
+ [:embedding_hostname [:maybe :string]]
+ [:embedding_path [:maybe :string]]
+ [:user_agent [:maybe :string]]
+ [:sanitized_user_agent [:maybe :string]]
[:user [:maybe UserInfo]]])
(def ^:private SortColumn
@@ -108,8 +112,12 @@
[:queries [:sequential GeneratedQuery]]
[:search_count ms/IntGreaterThanOrEqualToZero]
[:query_count ms/IntGreaterThanOrEqualToZero]
- [:ip_address [:maybe :string]]
- [:feedback [:sequential ConversationFeedback]]])
+ [:ip_address [:maybe :string]]
+ [:embedding_hostname [:maybe :string]]
+ [:embedding_path [:maybe :string]]
+ [:user_agent [:maybe :string]]
+ [:sanitized_user_agent [:maybe :string]]
+ [:feedback [:sequential ConversationFeedback]]])
(def ^:private ListConversationsResponse
"Response schema for `GET /conversations`."
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
index 28d8dbc772f..f2a6b5ee5d8 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
@@ -121,6 +121,10 @@
:search_count (:search_count row 0)
:query_count (:query_count row 0)
:ip_address (:ip_address row)
+ :embedding_hostname (:embedding_hostname row)
+ :embedding_path (:embedding_path row)
+ :user_agent (:user_agent row)
+ :sanitized_user_agent (:sanitized_user_agent row)
:user (trim-user (:user row))})
(defn- hydrate-tool-counts
@@ -228,5 +232,9 @@
:search_count (analytics.queries/count-tool-invocations messages "search")
:query_count (analytics.queries/count-tool-invocations
messages analytics.queries/new-query-tool-names)
- :ip_address (:ip_address conversation)
- :feedback (fetch-conversation-feedback conversation-id)})))
+ :ip_address (:ip_address conversation)
+ :embedding_hostname (:embedding_hostname conversation)
+ :embedding_path (:embedding_path conversation)
+ :user_agent (:user_agent conversation)
+ :sanitized_user_agent (:sanitized_user_agent conversation)
+ :feedback (fetch-conversation-feedback conversation-id)})))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_analytics/v_metabot_conversations_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_analytics/v_metabot_conversations_test.clj
index a912cbcc7de..5e2edabbda8 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_analytics/v_metabot_conversations_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_analytics/v_metabot_conversations_test.clj
@@ -264,6 +264,32 @@
(is (=? {:ip_address "10.0.0.1"} w-ip))
(is (nil? (:ip_address no-ip))))))))
+(deftest pii-fields-roundtrip-test
+ (testing "embedding_hostname/embedding_path/user_agent/sanitized_user_agent round-trip through the view"
+ (let [convo-with (str (random-uuid))
+ convo-without (str (random-uuid))]
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/MetabotConversation _ {:id convo-with
+ :user_id user-id
+ :embedding_hostname "customer.example.com"
+ :embedding_path "/dashboard/42"
+ :user_agent "Mozilla/5.0 (TestAgent)"
+ :sanitized_user_agent "Chrome 130 / macOS"}
+ :model/MetabotConversation _ {:id convo-without
+ :user_id user-id}]
+ (let [rows (query-view [convo-with convo-without])
+ w (find-row rows convo-with)
+ wo (find-row rows convo-without)]
+ (is (=? {:embedding_hostname "customer.example.com"
+ :embedding_path "/dashboard/42"
+ :user_agent "Mozilla/5.0 (TestAgent)"
+ :sanitized_user_agent "Chrome 130 / macOS"}
+ w))
+ (is (nil? (:embedding_hostname wo)))
+ (is (nil? (:embedding_path wo)))
+ (is (nil? (:user_agent wo)))
+ (is (nil? (:sanitized_user_agent wo))))))))
+
(deftest tenant-id-and-name-test
(testing "tenant_id and tenant_name come from ai_usage_log joined with tenant table"
(let [convo-id (str (random-uuid))]
diff --git a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/types.ts b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/types.ts
index 0f2bef58008..ff280b74850 100644
--- a/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/audit_app/metabot-analytics/types.ts
@@ -28,6 +28,10 @@ export type ConversationSummary = {
search_count: number;
query_count: number;
ip_address: string | null;
+ embedding_hostname: string | null;
+ embedding_path: string | null;
+ user_agent: string | null;
+ sanitized_user_agent: string | null;
user: MetabotUserInfo | null;
};
@@ -88,6 +92,10 @@ export type ConversationDetail = {
search_count: number;
query_count: number;
ip_address: string | null;
+ embedding_hostname: string | null;
+ embedding_path: string | null;
+ user_agent: string | null;
+ sanitized_user_agent: string | null;
feedback: ConversationFeedback[];
};
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/embedding_hostname.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/embedding_hostname.yaml
new file mode 100644
index 00000000000..b1c227e01c1
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/embedding_hostname.yaml
@@ -0,0 +1,23 @@
+name: embedding_hostname
+display_name: Embedding Hostname
+description: Hostname extracted from the embed referrer at the originating conversation. Always recorded when an embed referrer is present, independent of the analytics-pii-retention-enabled flag.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_ai_usage_log]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+semantic_type: type/Category
+dimensions: []
+position: 17
+custom_position: 0
+database_position: 17
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_ai_usage_log, model: Table}
+- {id: embedding_hostname, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/embedding_path.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/embedding_path.yaml
new file mode 100644
index 00000000000..59c481c4672
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/embedding_path.yaml
@@ -0,0 +1,22 @@
+name: embedding_path
+display_name: Embedding Path
+description: Path portion of the embed referrer URL at the originating conversation. PII; only recorded when analytics-pii-retention-enabled is on.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_ai_usage_log]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+dimensions: []
+position: 18
+custom_position: 0
+database_position: 18
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_ai_usage_log, model: Table}
+- {id: embedding_path, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/sanitized_user_agent.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/sanitized_user_agent.yaml
new file mode 100644
index 00000000000..4f768c4486d
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/sanitized_user_agent.yaml
@@ -0,0 +1,23 @@
+name: sanitized_user_agent
+display_name: Sanitized User Agent
+description: Sanitized User-Agent string (browser + OS family) at the originating conversation, for analytics display.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_ai_usage_log]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+semantic_type: type/Category
+dimensions: []
+position: 20
+custom_position: 0
+database_position: 20
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_ai_usage_log, model: Table}
+- {id: sanitized_user_agent, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/user_agent.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/user_agent.yaml
new file mode 100644
index 00000000000..0ee5b54b099
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_ai_usage_log/fields/user_agent.yaml
@@ -0,0 +1,22 @@
+name: user_agent
+display_name: User Agent
+description: Raw User-Agent header captured at the originating conversation. PII; only recorded when analytics-pii-retention-enabled is on.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_ai_usage_log]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+dimensions: []
+position: 19
+custom_position: 0
+database_position: 19
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_ai_usage_log, model: Table}
+- {id: user_agent, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/embedding_hostname.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/embedding_hostname.yaml
new file mode 100644
index 00000000000..3fb66c2bc45
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/embedding_hostname.yaml
@@ -0,0 +1,23 @@
+name: embedding_hostname
+display_name: Embedding Hostname
+description: Hostname extracted from the embed referrer header at conversation creation. Always recorded when an embed referrer is present, independent of the analytics-pii-retention-enabled flag.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_metabot_conversations]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+semantic_type: type/Category
+dimensions: []
+position: 21
+custom_position: 0
+database_position: 21
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_metabot_conversations, model: Table}
+- {id: embedding_hostname, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/embedding_path.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/embedding_path.yaml
new file mode 100644
index 00000000000..1fe87f46775
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/embedding_path.yaml
@@ -0,0 +1,22 @@
+name: embedding_path
+display_name: Embedding Path
+description: Path portion of the embed referrer URL captured at conversation creation. PII; only recorded when analytics-pii-retention-enabled is on.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_metabot_conversations]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+dimensions: []
+position: 22
+custom_position: 0
+database_position: 22
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_metabot_conversations, model: Table}
+- {id: embedding_path, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/sanitized_user_agent.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/sanitized_user_agent.yaml
new file mode 100644
index 00000000000..b400cf36f1e
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/sanitized_user_agent.yaml
@@ -0,0 +1,23 @@
+name: sanitized_user_agent
+display_name: Sanitized User Agent
+description: Sanitized User-Agent string (browser + OS family) at the originating conversation, for analytics display.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_metabot_conversations]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+semantic_type: type/Category
+dimensions: []
+position: 24
+custom_position: 0
+database_position: 24
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_metabot_conversations, model: Table}
+- {id: sanitized_user_agent, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/user_agent.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/user_agent.yaml
new file mode 100644
index 00000000000..074ea5615e3
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_metabot_conversations/fields/user_agent.yaml
@@ -0,0 +1,22 @@
+name: user_agent
+display_name: User Agent
+description: Raw User-Agent header captured at conversation creation. PII; only recorded when analytics-pii-retention-enabled is on.
+created_at: '2026-05-04T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_metabot_conversations]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+dimensions: []
+position: 23
+custom_position: 0
+database_position: 23
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_metabot_conversations, model: Table}
+- {id: user_agent, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/migrations/061/20260504_metabot_conversation_pii_compliance.yaml b/resources/migrations/061/20260504_metabot_conversation_pii_compliance.yaml
new file mode 100644
index 00000000000..870cd43eb1d
--- /dev/null
+++ b/resources/migrations/061/20260504_metabot_conversation_pii_compliance.yaml
@@ -0,0 +1,201 @@
+## BOT-1406 — Metabot GDPR PII gating.
+##
+## Bring metabot_conversation PII collection under analytics-pii-retention-enabled,
+## matching the gating already in place for view_log and query_execution.
+##
+## Order matters: addColumn → discard pre-flag PII → backfill → dropColumn →
+## re-create analytics views. All steps must live in this single file (and run
+## in this order) because Liquibase processes change-log files alphabetically;
+## splitting across files would re-order the steps.
+##
+## Pre-flag PII is discarded rather than carried forward:
+## - The path portion of the existing embed_url is intentionally NOT migrated
+## to embedding_path. It is the PII fraction of the URL and was collected
+## before the flag existed; there is no consent basis for those legacy values.
+## Only the hostname survives, into embedding_hostname.
+## - Existing ip_address values are NULLed for the same reason: they predate
+## analytics-pii-retention-enabled gating, so there is no consent basis to
+## keep them.
+## Carrying either forward would launder unconsented PII into a post-flag schema.
+
+databaseChangeLog:
+ - changeSet:
+ id: v61.2wozp4
+ author: tyler
+ comment: Add embedding_hostname to metabot_conversation
+ changes:
+ - addColumn:
+ tableName: metabot_conversation
+ columns:
+ - column:
+ name: embedding_hostname
+ type: varchar(512)
+ remarks: Hostname extracted from the embed referrer header at conversation creation. Always populated when an embed referrer is present.
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: metabot_conversation
+ columnName: embedding_hostname
+
+ - changeSet:
+ id: v61.ljr45i
+ author: tyler
+ comment: Add embedding_path to metabot_conversation, PII
+ changes:
+ - addColumn:
+ tableName: metabot_conversation
+ columns:
+ - column:
+ name: embedding_path
+ type: varchar(2048)
+ remarks: Path extracted from the embed referrer header at conversation creation, PII.
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: metabot_conversation
+ columnName: embedding_path
+
+ - changeSet:
+ id: v61.g2jc0k
+ author: tyler
+ comment: Add user_agent to metabot_conversation, PII
+ changes:
+ - addColumn:
+ tableName: metabot_conversation
+ columns:
+ - column:
+ name: user_agent
+ type: varchar(512)
+ remarks: Raw User-Agent header captured at conversation creation, PII.
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: metabot_conversation
+ columnName: user_agent
+
+ - changeSet:
+ id: v61.gc7wz4
+ author: tyler
+ comment: Add sanitized_user_agent to metabot_conversation, PII
+ changes:
+ - addColumn:
+ tableName: metabot_conversation
+ columns:
+ - column:
+ name: sanitized_user_agent
+ type: varchar(512)
+ remarks: Sanitized User-Agent string (browser + OS family) at the originating conversation, for analytics display.
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: metabot_conversation
+ columnName: sanitized_user_agent
+
+ - changeSet:
+ id: v61.uabwhr
+ author: tyler
+ comment: Discard pre-flag ip_address values on metabot_conversation (collected without analytics-pii-retention-enabled gating, no consent basis going forward)
+ changes:
+ - update:
+ tableName: metabot_conversation
+ columns:
+ - column:
+ name: ip_address
+ value: null
+ rollback:
+ - empty: {}
+
+ - changeSet:
+ id: v61.9q8n1e
+ author: tyler
+ comment: Backfill embedding_hostname on metabot_conversation from existing embed_url values (path portion intentionally not migrated)
+ changes:
+ - customChange:
+ class: metabase.app_db.custom_migrations.BackfillMetabotConversationEmbeddingHostname
+
+ - changeSet:
+ id: v61.vcwds2
+ author: tyler
+ comment: Drop metabot_conversation.embed_url. The non-PII hostname portion has been migrated to embedding_hostname; the PII path portion is intentionally discarded.
+ changes:
+ - dropColumn:
+ tableName: metabot_conversation
+ columnName: embed_url
+ rollback:
+ - addColumn:
+ tableName: metabot_conversation
+ columns:
+ - column:
+ name: embed_url
+ type: varchar(2048)
+ remarks: Referer URL captured at conversation creation; restored on rollback. Original values are not recoverable — only the hostname survives, in embedding_hostname.
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v61.pc3opb
+ author: tyler
+ runOnChange: true
+ comment: Update v_metabot_conversations to project embedding_hostname, embedding_path, user_agent, sanitized_user_agent
+ changes:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/metabot_conversations/v2/postgres-metabot_conversations.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/metabot_conversations/v2/mysql-metabot_conversations.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/metabot_conversations/v2/h2-metabot_conversations.sql
+ relativeToChangelogFile: true
+ rollback:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/metabot_conversations/v1/postgres-metabot_conversations.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/metabot_conversations/v1/mysql-metabot_conversations.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/metabot_conversations/v1/h2-metabot_conversations.sql
+ relativeToChangelogFile: true
+
+ - changeSet:
+ id: v61.4j9n7o
+ author: tyler
+ runOnChange: true
+ comment: Update v_ai_usage_log to project embedding_hostname, embedding_path, user_agent, sanitized_user_agent
+ changes:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/ai_usage_log/v2/postgres-ai_usage_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/ai_usage_log/v2/mysql-ai_usage_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/ai_usage_log/v2/h2-ai_usage_log.sql
+ relativeToChangelogFile: true
+ rollback:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/ai_usage_log/v1/postgres-ai_usage_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/ai_usage_log/v1/mysql-ai_usage_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/ai_usage_log/v1/h2-ai_usage_log.sql
+ relativeToChangelogFile: true
diff --git a/resources/migrations/instance_analytics_views/ai_usage_log/v2/h2-ai_usage_log.sql b/resources/migrations/instance_analytics_views/ai_usage_log/v2/h2-ai_usage_log.sql
new file mode 100644
index 00000000000..3c3d5d89d89
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/ai_usage_log/v2/h2-ai_usage_log.sql
@@ -0,0 +1,47 @@
+DROP VIEW IF EXISTS v_ai_usage_log;
+
+CREATE OR REPLACE VIEW v_ai_usage_log AS
+SELECT
+ a.id AS usage_log_id,
+ a.created_at,
+ a.source,
+ CASE a.source
+ WHEN 'metabot_agent' THEN 'Metabot'
+ WHEN 'agent' THEN 'Metabot'
+ WHEN 'document_generate_content' THEN 'Documents'
+ WHEN 'example_question_generation_batch' THEN 'Suggested Prompts'
+ WHEN 'slack' THEN 'Slackbot'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'oss-sql-gen' THEN 'SQL'
+ WHEN 'sql-gen' THEN 'SQL'
+ WHEN 'unknown' THEN 'Unknown'
+ ELSE a.source
+ END AS source_name,
+ a.model,
+ a.profile_id,
+ a.prompt_tokens,
+ a.completion_tokens,
+ a.total_tokens,
+ a.conversation_id,
+ a.user_id,
+ 'user_' || a.user_id AS user_qualified_id,
+ COALESCE(u.first_name || ' ' || u.last_name, u.email) AS user_display_name,
+ (SELECT pg.name
+ FROM permissions_group_membership pgm
+ JOIN permissions_group pg ON pg.id = pgm.group_id
+ WHERE pgm.user_id = a.user_id
+ AND pg.id != 1
+ ORDER BY pg.name
+ LIMIT 1) AS group_name,
+ c.ip_address AS ip_address,
+ c.embedding_hostname AS embedding_hostname,
+ c.embedding_path AS embedding_path,
+ c.user_agent AS user_agent,
+ c.sanitized_user_agent AS sanitized_user_agent,
+ a.tenant_id,
+ a.request_id
+FROM ai_usage_log a
+LEFT JOIN core_user u
+ ON u.id = a.user_id
+LEFT JOIN metabot_conversation c
+ ON c.id = a.conversation_id;
diff --git a/resources/migrations/instance_analytics_views/ai_usage_log/v2/mysql-ai_usage_log.sql b/resources/migrations/instance_analytics_views/ai_usage_log/v2/mysql-ai_usage_log.sql
new file mode 100644
index 00000000000..71ceaf94c29
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/ai_usage_log/v2/mysql-ai_usage_log.sql
@@ -0,0 +1,47 @@
+DROP VIEW IF EXISTS v_ai_usage_log;
+
+CREATE OR REPLACE VIEW v_ai_usage_log AS
+SELECT
+ a.id AS usage_log_id,
+ a.created_at,
+ a.source,
+ CASE a.source
+ WHEN 'metabot_agent' THEN 'Metabot'
+ WHEN 'agent' THEN 'Metabot'
+ WHEN 'document_generate_content' THEN 'Documents'
+ WHEN 'example_question_generation_batch' THEN 'Suggested Prompts'
+ WHEN 'slack' THEN 'Slackbot'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'oss-sql-gen' THEN 'SQL'
+ WHEN 'sql-gen' THEN 'SQL'
+ WHEN 'unknown' THEN 'Unknown'
+ ELSE a.source
+ END AS source_name,
+ a.model,
+ a.profile_id,
+ a.prompt_tokens,
+ a.completion_tokens,
+ a.total_tokens,
+ a.conversation_id,
+ a.user_id,
+ CONCAT('user_', a.user_id) AS user_qualified_id,
+ COALESCE(CONCAT(u.first_name, ' ', u.last_name), u.email) AS user_display_name,
+ (SELECT pg.name
+ FROM permissions_group_membership pgm
+ JOIN permissions_group pg ON pg.id = pgm.group_id
+ WHERE pgm.user_id = a.user_id
+ AND pg.id != 1
+ ORDER BY pg.name
+ LIMIT 1) AS group_name,
+ c.ip_address AS ip_address,
+ c.embedding_hostname AS embedding_hostname,
+ c.embedding_path AS embedding_path,
+ c.user_agent AS user_agent,
+ c.sanitized_user_agent AS sanitized_user_agent,
+ a.tenant_id,
+ a.request_id
+FROM ai_usage_log a
+LEFT JOIN core_user u
+ ON u.id = a.user_id
+LEFT JOIN metabot_conversation c
+ ON c.id = a.conversation_id;
diff --git a/resources/migrations/instance_analytics_views/ai_usage_log/v2/postgres-ai_usage_log.sql b/resources/migrations/instance_analytics_views/ai_usage_log/v2/postgres-ai_usage_log.sql
new file mode 100644
index 00000000000..3c3d5d89d89
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/ai_usage_log/v2/postgres-ai_usage_log.sql
@@ -0,0 +1,47 @@
+DROP VIEW IF EXISTS v_ai_usage_log;
+
+CREATE OR REPLACE VIEW v_ai_usage_log AS
+SELECT
+ a.id AS usage_log_id,
+ a.created_at,
+ a.source,
+ CASE a.source
+ WHEN 'metabot_agent' THEN 'Metabot'
+ WHEN 'agent' THEN 'Metabot'
+ WHEN 'document_generate_content' THEN 'Documents'
+ WHEN 'example_question_generation_batch' THEN 'Suggested Prompts'
+ WHEN 'slack' THEN 'Slackbot'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'oss-sql-gen' THEN 'SQL'
+ WHEN 'sql-gen' THEN 'SQL'
+ WHEN 'unknown' THEN 'Unknown'
+ ELSE a.source
+ END AS source_name,
+ a.model,
+ a.profile_id,
+ a.prompt_tokens,
+ a.completion_tokens,
+ a.total_tokens,
+ a.conversation_id,
+ a.user_id,
+ 'user_' || a.user_id AS user_qualified_id,
+ COALESCE(u.first_name || ' ' || u.last_name, u.email) AS user_display_name,
+ (SELECT pg.name
+ FROM permissions_group_membership pgm
+ JOIN permissions_group pg ON pg.id = pgm.group_id
+ WHERE pgm.user_id = a.user_id
+ AND pg.id != 1
+ ORDER BY pg.name
+ LIMIT 1) AS group_name,
+ c.ip_address AS ip_address,
+ c.embedding_hostname AS embedding_hostname,
+ c.embedding_path AS embedding_path,
+ c.user_agent AS user_agent,
+ c.sanitized_user_agent AS sanitized_user_agent,
+ a.tenant_id,
+ a.request_id
+FROM ai_usage_log a
+LEFT JOIN core_user u
+ ON u.id = a.user_id
+LEFT JOIN metabot_conversation c
+ ON c.id = a.conversation_id;
diff --git a/resources/migrations/instance_analytics_views/metabot_conversations/v2/h2-metabot_conversations.sql b/resources/migrations/instance_analytics_views/metabot_conversations/v2/h2-metabot_conversations.sql
new file mode 100644
index 00000000000..4d631d6854f
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/metabot_conversations/v2/h2-metabot_conversations.sql
@@ -0,0 +1,98 @@
+DROP VIEW IF EXISTS v_metabot_conversations;
+
+CREATE OR REPLACE VIEW v_metabot_conversations AS
+SELECT
+ c.id AS conversation_id,
+ c.created_at,
+ c.user_id,
+ c.summary,
+ COALESCE(u.first_name || ' ' || u.last_name, u.email) AS user_display_name,
+ COUNT(m.id) AS message_count,
+ COUNT(CASE WHEN m.role = 'user' THEN 1 END) AS user_message_count,
+ COUNT(CASE WHEN m.role = 'assistant' THEN 1 END) AS assistant_message_count,
+ COALESCE(MAX(a.total_tokens), 0) AS total_tokens,
+ COALESCE(MAX(a.prompt_tokens), 0) AS prompt_tokens,
+ COALESCE(MAX(a.completion_tokens), 0) AS completion_tokens,
+ MAX(m.created_at) AS last_message_at,
+ (SELECT mm.profile_id
+ FROM metabot_message mm
+ WHERE mm.conversation_id = c.id
+ AND mm.role = 'assistant'
+ AND mm.deleted_at IS NULL
+ ORDER BY mm.created_at
+ LIMIT 1) AS profile_id,
+ (SELECT CASE mm.profile_id
+ WHEN 'internal' THEN 'Internal'
+ WHEN 'embedding_next' THEN 'Embedding'
+ WHEN 'nlq' THEN 'NLQ'
+ WHEN 'sql' THEN 'SQL'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'transforms_codegen' THEN 'Transforms codegen'
+ WHEN 'document-generate-content' THEN 'Documents'
+ ELSE mm.profile_id
+ END
+ FROM metabot_message mm
+ WHERE mm.conversation_id = c.id
+ AND mm.role = 'assistant'
+ AND mm.deleted_at IS NULL
+ ORDER BY mm.created_at
+ LIMIT 1) AS profile_name,
+ (SELECT pg.name
+ FROM permissions_group_membership pgm
+ JOIN permissions_group pg ON pg.id = pgm.group_id
+ WHERE pgm.user_id = c.user_id
+ AND pg.id != 1
+ ORDER BY pg.name
+ LIMIT 1) AS group_name,
+ (SELECT aul.source
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS source,
+ (SELECT CASE aul.source
+ WHEN 'metabot_agent' THEN 'Metabot'
+ WHEN 'agent' THEN 'Metabot'
+ WHEN 'document_generate_content' THEN 'Documents'
+ WHEN 'example_question_generation_batch' THEN 'Suggested Prompts'
+ WHEN 'slack' THEN 'Slackbot'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'oss-sql-gen' THEN 'SQL'
+ WHEN 'sql-gen' THEN 'SQL'
+ WHEN 'unknown' THEN 'Unknown'
+ ELSE aul.source
+ END
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS source_name,
+ c.ip_address AS ip_address,
+ c.embedding_hostname AS embedding_hostname,
+ c.embedding_path AS embedding_path,
+ c.user_agent AS user_agent,
+ c.sanitized_user_agent AS sanitized_user_agent,
+ MAX(a.tenant_id) AS tenant_id,
+ MAX(t.name) AS tenant_name,
+ (SELECT aul.model
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS model
+FROM metabot_conversation c
+LEFT JOIN core_user u
+ ON u.id = c.user_id
+LEFT JOIN metabot_message m
+ ON m.conversation_id = c.id
+ AND m.deleted_at IS NULL
+LEFT JOIN (
+ SELECT
+ conversation_id,
+ COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,
+ COALESCE(SUM(completion_tokens), 0) AS completion_tokens,
+ COALESCE(SUM(total_tokens), 0) AS total_tokens,
+ MIN(tenant_id) AS tenant_id
+ FROM ai_usage_log
+ WHERE conversation_id IS NOT NULL
+ GROUP BY conversation_id
+) a ON a.conversation_id = c.id
+LEFT JOIN tenant t ON t.id = a.tenant_id
+GROUP BY c.id, c.created_at, c.user_id, c.summary, u.first_name, u.last_name, u.email;
diff --git a/resources/migrations/instance_analytics_views/metabot_conversations/v2/mysql-metabot_conversations.sql b/resources/migrations/instance_analytics_views/metabot_conversations/v2/mysql-metabot_conversations.sql
new file mode 100644
index 00000000000..514d2f5db60
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/metabot_conversations/v2/mysql-metabot_conversations.sql
@@ -0,0 +1,98 @@
+DROP VIEW IF EXISTS v_metabot_conversations;
+
+CREATE OR REPLACE VIEW v_metabot_conversations AS
+SELECT
+ c.id AS conversation_id,
+ c.created_at,
+ c.user_id,
+ c.summary,
+ COALESCE(CONCAT(u.first_name, ' ', u.last_name), u.email) AS user_display_name,
+ COUNT(m.id) AS message_count,
+ COUNT(CASE WHEN m.role = 'user' THEN 1 END) AS user_message_count,
+ COUNT(CASE WHEN m.role = 'assistant' THEN 1 END) AS assistant_message_count,
+ COALESCE(MAX(a.total_tokens), 0) AS total_tokens,
+ COALESCE(MAX(a.prompt_tokens), 0) AS prompt_tokens,
+ COALESCE(MAX(a.completion_tokens), 0) AS completion_tokens,
+ MAX(m.created_at) AS last_message_at,
+ (SELECT mm.profile_id
+ FROM metabot_message mm
+ WHERE mm.conversation_id = c.id
+ AND mm.role = 'assistant'
+ AND mm.deleted_at IS NULL
+ ORDER BY mm.created_at
+ LIMIT 1) AS profile_id,
+ (SELECT CASE mm.profile_id
+ WHEN 'internal' THEN 'Internal'
+ WHEN 'embedding_next' THEN 'Embedding'
+ WHEN 'nlq' THEN 'NLQ'
+ WHEN 'sql' THEN 'SQL'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'transforms_codegen' THEN 'Transforms codegen'
+ WHEN 'document-generate-content' THEN 'Documents'
+ ELSE mm.profile_id
+ END
+ FROM metabot_message mm
+ WHERE mm.conversation_id = c.id
+ AND mm.role = 'assistant'
+ AND mm.deleted_at IS NULL
+ ORDER BY mm.created_at
+ LIMIT 1) AS profile_name,
+ (SELECT pg.name
+ FROM permissions_group_membership pgm
+ JOIN permissions_group pg ON pg.id = pgm.group_id
+ WHERE pgm.user_id = c.user_id
+ AND pg.id != 1
+ ORDER BY pg.name
+ LIMIT 1) AS group_name,
+ (SELECT aul.source
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS source,
+ (SELECT CASE aul.source
+ WHEN 'metabot_agent' THEN 'Metabot'
+ WHEN 'agent' THEN 'Metabot'
+ WHEN 'document_generate_content' THEN 'Documents'
+ WHEN 'example_question_generation_batch' THEN 'Suggested Prompts'
+ WHEN 'slack' THEN 'Slackbot'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'oss-sql-gen' THEN 'SQL'
+ WHEN 'sql-gen' THEN 'SQL'
+ WHEN 'unknown' THEN 'Unknown'
+ ELSE aul.source
+ END
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS source_name,
+ c.ip_address AS ip_address,
+ c.embedding_hostname AS embedding_hostname,
+ c.embedding_path AS embedding_path,
+ c.user_agent AS user_agent,
+ c.sanitized_user_agent AS sanitized_user_agent,
+ MAX(a.tenant_id) AS tenant_id,
+ MAX(t.name) AS tenant_name,
+ (SELECT aul.model
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS model
+FROM metabot_conversation c
+LEFT JOIN core_user u
+ ON u.id = c.user_id
+LEFT JOIN metabot_message m
+ ON m.conversation_id = c.id
+ AND m.deleted_at IS NULL
+LEFT JOIN (
+ SELECT
+ conversation_id,
+ COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,
+ COALESCE(SUM(completion_tokens), 0) AS completion_tokens,
+ COALESCE(SUM(total_tokens), 0) AS total_tokens,
+ MIN(tenant_id) AS tenant_id
+ FROM ai_usage_log
+ WHERE conversation_id IS NOT NULL
+ GROUP BY conversation_id
+) a ON a.conversation_id = c.id
+LEFT JOIN tenant t ON t.id = a.tenant_id
+GROUP BY c.id, c.created_at, c.user_id, c.summary, u.first_name, u.last_name, u.email;
diff --git a/resources/migrations/instance_analytics_views/metabot_conversations/v2/postgres-metabot_conversations.sql b/resources/migrations/instance_analytics_views/metabot_conversations/v2/postgres-metabot_conversations.sql
new file mode 100644
index 00000000000..577db76458a
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/metabot_conversations/v2/postgres-metabot_conversations.sql
@@ -0,0 +1,98 @@
+DROP VIEW IF EXISTS v_metabot_conversations;
+
+CREATE OR REPLACE VIEW v_metabot_conversations AS
+SELECT
+ c.id AS conversation_id,
+ c.created_at,
+ c.user_id,
+ c.summary,
+ COALESCE(u.first_name || ' ' || u.last_name, u.email) AS user_display_name,
+ COUNT(m.id) AS message_count,
+ COUNT(CASE WHEN m.role = 'user' THEN 1 END) AS user_message_count,
+ COUNT(CASE WHEN m.role = 'assistant' THEN 1 END) AS assistant_message_count,
+ COALESCE(MAX(a.total_tokens), 0) AS total_tokens,
+ COALESCE(MAX(a.prompt_tokens), 0) AS prompt_tokens,
+ COALESCE(MAX(a.completion_tokens), 0) AS completion_tokens,
+ MAX(m.created_at) AS last_message_at,
+ (SELECT mm.profile_id
+ FROM metabot_message mm
+ WHERE mm.conversation_id = c.id
+ AND mm.role = 'assistant'
+ AND mm.deleted_at IS NULL
+ ORDER BY mm.created_at
+ LIMIT 1) AS profile_id,
+ (SELECT CASE mm.profile_id
+ WHEN 'internal' THEN 'Internal'
+ WHEN 'embedding_next' THEN 'Embedding'
+ WHEN 'nlq' THEN 'NLQ'
+ WHEN 'sql' THEN 'SQL'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'transforms_codegen' THEN 'Transforms codegen'
+ WHEN 'document-generate-content' THEN 'Documents'
+ ELSE mm.profile_id
+ END
+ FROM metabot_message mm
+ WHERE mm.conversation_id = c.id
+ AND mm.role = 'assistant'
+ AND mm.deleted_at IS NULL
+ ORDER BY mm.created_at
+ LIMIT 1) AS profile_name,
+ (SELECT pg.name
+ FROM permissions_group_membership pgm
+ JOIN permissions_group pg ON pg.id = pgm.group_id
+ WHERE pgm.user_id = c.user_id
+ AND pg.id != 1
+ ORDER BY pg.name
+ LIMIT 1) AS group_name,
+ (SELECT aul.source
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS source,
+ (SELECT CASE aul.source
+ WHEN 'metabot_agent' THEN 'Metabot'
+ WHEN 'agent' THEN 'Metabot'
+ WHEN 'document_generate_content' THEN 'Documents'
+ WHEN 'example_question_generation_batch' THEN 'Suggested Prompts'
+ WHEN 'slack' THEN 'Slackbot'
+ WHEN 'slackbot' THEN 'Slackbot'
+ WHEN 'oss-sql-gen' THEN 'SQL'
+ WHEN 'sql-gen' THEN 'SQL'
+ WHEN 'unknown' THEN 'Unknown'
+ ELSE aul.source
+ END
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS source_name,
+ c.ip_address AS ip_address,
+ c.embedding_hostname AS embedding_hostname,
+ c.embedding_path AS embedding_path,
+ c.user_agent AS user_agent,
+ c.sanitized_user_agent AS sanitized_user_agent,
+ MAX(a.tenant_id) AS tenant_id,
+ MAX(t.name) AS tenant_name,
+ (SELECT aul.model
+ FROM ai_usage_log aul
+ WHERE aul.conversation_id = c.id
+ ORDER BY aul.created_at
+ LIMIT 1) AS model
+FROM metabot_conversation c
+LEFT JOIN core_user u
+ ON u.id = c.user_id
+LEFT JOIN metabot_message m
+ ON m.conversation_id = c.id
+ AND m.deleted_at IS NULL
+LEFT JOIN (
+ SELECT
+ conversation_id,
+ COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,
+ COALESCE(SUM(completion_tokens), 0) AS completion_tokens,
+ COALESCE(SUM(total_tokens), 0) AS total_tokens,
+ MIN(tenant_id) AS tenant_id
+ FROM ai_usage_log
+ WHERE conversation_id IS NOT NULL
+ GROUP BY conversation_id
+) a ON a.conversation_id = c.id
+LEFT JOIN tenant t ON t.id = a.tenant_id
+GROUP BY c.id, c.created_at, c.user_id, c.summary, u.first_name, u.last_name, u.email;
diff --git a/src/metabase/analytics/core.clj b/src/metabase/analytics/core.clj
index e9c3cf55afb..05f118644eb 100644
--- a/src/metabase/analytics/core.clj
+++ b/src/metabase/analytics/core.clj
@@ -52,6 +52,7 @@
extract-hostname
extract-path
include-sdk-info
+ pii-fields-from
pii-request-info
with-auth-method! get-auth-method
with-client! get-client
diff --git a/src/metabase/analytics/sdk.clj b/src/metabase/analytics/sdk.clj
index bf5a823e568..bd1eb6cdb92 100644
--- a/src/metabase/analytics/sdk.clj
+++ b/src/metabase/analytics/sdk.clj
@@ -86,6 +86,16 @@
:sanitized_user_agent (request.user-agent/describe-user-agent user-agent)
:ip_address ip-address})
+(defn pii-fields-from
+ "Like the request-bound `pii-fields` but takes an explicit info map (for callers
+ that have already extracted request fields on-thread, e.g. before async hand-off).
+ Returns the PII map when `analytics-pii-retention-enabled` is true, else nil.
+ Callers that always want the ungated `embedding_hostname` should compute it
+ separately via `extract-hostname` and not read it off the returned map."
+ [info]
+ (when (analytics.settings/analytics-pii-retention-enabled)
+ (pii-request-info info)))
+
(defn- hostname-fields
"Returns embedding_hostname from the current request. Always collected (not PII)."
[]
diff --git a/src/metabase/analytics/settings.clj b/src/metabase/analytics/settings.clj
index f25bacf9e07..4b0a0d7a84a 100644
--- a/src/metabase/analytics/settings.clj
+++ b/src/metabase/analytics/settings.clj
@@ -92,8 +92,9 @@
:setter #'-non-table-chart-generated!)
(defsetting analytics-pii-retention-enabled
- (deferred-tru (str "Enable logging of embed path, query parameters, user agent, and IP address of who views your "
- "internal data and embeds. This information will be shown in your usage analytics."))
+ (deferred-tru (str "Enable logging of embed path, query parameters, user agent, IP address, and Metabot "
+ "conversation metadata for users of your internal data and embeds. This information "
+ "will be shown in your usage analytics."))
:type :boolean
:default false
:visibility :admin
diff --git a/src/metabase/app_db/custom_migrations.clj b/src/metabase/app_db/custom_migrations.clj
index b71c1bfdf67..622b672f9f8 100644
--- a/src/metabase/app_db/custom_migrations.clj
+++ b/src/metabase/app_db/custom_migrations.clj
@@ -2194,3 +2194,22 @@
:where [:and
[:not= :target_db_id nil]
[:= :target_table_id nil]]})))
+
+(define-migration BackfillMetabotConversationEmbeddingHostname
+ ;; Carry over the hostname portion of metabot_conversation.embed_url into the
+ ;; new embedding_hostname column. Only the hostname is migrated — the path
+ ;; portion of pre-flag embed_url values has no consent basis under
+ ;; analytics-pii-retention-enabled and is intentionally discarded.
+ (run! (fn [{:keys [id embed_url]}]
+ (let [^java.net.URI parsed (try (java.net.URI. ^String embed_url) (catch Exception _ nil))
+ host (some-> parsed .getHost not-empty)
+ host* (when host (subs host 0 (min (count host) 512)))]
+ (when host*
+ (t2/query {:update :metabot_conversation
+ :set {:embedding_hostname host*}
+ :where [:= :id id]}))))
+ (t2/reducible-query {:select [:id :embed_url]
+ :from [:metabot_conversation]
+ :where [:and
+ [:not= :embed_url nil]
+ [:= :embedding_hostname nil]]})))
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index f8892c35113..9611cabe542 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -4,6 +4,7 @@
[clojure.core.async :as a]
[clojure.string :as str]
[medley.core :as m]
+ [metabase.analytics.core :as analytics.core]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
@@ -55,8 +56,12 @@
(api/check-403 (mi/can-read? conversation))))
(defn- store-aiservice-messages!
- "Store messages that are going from ai-service"
- [conversation-id profile-id ip-address embed-url messages]
+ "Store messages that are going from ai-service.
+
+ `hostname` is the always-on `embedding_hostname`; `pii-info` is the gated map
+ returned by `analytics.core/pii-fields-from` (nil when the retention flag is
+ off). Both apply only on first insert per conversation (first-writer-wins)."
+ [conversation-id profile-id hostname pii-info messages]
(let [finish (let [m (u/last messages)]
(when (= (:_type m) :FINISH_MESSAGE)
m))
@@ -69,10 +74,26 @@
(app-db/update-or-insert! :model/MetabotConversation {:id conversation-id}
(fn [existing]
(cond-> {}
- (nil? existing) (assoc :user_id api/*current-user-id*)
- state (assoc :state state)
- (nil? (:ip_address existing)) (assoc :ip_address ip-address)
- (nil? (:embed_url existing)) (assoc :embed_url embed-url))))
+ (nil? existing)
+ (assoc :user_id api/*current-user-id*)
+
+ state
+ (assoc :state state)
+
+ (and hostname (nil? (:embedding_hostname existing)))
+ (assoc :embedding_hostname hostname)
+
+ (and (:embedding_path pii-info) (nil? (:embedding_path existing)))
+ (assoc :embedding_path (:embedding_path pii-info))
+
+ (and (:user_agent pii-info) (nil? (:user_agent existing)))
+ (assoc :user_agent (:user_agent pii-info))
+
+ (and (:sanitized_user_agent pii-info) (nil? (:sanitized_user_agent existing)))
+ (assoc :sanitized_user_agent (:sanitized_user_agent pii-info))
+
+ (and (:ip_address pii-info) (nil? (:ip_address existing)))
+ (assoc :ip_address (:ip_address pii-info)))))
;; NOTE: this will need to be constrained at some point, see BOT-386
(t2/insert! :model/MetabotMessage
{:conversation_id conversation-id
@@ -123,7 +144,7 @@
When `:debug?` is true, enables debug logging which emits a `debug_log` data
part at the end of the stream with full LLM request/response data per iteration."
- [{:keys [metabot-id profile-id message context history conversation-id state debug? ip-address embed-url]}]
+ [{:keys [metabot-id profile-id message context history conversation-id state debug? hostname pii-info]}]
(let [enriched-context (metabot.context/create-context context {:metabot-id metabot-id})
messages (concat history [message])
external-id (str (random-uuid))]
@@ -151,8 +172,8 @@
(metabot.persistence/store-native-parts!
conversation-id profile-id
(into [] (metabot.persistence/combine-text-parts-xf) @parts-atom)
- :ip-address ip-address
- :embed-url embed-url
+ :hostname hostname
+ :pii-info pii-info
:external-id external-id)
(catch Exception e
(log/error e "Failed to persist native agent parts"
@@ -160,17 +181,24 @@
:external-id external-id})))))))))
(defn streaming-request
- "Handles an incoming request, making all required tool invocation, LLM call loops, etc."
- [{:keys [metabot_id profile_id message context history conversation_id state debug]} ip-address embed-url]
+ "Handles an incoming request, making all required tool invocation, LLM call loops, etc.
+
+ `request-info` is a map of `{:origin :referer :user-agent :ip-address}`. We split
+ it into:
+ - `hostname`: extracted from the origin URL, always recorded.
+ - `pii-info`: gated by `analytics-pii-retention-enabled` — nil when off."
+ [{:keys [metabot_id profile_id message context history conversation_id state debug]} request-info]
(let [message (metabot.envelope/user-message message)
metabot-id (metabot.config/resolve-dynamic-metabot-id metabot_id)
_ (metabot.config/check-metabot-enabled! metabot-id)
_ (metabot.usage/check-metabase-managed-free-limit!)
profile-id (metabot.config/resolve-dynamic-profile-id profile_id metabot-id)
;; Only allow debug mode in dev — never in production
- debug? (and config/is-dev? (boolean debug))]
+ debug? (and config/is-dev? (boolean debug))
+ hostname (analytics.core/extract-hostname (:origin request-info))
+ pii-info (analytics.core/pii-fields-from request-info)]
(check-conversation-access! conversation_id)
- (store-aiservice-messages! conversation_id profile-id ip-address embed-url [message])
+ (store-aiservice-messages! conversation_id profile-id hostname pii-info [message])
(log/info "Using native Clojure agent" {:profile-id profile-id :debug? debug?})
(native-agent-streaming-request
@@ -182,8 +210,8 @@
:conversation-id conversation_id
:state state
:debug? debug?
- :ip-address ip-address
- :embed-url embed-url})))
+ :hostname hostname
+ :pii-info pii-info})))
(defn- legacy->modern-query
[query]
@@ -229,8 +257,13 @@
[:debug {:optional true} [:maybe :boolean]]]
req]
(metabot.context/log body :llm.log/fe->be)
- (let [body* (m/update-existing body [:context :user_is_viewing] upgrade-viewing-queries)]
- (streaming-request body* (request/ip-address req) (request/referer req))))
+ (let [body* (m/update-existing body [:context :user_is_viewing] upgrade-viewing-queries)
+ embed-referrer (get-in req [:headers "x-metabase-embed-referrer"])
+ request-info {:origin embed-referrer
+ :referer embed-referrer
+ :user-agent (get-in req [:headers "user-agent"])
+ :ip-address (request/ip-address req)}]
+ (streaming-request body* request-info)))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/src/metabase/metabot/persistence.clj b/src/metabase/metabot/persistence.clj
index 10f168a0bd0..425b58f6d52 100644
--- a/src/metabase/metabot/persistence.clj
+++ b/src/metabase/metabot/persistence.clj
@@ -89,7 +89,11 @@
Positional args: `conversation-id`, `profile-id`, `parts`.
Keyword args:
- - `:ip-address`, `:embed-url` — recorded on the conversation row on first insert only.
+ - `:hostname` — always-on `embedding_hostname`; recorded on first insert only.
+ - `:pii-info` — gated PII map (`analytics.core/pii-fields-from`'s shape: keys
+ `:embedding_path`, `:user_agent`, `:sanitized_user_agent`, `:ip_address`).
+ Nil when the retention flag is off; individual keys recorded on first
+ insert only. Slack persistence never passes this — slack rows stay NULL.
- `:slack-msg-id`, `:channel-id`, `:slack-team-id`, `:slack-thread-ts` — slack
metadata. `:slack-team-id`/`:channel-id`/`:slack-thread-ts` land on the
conversation row on first insert only; `:slack-msg-id`/`:channel-id` land on
@@ -101,7 +105,7 @@
Returns the inserted `MetabotMessage` primary key."
[conversation-id profile-id parts
- & {:keys [ip-address embed-url external-id
+ & {:keys [hostname pii-info external-id
slack-msg-id channel-id slack-team-id slack-thread-ts
user-id ai-proxy?]}]
(let [state-part (u/seek #(and (= :data (:type %))
@@ -135,10 +139,16 @@
(assoc :user_id api/*current-user-id*)
state-part
(assoc :state (:data state-part))
- (and ip-address (nil? (:ip_address existing)))
- (assoc :ip_address ip-address)
- (and embed-url (nil? (:embed_url existing)))
- (assoc :embed_url embed-url)
+ (and hostname (nil? (:embedding_hostname existing)))
+ (assoc :embedding_hostname hostname)
+ (and (:embedding_path pii-info) (nil? (:embedding_path existing)))
+ (assoc :embedding_path (:embedding_path pii-info))
+ (and (:user_agent pii-info) (nil? (:user_agent existing)))
+ (assoc :user_agent (:user_agent pii-info))
+ (and (:sanitized_user_agent pii-info) (nil? (:sanitized_user_agent existing)))
+ (assoc :sanitized_user_agent (:sanitized_user_agent pii-info))
+ (and (:ip_address pii-info) (nil? (:ip_address existing)))
+ (assoc :ip_address (:ip_address pii-info))
(and slack-team-id (nil? (:slack_team_id existing)))
(assoc :slack_team_id slack-team-id)
(and channel-id (nil? (:slack_channel_id existing)))
diff --git a/src/metabase/metabot/repl.clj b/src/metabase/metabot/repl.clj
index e1c5a381d0c..427317ad8b1 100644
--- a/src/metabase/metabot/repl.clj
+++ b/src/metabase/metabot/repl.clj
@@ -64,7 +64,6 @@
:history history
:conversation_id conversation-id
:state state}
- nil
nil)
consume-streaming-response
str/split-lines
diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.clj
index 1776c43c1d2..b2106192781 100644
--- a/test/metabase/metabot/api_test.clj
+++ b/test/metabase/metabot/api_test.clj
@@ -886,8 +886,7 @@
:conversation_id (str (random-uuid))
:state {}
:debug false}
- nil
- nil)
+ {:origin nil :referer nil :user-agent nil :ip-address nil})
(testing "metabot-id is included in the arguments"
(is (some? (:metabot-id @captured-args))
"metabot-id should not be nil")
@@ -907,57 +906,85 @@
:state {}
:debug false})
ip-for (fn [conversation-id]
- (:ip_address (t2/select-one :model/MetabotConversation :id conversation-id)))]
+ (:ip_address (t2/select-one :model/MetabotConversation :id conversation-id)))
+ info-with-ip (fn [ip] {:origin nil :referer nil :user-agent nil :ip-address ip})]
(with-redefs [metabot.config/check-metabot-enabled! (constantly nil)
api/native-agent-streaming-request (constantly nil)]
(mt/with-test-user :rasta
- (testing "first writer wins: initial call captures the IP, later calls do not overwrite it"
- (let [conversation-id (str (random-uuid))]
- (api/streaming-request (request-body conversation-id) "1.2.3.4" nil)
- (is (= "1.2.3.4" (ip-for conversation-id)))
- (api/streaming-request (request-body conversation-id) "5.6.7.8" nil)
- (is (= "1.2.3.4" (ip-for conversation-id)))))
- (testing "null IP on pre-feature rows is backfilled on next call"
- (let [conversation-id (str (random-uuid))]
- (t2/insert! :model/MetabotConversation {:id conversation-id :user_id (mt/user->id :rasta)})
- (api/streaming-request (request-body conversation-id) "9.9.9.9" nil)
- (is (= "9.9.9.9" (ip-for conversation-id))))))))))
-
-(deftest streaming-request-embed-url-test
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]
+ (testing "first writer wins: initial call captures the IP, later calls do not overwrite it"
+ (let [conversation-id (str (random-uuid))]
+ (api/streaming-request (request-body conversation-id) (info-with-ip "1.2.3.4"))
+ (is (= "1.2.3.4" (ip-for conversation-id)))
+ (api/streaming-request (request-body conversation-id) (info-with-ip "5.6.7.8"))
+ (is (= "1.2.3.4" (ip-for conversation-id)))))
+ (testing "null IP on pre-feature rows is backfilled on next call"
+ (let [conversation-id (str (random-uuid))]
+ (t2/insert! :model/MetabotConversation {:id conversation-id :user_id (mt/user->id :rasta)})
+ (api/streaming-request (request-body conversation-id) (info-with-ip "9.9.9.9"))
+ (is (= "9.9.9.9" (ip-for conversation-id))))))
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled false]
+ (testing "ip_address is NOT recorded when analytics-pii-retention-enabled is off"
+ (let [conversation-id (str (random-uuid))]
+ (api/streaming-request (request-body conversation-id) (info-with-ip "1.2.3.4"))
+ (is (nil? (ip-for conversation-id)))))))))))
+
+(deftest streaming-request-embedding-fields-test
(mt/with-model-cleanup [:model/MetabotMessage
[:model/MetabotConversation :created_at]]
- (let [request-body (fn [conversation-id]
- {:metabot_id metabot.config/embedded-metabot-id
- :profile_id nil
- :message "hi"
- :context {}
- :history []
- :conversation_id conversation-id
- :state {}
- :debug false})
- embed-url-for (fn [conversation-id]
- (:embed_url (t2/select-one :model/MetabotConversation :id conversation-id)))]
+ (let [request-body (fn [conversation-id]
+ {:metabot_id metabot.config/embedded-metabot-id
+ :profile_id nil
+ :message "hi"
+ :context {}
+ :history []
+ :conversation_id conversation-id
+ :state {}
+ :debug false})
+ info-with (fn [embed-referrer]
+ {:origin embed-referrer
+ :referer embed-referrer
+ :user-agent nil
+ :ip-address nil})
+ convo-for (fn [conversation-id]
+ (t2/select-one :model/MetabotConversation :id conversation-id))]
(with-redefs [metabot.config/check-metabot-enabled! (constantly nil)
api/native-agent-streaming-request (constantly nil)]
(mt/with-test-user :rasta
- (testing "first writer wins: initial call captures the Referer, later calls do not overwrite it"
- (let [conversation-id (str (random-uuid))]
- (api/streaming-request (request-body conversation-id) nil "https://host.example.com/page")
- (is (= "https://host.example.com/page" (embed-url-for conversation-id)))
- (api/streaming-request (request-body conversation-id) nil "https://other.example.com/other")
- (is (= "https://host.example.com/page" (embed-url-for conversation-id)))))
- (testing "null embed_url on pre-feature rows is backfilled on next call"
- (let [conversation-id (str (random-uuid))]
- (t2/insert! :model/MetabotConversation {:id conversation-id :user_id (mt/user->id :rasta)})
- (api/streaming-request (request-body conversation-id) nil "https://host.example.com/backfilled")
- (is (= "https://host.example.com/backfilled" (embed-url-for conversation-id)))))
- (testing "missing Referer leaves embed_url null"
- (let [conversation-id (str (random-uuid))]
- (api/streaming-request (request-body conversation-id) nil nil)
- (is (nil? (embed-url-for conversation-id))))))))))
-
-(deftest agent-streaming-endpoint-captures-referer-test
- (testing "POST /metabot/agent-streaming captures the Referer header as embed_url"
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]
+ (testing "flag on: hostname AND path are recorded"
+ (let [conversation-id (str (random-uuid))]
+ (api/streaming-request (request-body conversation-id)
+ (info-with "https://customer.example.com/dashboard"))
+ (let [convo (convo-for conversation-id)]
+ (is (= "customer.example.com" (:embedding_hostname convo)))
+ (is (= "/dashboard" (:embedding_path convo))))))
+ (testing "first writer wins: hostname is not overwritten on later calls"
+ (let [conversation-id (str (random-uuid))]
+ (api/streaming-request (request-body conversation-id)
+ (info-with "https://host.example.com/page"))
+ (api/streaming-request (request-body conversation-id)
+ (info-with "https://other.example.com/other"))
+ (let [convo (convo-for conversation-id)]
+ (is (= "host.example.com" (:embedding_hostname convo)))
+ (is (= "/page" (:embedding_path convo))))))
+ (testing "missing embed referrer leaves both columns null"
+ (let [conversation-id (str (random-uuid))]
+ (api/streaming-request (request-body conversation-id) (info-with nil))
+ (let [convo (convo-for conversation-id)]
+ (is (nil? (:embedding_hostname convo)))
+ (is (nil? (:embedding_path convo)))))))
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled false]
+ (testing "flag off: hostname IS still recorded (ungated), path is NOT"
+ (let [conversation-id (str (random-uuid))]
+ (api/streaming-request (request-body conversation-id)
+ (info-with "https://customer.example.com/dashboard"))
+ (let [convo (convo-for conversation-id)]
+ (is (= "customer.example.com" (:embedding_hostname convo)))
+ (is (nil? (:embedding_path convo))))))))))))
+
+(deftest agent-streaming-endpoint-captures-embed-referrer-test
+ (testing "POST /metabot/agent-streaming captures x-metabase-embed-referrer as embedding_hostname/embedding_path"
(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider test-provider]
(binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
(with-redefs [openrouter/openrouter (fn [_]
@@ -968,17 +995,72 @@
:model "test-model" :id "msg-1"}]))]
(mt/with-model-cleanup [:model/MetabotMessage
[:model/MetabotConversation :created_at]]
- (let [conversation-id (str (random-uuid))
- referer "https://customer.example.com/dashboard"]
- (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
- {:request-options {:headers {"referer" referer}}}
- {:message "hello"
- :context {}
- :conversation_id conversation-id
- :history []
- :state {}})
- (is (= referer
- (:embed_url (t2/select-one :model/MetabotConversation :id conversation-id)))))))))))
+ (testing "flag on: hostname AND path are recorded"
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]
+ (let [conversation-id (str (random-uuid))
+ embed-referrer "https://customer.example.com/dashboard"]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:request-options {:headers {"x-metabase-embed-referrer" embed-referrer}}}
+ {:message "hello"
+ :context {}
+ :conversation_id conversation-id
+ :history []
+ :state {}})
+ (let [convo (t2/select-one :model/MetabotConversation :id conversation-id)]
+ (is (= "customer.example.com" (:embedding_hostname convo)))
+ (is (= "/dashboard" (:embedding_path convo)))))))
+ (testing "flag off: hostname recorded (ungated), path NOT recorded"
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled false]
+ (let [conversation-id (str (random-uuid))
+ embed-referrer "https://customer.example.com/dashboard"]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:request-options {:headers {"x-metabase-embed-referrer" embed-referrer}}}
+ {:message "hello"
+ :context {}
+ :conversation_id conversation-id
+ :history []
+ :state {}})
+ (let [convo (t2/select-one :model/MetabotConversation :id conversation-id)]
+ (is (= "customer.example.com" (:embedding_hostname convo)))
+ (is (nil? (:embedding_path convo)))))))
+ (testing "standard Referer header (no x-metabase-embed-referrer) leaves both columns null"
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]
+ (let [conversation-id (str (random-uuid))]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:request-options {:headers {"referer" "https://customer.example.com/dashboard"}}}
+ {:message "hello"
+ :context {}
+ :conversation_id conversation-id
+ :history []
+ :state {}})
+ (let [convo (t2/select-one :model/MetabotConversation :id conversation-id)]
+ (is (nil? (:embedding_hostname convo)))
+ (is (nil? (:embedding_path convo)))))))
+ (testing "user-agent recorded only when flag is on"
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled true]
+ (let [conversation-id (str (random-uuid))]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:request-options {:headers {"user-agent" "Mozilla/5.0 (TestAgent)"}}}
+ {:message "hello"
+ :context {}
+ :conversation_id conversation-id
+ :history []
+ :state {}})
+ (let [convo (t2/select-one :model/MetabotConversation :id conversation-id)]
+ (is (= "Mozilla/5.0 (TestAgent)" (:user_agent convo)))
+ (is (some? (:sanitized_user_agent convo))))))
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled false]
+ (let [conversation-id (str (random-uuid))]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:request-options {:headers {"user-agent" "Mozilla/5.0 (TestAgent)"}}}
+ {:message "hello"
+ :context {}
+ :conversation_id conversation-id
+ :history []
+ :state {}})
+ (let [convo (t2/select-one :model/MetabotConversation :id conversation-id)]
+ (is (nil? (:user_agent convo)))
+ (is (nil? (:sanitized_user_agent convo)))))))))))))
(deftest agent-streaming-returns-free-trial-limit-error-when-managed-provider-is-locked-test
(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider
diff --git a/test/metabase/slackbot/streaming_test.clj b/test/metabase/slackbot/streaming_test.clj
index 985bd430e13..4759b6bc44e 100644
--- a/test/metabase/slackbot/streaming_test.clj
+++ b/test/metabase/slackbot/streaming_test.clj
@@ -231,6 +231,32 @@
(is (not= ::timeout opts))
(is (some? (:slack-msg-id opts))))))))))))
+(deftest slackbot-streaming-never-writes-pii-columns-test
+ (testing "Slack-originated rows leave ip_address/embedding_*/user_agent NULL regardless of analytics-pii-retention-enabled"
+ (tu/with-slackbot-setup
+ (let [event-body tu/base-dm-event]
+ (doseq [flag-on? [true false]]
+ (testing (str "with analytics-pii-retention-enabled=" flag-on?)
+ (let [store-opts (atom [])]
+ (tu/with-slackbot-mocks
+ {:ai-text "Hello!"}
+ (fn [{:keys [stop-stream-calls]}]
+ (mt/with-temporary-setting-values [analytics-pii-retention-enabled flag-on?]
+ (with-redefs [metabot.persistence/store-native-parts!
+ (fn [_conv-id _profile-id _parts & {:as opts}]
+ (swap! store-opts conj opts)
+ nil)]
+ (mt/client :post 200 "metabot/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})))
+ (testing "store-native-parts! never received :hostname or :pii-info from the slackbot path"
+ (doseq [opts @store-opts]
+ (is (not (contains? opts :hostname)))
+ (is (not (contains? opts :pii-info))))))))))))))
+
(deftest slackbot-streaming-sets-ai-proxied-false-for-byok-test
(testing "user + assistant persists receive ai-proxy? = false for direct BYOK provider"
(tu/with-slackbot-setup