diff --git a/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx b/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx index 1fd01844101..5fecb8b47e6 100644 --- a/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx +++ b/apps/docs/content/docs/platform/self-hosting/background-jobs.mdx @@ -182,7 +182,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa | Table row TTL cleanup | `/api/cron/cleanup-table-row-ttl` | `*/15 * * * *` | Deletes table rows whose TTL column has expired | | Stale execution cleanup | `/api/cron/cleanup-stale-executions` | `*/30 * * * *` | Fails runs whose worker died without finishing — workflow executions, background jobs, table jobs and table runs — so they stop showing as running | | OAuth token cleanup | `/api/cron/cleanup-oauth-tokens` | `0 * * * *` | Deletes access and refresh tokens after the retention tail | -| Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity after 400 days, Search MCP call metadata after 270 days | +| Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity and Search MCP call metadata after 400 days | | Workspace source staging cleanup | `/api/cron/cleanup-source-staging` | `30 * * * *` | Deletes binary files staged for a workspace source apply a day after they were last staged | | SCIM reconciliation | `/api/cron/scim-reconcile` | `17 * * * *` | Re-applies directory group mappings | | Data drains | `/api/cron/run-data-drains` | `0 * * * *` | Enterprise data drains | diff --git a/apps/sim/app/api/organizations/[id]/usage/adoption/export/route.integration.ts b/apps/sim/app/api/organizations/[id]/usage/adoption/export/route.integration.ts new file mode 100644 index 00000000000..f77e64c96a8 --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/usage/adoption/export/route.integration.ts @@ -0,0 +1,76 @@ +/** + * The adoption CSV export's authorization against real PostgreSQL and Redis: every member's + * activity is for organization admins and owners only, so a member is refused before any read + * while an admin gets one row per member. + */ +import { db } from '@sim/db' +import { member, organization, user } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { NextRequest } from 'next/server' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' + +vi.hoisted(() => vi.stubEnv('USAGE_MONITORING_ENABLED', 'true')) +const sessionUser = vi.hoisted(() => ({ id: '' })) +vi.mock('@/lib/auth', async (importOriginal) => ({ + ...(await importOriginal()), + getSession: async () => ({ user: { id: sessionUser.id }, session: { id: 'session-fixture' } }), +})) + +import { GET } from '@/app/api/organizations/[id]/usage/adoption/export/route' + +const organizationId = generateId() +const memberUserId = generateId() +const adminUserId = generateId() +const users = [memberUserId, adminUserId] + +function exportAs(userId: string) { + sessionUser.id = userId + return GET( + new NextRequest( + `http://localhost:3000/api/organizations/${organizationId}/usage/adoption/export?preset=30d` + ), + { params: Promise.resolve({ id: organizationId }) } + ) +} + +describe('adoption export', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + users.map((id) => ({ + id, + name: 'Export fixture', + email: `${id}@adoption-export.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db + .insert(organization) + .values({ id: organizationId, name: 'Export fixture', slug: `export-${organizationId}` }) + await db.insert(member).values([ + { id: generateId(), userId: memberUserId, organizationId, role: 'member' }, + { id: generateId(), userId: adminUserId, organizationId, role: 'admin' }, + ]) + }) + + afterAll(async () => { + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(inArray(user.id, users)) + }) + + it('refuses a member who is not an admin or owner', async () => { + const response = await exportAs(memberUserId) + expect(response.status).toBe(403) + expect(response.headers.get('Content-Type')).not.toContain('text/csv') + }) + + it('exports every member for an admin', async () => { + const response = await exportAs(adminUserId) + expect(response.status).toBe(200) + expect(response.headers.get('Content-Type')).toContain('text/csv') + expect((await response.text()).split('\n')).toHaveLength(3) + }) +}) diff --git a/apps/sim/app/api/v2/chat/route.ts b/apps/sim/app/api/v2/chat/route.ts index a3036694426..d473fe1a609 100644 --- a/apps/sim/app/api/v2/chat/route.ts +++ b/apps/sim/app/api/v2/chat/route.ts @@ -50,6 +50,7 @@ import { runHeadlessCopilotLifecycle } from '@/lib/mothership/request/lifecycle/ import { requestExplicitStreamAbort } from '@/lib/mothership/request/session/explicit-abort' import type { OrchestratorResult, StreamEvent } from '@/lib/mothership/request/types' import { normalizeSecretMountPolicy } from '@/lib/mothership/secret-mount-policy' +import { recordMemberActivity } from '@/lib/organizations/member-activity/record' import { CAPABILITY_RULES } from '@/lib/permission-groups/capabilities' import { capabilityRefusal, @@ -383,6 +384,8 @@ export const POST = withRouteHandler( req.signal.addEventListener('abort', onAbort, { once: true }) } + // Admitted and billed: the route takes only a person's own credential, so the turn is theirs. + recordMemberActivity({ userId, surface: 'agent', scope: { kind: 'workspace', workspaceId } }) const runLifecycle = (onEvent?: (event: StreamEvent) => Promise) => runHeadlessCopilotLifecycle(requestPayload, { userId, diff --git a/apps/sim/lib/billing/core/organization-adoption.integration.ts b/apps/sim/lib/billing/core/organization-adoption.integration.ts index d92f7f0e2aa..f355a2d642b 100644 --- a/apps/sim/lib/billing/core/organization-adoption.integration.ts +++ b/apps/sim/lib/billing/core/organization-adoption.integration.ts @@ -170,6 +170,71 @@ describe('organization adoption', () => { ).toBe(true) }) + it('reads a window starting tomorrow as empty, with headlines ending today', () => { + const now = new Date('2026-11-28T15:00:00Z') + const tomorrow = adoptionDays( + organizationId, + { start: new Date('2026-11-29T00:00:00Z'), end: new Date('2026-11-30T00:00:00Z') }, + now + ) + expect([tomorrow.from, tomorrow.to, tomorrow.asOf]).toEqual([ + '2026-11-29', + '2026-11-29', + '2026-11-29', + ]) + }) + + it('keeps the day a short window inside one UTC day falls on', () => { + const short = adoptionDays( + organizationId, + { start: new Date('2026-11-10T00:30:00Z'), end: new Date('2026-11-10T23:30:00Z') }, + new Date('2026-12-15T00:00:00Z') + ) + expect([short.from, short.to]).toEqual(['2026-11-10', '2026-11-11']) + }) + + it('runs a window ending now through today', () => { + const now = new Date('2026-11-28T15:00:00Z') + const trailing = adoptionDays( + organizationId, + { start: new Date('2026-11-21T15:00:00Z'), end: now }, + new Date(now.getTime() + 1000) + ) + expect([trailing.from, trailing.to, trailing.asOf]).toEqual([ + '2026-11-21', + '2026-11-29', + '2026-11-29', + ]) + }) + + it('reads a period in another time zone as the same UTC days, for counts and Search MCP alike', async () => { + const pacific = adoptionDays( + organizationId, + { start: new Date('2026-11-01T08:00:00Z'), end: new Date('2026-11-29T08:00:00Z') }, + new Date('2026-12-15T00:00:00Z') + ) + expect([pacific.from, pacific.to]).toEqual([days.from, days.to]) + const late = generateId() + await db.insert(organizationSearchMcpInvocation).values({ + id: late, + organizationId, + userId: ben, + authKind: 'personal_api_key', + toolName: 'search', + outcome: 'success', + durationMs: 5, + createdAt: new Date('2026-11-29T05:00:00Z'), + }) + try { + const tools = await readAdoptionBreakdown(pacific, 'mcp_tool') + expect(tools.rows.find((row) => row.id === 'search')?.total).toBe(2) + } finally { + await db + .delete(organizationSearchMcpInvocation) + .where(eq(organizationSearchMcpInvocation.id, late)) + } + }) + it('lists every current member, inactive ones included, most days active first', async () => { const page = await readAdoptionMemberPage(days, 'days', 0) diff --git a/apps/sim/lib/billing/core/organization-adoption.ts b/apps/sim/lib/billing/core/organization-adoption.ts index 1fa2cdd2ed9..76b44a350d7 100644 --- a/apps/sim/lib/billing/core/organization-adoption.ts +++ b/apps/sim/lib/billing/core/organization-adoption.ts @@ -24,36 +24,48 @@ const BREAKDOWN_MAX_ROWS = 500 /** The longest export, in members; an organization larger than this exports its most active. */ export const ADOPTION_EXPORT_MAX_ROWS = 10_000 -/** A window as the UTC calendar days the daily counts are keyed by: `[from, to)`. */ +/** + * A window as the UTC calendar days every adoption read is keyed by, `[from, to)`: the daily + * counts and the Search MCP log alike, so the two never disagree about a period's edges. + */ export interface AdoptionDays { organizationId: string from: string to: string /** The exclusive day the headline 1/7/28-day counts end at: the window's end, or today. */ asOf: string - /** The instant the window started, for the Search MCP log, which keeps exact times. */ - start: Date - end: Date } function utcDay(instant: Date): string { return instant.toISOString().slice(0, 10) } -/** The UTC days a window touches, ending no later than today. */ +/** + * The UTC days of a window: from the day its start falls on to the day its end falls on + * (exclusive), or through today when the window runs past now. A period in another time zone + * therefore keeps its day count rather than gaining a partial UTC day at either edge. + */ export function adoptionDays( organizationId: string, window: { start: Date; end: Date }, now = new Date() ): AdoptionDays { - const end = window.end < now ? window.end : now - /** A window that starts after today is empty, not a window that runs backwards. */ - const asOf = utcDay(new Date(end.getTime() - 1 + DAY_MS)) - if (window.start >= end) { - const today = utcDay(end) - return { organizationId, from: today, to: today, asOf, start: end, end } + const today = utcDay(now) + // A window ending anywhere in today, as a trailing preset ending now does, runs through today. + const to = + window.end > new Date(`${today}T00:00:00.000Z`) + ? utcDay(new Date(now.getTime() + DAY_MS)) + : utcDay(window.end) + const from = utcDay(window.start) + // A window that starts after it ends or after now is empty; any other + // window keeps at least the day it starts on, as a short one inside one UTC day would not. + if (window.start >= window.end || window.start >= now || from > to) + return { organizationId, from: to, to, asOf: to } + if (from === to) { + const next = utcDay(new Date(new Date(`${from}T00:00:00.000Z`).getTime() + DAY_MS)) + return { organizationId, from, to: next, asOf: next } } - return { organizationId, from: utcDay(window.start), to: asOf, asOf, start: window.start, end } + return { organizationId, from, to, asOf: to } } function dayBefore(day: string, days: number): string { @@ -250,8 +262,8 @@ export async function readAdoptionBreakdown( FROM ${organizationSearchMcpInvocation} i JOIN ${member} m ON m.user_id = i.user_id AND m.organization_id = i.organization_id WHERE i.organization_id = ${days.organizationId} - AND i.created_at >= ${days.start.toISOString()}::timestamptz - AND i.created_at < ${days.end.toISOString()}::timestamptz + AND i.created_at >= (${days.from}::timestamp AT TIME ZONE 'UTC') + AND i.created_at < (${days.to}::timestamp AT TIME ZONE 'UTC') GROUP BY 1 ORDER BY total DESC, label ASC LIMIT ${BREAKDOWN_MAX_ROWS + 1}`) diff --git a/apps/sim/lib/execution/preprocessing.ts b/apps/sim/lib/execution/preprocessing.ts index afe89e8ef34..0f7afdbf3e6 100644 --- a/apps/sim/lib/execution/preprocessing.ts +++ b/apps/sim/lib/execution/preprocessing.ts @@ -39,7 +39,10 @@ import type { SubscriptionPlan } from '@/lib/core/rate-limiter/types' import { withDatabaseReadRetry } from '@/lib/db/read-retry' import { claimBlockedRunLog } from '@/lib/execution/blocked-run-log' import { LoggingSession, type SessionStartParams } from '@/lib/logs/execution/logging-session' -import { recordMemberActivity } from '@/lib/organizations/member-activity/record' +import { + isPersonWorkflowRun, + recordMemberActivity, +} from '@/lib/organizations/member-activity/record' import type { CoreTriggerType } from '@/stores/logs/filters/types' const logger = createLogger('ExecutionPreprocessing') @@ -1109,14 +1112,8 @@ export async function preprocessExecution( executionType, effectiveTimeoutMs: executionTimeout[executionType], }) - /** A run the person started from the editor or with their own API key, never a child or table run. */ - if ( - useAuthenticatedUserAsActor && - (triggerType === 'manual' || triggerType === 'api') && - userId && - workspaceId - ) { - void recordMemberActivity({ + if (isPersonWorkflowRun(useAuthenticatedUserAsActor, triggerType) && userId && workspaceId) { + recordMemberActivity({ userId, surface: 'workflows', scope: { kind: 'workspace', workspaceId }, diff --git a/apps/sim/lib/knowledge/application/slack-search/assistant.ts b/apps/sim/lib/knowledge/application/slack-search/assistant.ts index 86077a12a94..a33f817ba41 100644 --- a/apps/sim/lib/knowledge/application/slack-search/assistant.ts +++ b/apps/sim/lib/knowledge/application/slack-search/assistant.ts @@ -184,7 +184,7 @@ export async function runSlackSearchAssistant( await checkAccess() await persistSlackSearchQuestion(chat.id, userId, messageId, job.message.query) questionPersisted = true - void recordMemberActivity({ + recordMemberActivity({ userId, surface: 'slack', scope: { kind: 'organization', organizationId: installation.organizationId }, diff --git a/apps/sim/lib/knowledge/mcp/activity.ts b/apps/sim/lib/knowledge/mcp/activity.ts index 5652b467d86..cb7ade5a272 100644 --- a/apps/sim/lib/knowledge/mcp/activity.ts +++ b/apps/sim/lib/knowledge/mcp/activity.ts @@ -50,7 +50,7 @@ export async function recordOrganizationSearchMcpActivity( }) } if (input.userId && input.outcome !== 'rate_limited') { - await recordMemberActivity({ + recordMemberActivity({ userId: input.userId, surface: 'search_mcp', scope: { kind: 'organization', organizationId: input.organizationId }, diff --git a/apps/sim/lib/mothership/chat/post.ts b/apps/sim/lib/mothership/chat/post.ts index eacdad0c258..478bae32f16 100644 --- a/apps/sim/lib/mothership/chat/post.ts +++ b/apps/sim/lib/mothership/chat/post.ts @@ -84,7 +84,7 @@ import { getLocalChatStreamLease } from '@/lib/mothership/request/session/abort' import type { ExecutionContext } from '@/lib/mothership/request/types' import { hasAddressableId } from '@/lib/mothership/resources/types' import { prepareExecutionContext } from '@/lib/mothership/tools/handlers/context' -import { recordMemberActivity } from '@/lib/organizations/member-activity/record' +import { chatTurnSurface, recordMemberActivity } from '@/lib/organizations/member-activity/record' import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions' import { capabilityRefusalResponse } from '@/lib/permission-groups/capability-response' import { captureServerEvent } from '@/lib/posthog/server' @@ -1315,10 +1315,9 @@ export async function handleUnifiedChatPost(req: NextRequest) { branch.kind === 'organization' ? { kind: 'organization', organizationId: branch.organizationId } : { kind: 'workspace', workspaceId: branch.workspaceId } - void recordMemberActivity({ + recordMemberActivity({ userId: authenticatedUserId, - surface: - branch.kind === 'organization' && body.mode === 'assistant' ? 'assistant' : 'agent', + surface: chatTurnSurface(branch.kind === 'organization', body.mode), scope: activityScope, }) } diff --git a/apps/sim/lib/organizations/member-activity/backfill.integration.ts b/apps/sim/lib/organizations/member-activity/backfill.integration.ts new file mode 100644 index 00000000000..3d2db66a6aa --- /dev/null +++ b/apps/sim/lib/organizations/member-activity/backfill.integration.ts @@ -0,0 +1,172 @@ +/** + * The adoption backfill against real PostgreSQL: it counts what the live recorder counts (a + * person's own questions under the mode they were asked in, Search MCP calls that were not rate + * limited), each forked copy of a question once, never inbox email (forked or not) or automated + * turns, only the + * day asked for, and the same rows when run again. + */ +import { db } from '@sim/db' +import { + copilotChats, + copilotMessages, + member, + mothershipInboxTask, + organization, + organizationMemberActivityDaily, + organizationSearchMcpInvocation, + project, + user, + workspace, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { + backfillDays, + backfillMemberActivityDay, +} from '@/lib/organizations/member-activity/backfill' + +/** A day no other suite writes, since a backfilled day is replaced for every organization. */ +const DAY = '2025-03-17' +const NEXT_DAY = '2025-03-18' +const organizationId = generateId() +const userId = generateId() +const projectId = generateId() +const workspaceId = generateId() + +async function chat(values: Partial = {}) { + const id = generateId() + await db + .insert(copilotChats) + .values({ id, userId, organizationId, type: 'mothership', ...values }) + return id +} + +async function question( + chatId: string, + content: Record, + at = `${DAY}T10:00:00Z`, + messageId = generateId() +) { + await db + .insert(copilotMessages) + .values({ chatId, messageId, role: 'user', content, createdAt: new Date(at) }) +} + +async function counts() { + const rows = await db + .select() + .from(organizationMemberActivityDaily) + .where(eq(organizationMemberActivityDaily.organizationId, organizationId)) + return Object.fromEntries(rows.map((row) => [`${row.surface}@${row.day}`, row.eventCount])) +} + +describe('member activity backfill', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Backfill fixture', + email: `${userId}@backfill.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db + .insert(organization) + .values({ id: organizationId, name: 'Backfill fixture', slug: `backfill-${organizationId}` }) + await db.insert(member).values({ id: generateId(), userId, organizationId, role: 'member' }) + await db + .insert(project) + .values({ id: projectId, name: 'Backfill', ownerId: userId, organizationId }) + await db.insert(workspace).values({ + id: workspaceId, + projectId, + name: 'Backfill workspace', + ownerId: userId, + billedAccountUserId: userId, + organizationId, + workspaceMode: 'organization', + }) + + const assistantChat = await chat({ config: { conversationMode: 'agent' } }) + const asked = generateId() + await question( + assistantChat, + { content: 'asked in Assistant mode', requestMode: 'assistant' }, + undefined, + asked + ) + await question(assistantChat, { content: 'asked in agent mode', requestMode: 'agent' }) + await question(assistantChat, { content: 'Job: brief', origin: 'job' }) + await question( + assistantChat, + { content: 'the next day', requestMode: 'agent' }, + `${NEXT_DAY}T10:00:00Z` + ) + const fork = await chat() + await question( + fork, + { content: 'asked in Assistant mode', requestMode: 'assistant' }, + undefined, + asked + ) + const inboxChat = await chat({ organizationId: null, workspaceId }) + const emailed = generateId() + await question(inboxChat, { content: 'an emailed request' }, undefined, emailed) + const forkedInbox = await chat({ organizationId: null, workspaceId }) + await question(forkedInbox, { content: 'an emailed request' }, undefined, emailed) + await db.insert(mothershipInboxTask).values({ + id: generateId(), + workspaceId, + fromEmail: 'sender@example.test', + subject: 'Request', + chatId: inboxChat, + }) + await question(await chat({ externalConversationKey: 'slack:["i","D1","t"]' }), { + content: 'from Slack', + }) + await db.insert(organizationSearchMcpInvocation).values( + (['success', 'rate_limited'] as const).map((outcome) => ({ + id: generateId(), + organizationId, + userId, + authKind: 'personal_api_key' as const, + toolName: 'search' as const, + outcome, + durationMs: 5, + createdAt: new Date(`${DAY}T12:00:00Z`), + })) + ) + }) + + afterAll(async () => { + await db.delete(workspace).where(eq(workspace.id, workspaceId)) + await db.delete(project).where(eq(project.id, projectId)) + await db.delete(organization).where(eq(organization.id, organizationId)) + await db.delete(user).where(inArray(user.id, [userId])) + }) + + it('counts the day as the live recorder would, and the same again when rerun', async () => { + const expected = { + [`assistant@${DAY}`]: 1, + [`agent@${DAY}`]: 1, + [`slack@${DAY}`]: 1, + [`search_mcp@${DAY}`]: 1, + } + expect(await backfillMemberActivityDay(DAY, true)).toBe(4) + expect(await counts()).toEqual({}) + + expect(await backfillMemberActivityDay(DAY)).toBe(4) + expect(await counts()).toEqual(expected) + await backfillMemberActivityDay(DAY) + expect(await counts()).toEqual(expected) + }) + + it('covers the days from --since up to, not including, --before', () => { + expect(backfillDays(new Date(`${DAY}T00:00:00Z`), new Date('2025-03-19T00:00:00Z'))).toEqual([ + DAY, + NEXT_DAY, + ]) + }) +}) diff --git a/apps/sim/lib/organizations/member-activity/backfill.ts b/apps/sim/lib/organizations/member-activity/backfill.ts new file mode 100644 index 00000000000..36c65cc507e --- /dev/null +++ b/apps/sim/lib/organizations/member-activity/backfill.ts @@ -0,0 +1,101 @@ +import { db } from '@sim/db' +import { + copilotChats, + copilotMessages, + member, + mothershipInboxTask, + organizationMemberActivityDaily, + organizationSearchMcpInvocation, + workspace, +} from '@sim/db/schema' +import { type SQL, sql } from 'drizzle-orm' + +const DAY_MS = 86_400_000 + +/** + * One UTC day of people's own chat questions, as (organization, person, day, surface, count, + * first, last). Counts what the live recorder counts: a forked chat's copies once, under the + * mode each question was asked in; automated task and job turns, benchmark chats and inbox email + * questions (run for an external sender as the workspace owner), including their forked copies, + * never. Chats the person later + * deleted still count: the use happened. + */ +function chatActivity(from: string, to: string): SQL { + return sql` + SELECT org.organization_id, c.user_id, m.created_at::date AS day, + CASE + WHEN c.external_conversation_key LIKE 'slack:%' THEN 'slack' + WHEN c.organization_id IS NOT NULL AND coalesce( + m.content->>'requestMode', c.config->>'conversationMode', 'assistant' + ) = 'assistant' THEN 'assistant' + ELSE 'agent' + END AS surface, + count(DISTINCT m.message_id)::int AS event_count, + min(m.created_at) AT TIME ZONE 'UTC' AS first_at, + max(m.created_at) AT TIME ZONE 'UTC' AS last_at + FROM ${copilotMessages} m + JOIN ${copilotChats} c ON c.id = m.chat_id + LEFT JOIN ${workspace} w ON w.id = c.workspace_id + CROSS JOIN LATERAL (SELECT coalesce(c.organization_id, w.organization_id) AS organization_id) org + JOIN ${member} mb ON mb.user_id = c.user_id AND mb.organization_id = org.organization_id + WHERE m.role = 'user' AND m.deleted_at IS NULL + AND m.created_at >= ${from}::timestamp AND m.created_at < ${to}::timestamp + AND m.content->>'origin' IS NULL + AND c.config->'benchmark' IS NULL + AND NOT EXISTS ( + SELECT 1 FROM ${copilotMessages} im + JOIN ${mothershipInboxTask} t ON t.chat_id = im.chat_id + WHERE im.role = 'user' AND im.deleted_at IS NULL + AND im.created_at = m.created_at AND im.message_id = m.message_id) + GROUP BY 1, 2, 3, 4` +} + +/** One UTC day of Search MCP calls by members, in the same shape as {@link chatActivity}. */ +function searchMcpActivity(from: string, to: string): SQL { + return sql` + SELECT i.organization_id, i.user_id, (i.created_at AT TIME ZONE 'UTC')::date AS day, + 'search_mcp' AS surface, count(*)::int AS event_count, + min(i.created_at) AS first_at, max(i.created_at) AS last_at + FROM ${organizationSearchMcpInvocation} i + JOIN ${member} mb ON mb.user_id = i.user_id AND mb.organization_id = i.organization_id + WHERE i.user_id IS NOT NULL AND i.outcome <> 'rate_limited' + AND i.created_at >= (${from}::timestamp AT TIME ZONE 'UTC') + AND i.created_at < (${to}::timestamp AT TIME ZONE 'UTC') + GROUP BY 1, 2, 3, 4` +} + +/** The UTC days `[since, before)` a backfill covers, as `YYYY-MM-DD`. */ +export function backfillDays(since: Date, before: Date): string[] { + const days: string[] = [] + for (let day = since.getTime(); day < before.getTime(); day += DAY_MS) + days.push(new Date(day).toISOString().slice(0, 10)) + return days +} + +/** + * Replaces one UTC day's backfilled surfaces with the history's current count, in one + * transaction, so a rerun writes the same rows and drops counts whose source rows are gone. + * Returns the rows written, or with `dryRun` the rows it would write. + */ +export async function backfillMemberActivityDay(day: string, dryRun = false): Promise { + const to = new Date(new Date(`${day}T00:00:00.000Z`).getTime() + DAY_MS) + .toISOString() + .slice(0, 10) + const activity = sql`${chatActivity(day, to)} UNION ALL ${searchMcpActivity(day, to)}` + if (dryRun) { + const [counted] = await db.execute<{ rows: number }>( + sql`SELECT count(*)::int AS rows FROM (${activity}) a` + ) + return counted?.rows ?? 0 + } + const written = await db.transaction(async (tx) => { + await tx.execute(sql` + DELETE FROM ${organizationMemberActivityDaily} + WHERE day = ${day}::date AND surface IN ('assistant', 'agent', 'slack', 'search_mcp')`) + return tx.execute(sql` + INSERT INTO ${organizationMemberActivityDaily} + (organization_id, user_id, day, surface, event_count, first_at, last_at) + SELECT * FROM (${activity}) a`) + }) + return written.count +} diff --git a/apps/sim/lib/organizations/member-activity/history.integration.ts b/apps/sim/lib/organizations/member-activity/history.integration.ts index 331cb5850b4..1a6a62bf2fb 100644 --- a/apps/sim/lib/organizations/member-activity/history.integration.ts +++ b/apps/sim/lib/organizations/member-activity/history.integration.ts @@ -1,9 +1,10 @@ /** * Organization adoption history against real PostgreSQL: which organization a person's use is - * counted for, that concurrent uses lose no count, that a failed write stays silent, and that the - * retention sweep removes only rows past their age. + * counted for, that buffered uses add up across flushes and scopes, which Search MCP calls and + * Search page queries count, that a failed write stays silent, and that the retention sweep + * removes only rows past their age and keeps going when one table is blocked. */ -import { db } from '@sim/db' +import { db, runOutsideTransactionContext } from '@sim/db' import { member, organization, @@ -16,13 +17,15 @@ import { import { generateId } from '@sim/utils/id' import { eq, inArray, sql } from 'drizzle-orm' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { recordOrganizationSearchMcpActivity } from '@/lib/knowledge/mcp/activity' import { + flushMemberActivity, type MemberActivitySurface, recordMemberActivity, + recordSearchPageActivity, } from '@/lib/organizations/member-activity/record' import { - MEMBER_ACTIVITY_RETENTION_DAYS, - SEARCH_MCP_INVOCATION_RETENTION_DAYS, + ADOPTION_HISTORY_RETENTION_DAYS, sweepActivityHistory, } from '@/lib/organizations/member-activity/retention' @@ -38,6 +41,23 @@ const personalProjectId = generateId() const organizations = [organizationId, otherOrganizationId] const users = [memberUserId, outsiderUserId] +const orgScope = { kind: 'organization', organizationId } as const + +function use( + surface: MemberActivitySurface, + userId = memberUserId, + scope: + | { kind: 'organization'; organizationId: string } + | { kind: 'workspace'; workspaceId: string } = orgScope +) { + recordMemberActivity({ userId, surface, scope }) +} + +async function counts(orgId = organizationId) { + await flushMemberActivity() + return Object.fromEntries((await rowsFor(orgId)).map((row) => [row.surface, row.eventCount])) +} + function rowsFor(orgId: string) { return db .select() @@ -112,22 +132,11 @@ describe('organization member activity history', () => { await db.delete(user).where(inArray(user.id, users)) }) - it('counts each use by a member on the day, per surface', async () => { - await recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'organization', organizationId }, - surface: 'assistant', - }) - await recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'organization', organizationId }, - surface: 'assistant', - }) - await recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'organization', organizationId }, - surface: 'search_mcp', - }) + it('counts each use by a member on the UTC day, per surface', async () => { + use('assistant') + use('assistant') + use('search_mcp') + await flushMemberActivity() const rows = await rowsFor(organizationId) const [{ today }] = await db.execute<{ today: string }>( @@ -142,104 +151,153 @@ describe('organization member activity history', () => { }) it('never counts a person toward an organization they do not belong to', async () => { - await recordMemberActivity({ - userId: outsiderUserId, - scope: { kind: 'organization', organizationId }, - surface: 'slack', - }) - await recordMemberActivity({ - userId: outsiderUserId, - scope: { kind: 'workspace', workspaceId: organizationWorkspaceId }, - surface: 'workflows', - }) + use('slack', outsiderUserId) + use('workflows', outsiderUserId, { kind: 'workspace', workspaceId: organizationWorkspaceId }) - expect(await rowsFor(organizationId)).toEqual([]) - expect(await rowsFor(otherOrganizationId)).toEqual([]) + expect(await counts()).toEqual({}) + expect(await counts(otherOrganizationId)).toEqual({}) }) it("counts workspace use toward the workspace's organization, and nothing for a workspace without one", async () => { - await recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'workspace', workspaceId: organizationWorkspaceId }, - surface: 'agent', - }) - await recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'workspace', workspaceId: personalWorkspaceId }, - surface: 'agent', - }) + use('agent', memberUserId, { kind: 'workspace', workspaceId: organizationWorkspaceId }) + use('agent', memberUserId, { kind: 'workspace', workspaceId: personalWorkspaceId }) - const rows = await rowsFor(organizationId) - expect(rows.map((row) => [row.surface, row.eventCount])).toEqual([['agent', 1]]) + expect(await counts()).toEqual({ agent: 1 }) }) - it('loses no count when uses arrive at once', async () => { - await Promise.all( - Array.from({ length: 20 }, () => - recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'organization', organizationId }, - surface: 'search', - }) - ) - ) + it('adds up uses across flushes, and an organization and its workspace into one row', async () => { + use('agent') + use('agent', memberUserId, { kind: 'workspace', workspaceId: organizationWorkspaceId }) + expect(await counts()).toEqual({ agent: 2 }) + use('agent') + expect(await counts()).toEqual({ agent: 3 }) + }) - const rows = await rowsFor(organizationId) - expect(rows.map((row) => row.eventCount)).toEqual([20]) + it('waits for a flush already writing, and loses no count when flushes overlap', async () => { + for (let index = 0; index < 10; index++) use('search') + const timerFlush = flushMemberActivity() + expect(await counts()).toEqual({ search: 10 }) + for (let index = 0; index < 10; index++) use('search') + await Promise.all([timerFlush, flushMemberActivity(), flushMemberActivity()]) + expect(await counts()).toEqual({ search: 20 }) }) it('swallows a write the database refuses', async () => { - await expect( - recordMemberActivity({ - userId: memberUserId, - scope: { kind: 'organization', organizationId }, - surface: 'unknown' as MemberActivitySurface, - }) - ).resolves.toBeUndefined() + use('unknown' as MemberActivitySurface) + await expect(flushMemberActivity()).resolves.toBeUndefined() expect(await rowsFor(organizationId)).toEqual([]) }) + it('counts a Search MCP call by a person unless it was rate limited', async () => { + const call = (outcome: 'success' | 'rate_limited', userId: string | null = memberUserId) => + recordOrganizationSearchMcpActivity({ + organizationId, + userId, + authKind: 'personal_api_key', + oauthClientId: null, + clientName: null, + toolName: 'search', + outcome, + durationMs: 5, + createdAt: new Date(), + }) + await call('rate_limited') + await call('success', null) + expect(await counts()).toEqual({}) + await call('success') + expect(await counts()).toEqual({ search_mcp: 1 }) + }) + + it('counts a Search page query once a minute, and no other search surface', async () => { + const search = (surface: string, query: string, userId?: string) => + recordSearchPageActivity({ surface, userId, scope: orgScope, search: [query, {}] }) + const query = `release notes ${generateId()}` + await search('mcp', query, memberUserId) + await search('workflow', query, memberUserId) + await search('dashboard', query, undefined) + expect(await counts()).toEqual({}) + + await search('dashboard', query, memberUserId) + await search('dashboard', query, memberUserId) + expect(await counts()).toEqual({ search: 1 }) + await search('dashboard', `${query} again`, memberUserId) + expect(await counts()).toEqual({ search: 2 }) + }) + it('sweeps only history past its retention', async () => { const now = new Date() const dayAgo = (days: number) => new Date(now.getTime() - days * DAY_MS) const dayString = (days: number) => dayAgo(days).toISOString().slice(0, 10) - await db.insert(organizationMemberActivityDaily).values( - [MEMBER_ACTIVITY_RETENTION_DAYS - 1, MEMBER_ACTIVITY_RETENTION_DAYS + 1].map((days) => ({ - organizationId, - userId: memberUserId, - day: dayString(days), - surface: 'assistant' as const, - eventCount: 1, - firstAt: dayAgo(days), - lastAt: dayAgo(days), - })) - ) - await db.insert(organizationSearchMcpInvocation).values( - [SEARCH_MCP_INVOCATION_RETENTION_DAYS - 1, SEARCH_MCP_INVOCATION_RETENTION_DAYS + 1].map( - (days) => ({ - id: generateId(), - organizationId, - userId: memberUserId, - authKind: 'personal_api_key' as const, - toolName: 'search' as const, - outcome: 'success' as const, - durationMs: 10, - createdAt: dayAgo(days), - }) - ) - ) + await insertAged(dayAgo, dayString) await sweepActivityHistory(now) expect((await rowsFor(organizationId)).map((row) => row.day)).toEqual([ - dayString(MEMBER_ACTIVITY_RETENTION_DAYS - 1), - ]) - const invocations = await db - .select({ createdAt: organizationSearchMcpInvocation.createdAt }) - .from(organizationSearchMcpInvocation) - .where(eq(organizationSearchMcpInvocation.organizationId, organizationId)) - expect(invocations.map((row) => row.createdAt.getTime())).toEqual([ - dayAgo(SEARCH_MCP_INVOCATION_RETENTION_DAYS - 1).getTime(), + dayString(ADOPTION_HISTORY_RETENTION_DAYS - 1), ]) + expect(await invocationAges(now)).toEqual([ADOPTION_HISTORY_RETENTION_DAYS - 1]) }) + + it('keeps sweeping the other table when one batch times out on a held row', async () => { + const now = new Date() + const dayAgo = (days: number) => new Date(now.getTime() - days * DAY_MS) + const dayString = (days: number) => dayAgo(days).toISOString().slice(0, 10) + await insertAged(dayAgo, dayString) + + const result = await db.transaction(async (tx) => { + await tx.execute(sql` + SELECT 1 FROM ${organizationMemberActivityDaily} + WHERE organization_id = ${organizationId} + AND day = ${dayString(ADOPTION_HISTORY_RETENTION_DAYS + 1)}::date + FOR UPDATE`) + // The sweep runs on its own cleanup connection while this one holds the row. + return runOutsideTransactionContext(() => sweepActivityHistory(now)) + }) + + expect(result.finished).toBe(false) + expect((await rowsFor(organizationId)).map((row) => row.day).sort()).toEqual( + [ + dayString(ADOPTION_HISTORY_RETENTION_DAYS + 1), + dayString(ADOPTION_HISTORY_RETENTION_DAYS - 1), + ].sort() + ) + expect(await invocationAges(now)).toEqual([ADOPTION_HISTORY_RETENTION_DAYS - 1]) + }, 60_000) }) + +/** One row a day inside and one a day outside retention, in both tables. */ +async function insertAged(dayAgo: (days: number) => Date, dayString: (days: number) => string) { + const ages = [ADOPTION_HISTORY_RETENTION_DAYS - 1, ADOPTION_HISTORY_RETENTION_DAYS + 1] + await db.insert(organizationMemberActivityDaily).values( + ages.map((days) => ({ + organizationId, + userId: memberUserId, + day: dayString(days), + surface: 'assistant' as const, + eventCount: 1, + firstAt: dayAgo(days), + lastAt: dayAgo(days), + })) + ) + await db.insert(organizationSearchMcpInvocation).values( + ages.map((days) => ({ + id: generateId(), + organizationId, + userId: memberUserId, + authKind: 'personal_api_key' as const, + toolName: 'search' as const, + outcome: 'success' as const, + durationMs: 10, + createdAt: dayAgo(days), + })) + ) +} + +/** The fixture organization's Search MCP rows left, as whole days before `now`. */ +async function invocationAges(now: Date) { + const rows = await db + .select({ createdAt: organizationSearchMcpInvocation.createdAt }) + .from(organizationSearchMcpInvocation) + .where(eq(organizationSearchMcpInvocation.organizationId, organizationId)) + return rows.map((row) => Math.round((now.getTime() - row.createdAt.getTime()) / DAY_MS)) +} diff --git a/apps/sim/lib/organizations/member-activity/record.test.ts b/apps/sim/lib/organizations/member-activity/record.test.ts new file mode 100644 index 00000000000..8eb35094254 --- /dev/null +++ b/apps/sim/lib/organizations/member-activity/record.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { chatTurnSurface, isPersonWorkflowRun } from '@/lib/organizations/member-activity/record' + +describe('which uses count as whose', () => { + it.each([ + [true, 'manual', true], + [true, 'api', true], + [true, 'workflow', false], + [true, 'schedule', false], + [true, 'webhook', false], + [false, 'manual', false], + [false, 'api', false], + ] as const)( + 'a run acting as its person=%s with trigger %s counts: %s', + (asPerson, trigger, counts) => { + expect(isPersonWorkflowRun(asPerson, trigger)).toBe(counts) + } + ) + + it.each([ + [true, 'assistant', 'assistant'], + [true, 'agent', 'agent'], + [true, 'plan', 'agent'], + [true, undefined, 'agent'], + [false, 'assistant', 'agent'], + ] as const)( + 'an organization chat=%s in mode %s counts as %s', + (organizationChat, mode, surface) => { + expect(chatTurnSurface(organizationChat, mode)).toBe(surface) + } + ) +}) diff --git a/apps/sim/lib/organizations/member-activity/record.ts b/apps/sim/lib/organizations/member-activity/record.ts index 1cf8f0afff8..215fe3936d7 100644 --- a/apps/sim/lib/organizations/member-activity/record.ts +++ b/apps/sim/lib/organizations/member-activity/record.ts @@ -1,8 +1,10 @@ +import { createHash } from 'node:crypto' import { db } from '@sim/db' import { member, organizationMemberActivityDaily, workspace } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { sql } from 'drizzle-orm' +import { getRedisClient } from '@/lib/core/config/redis' import type { ResourceScope } from '@/lib/core/resource-scope' const logger = createLogger('OrganizationMemberActivity') @@ -10,40 +12,193 @@ const logger = createLogger('OrganizationMemberActivity') /** Where a member used Sim: the organization Assistant, an agent chat, the Search page, the Search MCP server, the Slack app, or a workflow they ran themselves. */ export type MemberActivitySurface = (typeof organizationMemberActivityDaily.$inferSelect)['surface'] +/** An organization chat in Assistant mode is Assistant use; every other chat turn is agent use. */ +export function chatTurnSurface( + isOrganizationChat: boolean, + mode: string | undefined +): MemberActivitySurface { + return isOrganizationChat && mode === 'assistant' ? 'assistant' : 'agent' +} + /** - * Counts one use of a surface by a person, on today's UTC day, for the organization that owns the - * scope: the organization itself, or the workspace's. A person who is not a member of that - * organization, or a workspace without one, records nothing. Content-free, best effort and never - * throws, so callers need no error handling and may fire it without awaiting. + * A workflow run counts as its person's use only when they started it themselves: from the editor + * (`manual`) or with their own credential (`api`). Child, table, schedule and webhook runs do not. */ -export async function recordMemberActivity(input: { +export function isPersonWorkflowRun( + useAuthenticatedUserAsActor: boolean, + triggerType: string +): boolean { + return useAuthenticatedUserAsActor && (triggerType === 'manual' || triggerType === 'api') +} + +interface PendingActivity { userId: string surface: MemberActivitySurface scope: ResourceScope -}): Promise { - const organizationId = - input.scope.kind === 'organization' - ? sql`${input.scope.organizationId}` - : sql`(SELECT ${workspace.organizationId} FROM ${workspace} WHERE ${workspace.id} = ${input.scope.workspaceId})` + day: string + count: number + firstAt: Date + lastAt: Date +} + +const FLUSH_INTERVAL_MS = 5_000 +/** Distinct (scope, person, surface, day) keys held before a flush is forced, and rows per write. */ +const FLUSH_THRESHOLD = 500 +/** Keys held while writes are failing or slow; a new key past this is dropped, as analytics. */ +const MAX_PENDING = 10_000 + +let pending = new Map() +let timer: ReturnType | undefined +let handlersRegistered = false +/** The flush being written; flushes run one after another, never overlapping. */ +let inFlight: Promise = Promise.resolve() +/** Whether a flush is already waiting behind {@link inFlight}, so no second one queues. */ +let flushQueued: Promise | undefined +let droppedKeys = 0 + +function scopeId(scope: ResourceScope): string { + return scope.kind === 'organization' ? scope.organizationId : scope.workspaceId +} + +function ensureBackground(): void { + if (timer) return + timer = setInterval(() => void flushMemberActivity(), FLUSH_INTERVAL_MS) + timer.unref?.() + if (handlersRegistered) return + handlersRegistered = true + const onExit = async () => { + await flushMemberActivity() + } + process.once('SIGTERM', onExit) + process.once('SIGINT', onExit) + process.once('beforeExit', onExit) +} + +/** + * Counts one use of a surface by a person, on the current UTC day, for the organization that owns + * the scope: the organization itself, or the workspace's. Uses are added up in this process and + * written together every few seconds and on shutdown, so the action never waits on the database + * and repeated uses cost one row update per flush. A person who is not a member of that + * organization, or a workspace without one, records nothing. Content-free and never throws. + */ +export function recordMemberActivity(input: { + userId: string + surface: MemberActivitySurface + scope: ResourceScope +}): void { + const now = new Date() + const day = now.toISOString().slice(0, 10) + const key = JSON.stringify([ + input.scope.kind, + scopeId(input.scope), + input.userId, + input.surface, + day, + ]) + const existing = pending.get(key) + if (existing) { + existing.count += 1 + existing.lastAt = now + } else if (pending.size >= MAX_PENDING) { + droppedKeys += 1 + } else { + pending.set(key, { ...input, day, count: 1, firstAt: now, lastAt: now }) + } + if (pending.size >= FLUSH_THRESHOLD) void flushMemberActivity() + else ensureBackground() +} + +/** + * Writes every pending use, after any flush already writing, so flushes never overlap and + * awaiting one also awaits the write before it; while one waits to run, later calls share it. + * Uses that resolve to the same organization row (an organization and one of its workspaces) are + * summed before the upsert. A failed write is logged and its uses dropped, as analytics, rather + * than carried into the next flush. + */ +export function flushMemberActivity(): Promise { + if (flushQueued) return flushQueued + const queued = inFlight.then(() => { + flushQueued = undefined + return writePending() + }) + flushQueued = queued + inFlight = queued + return queued +} + +async function writePending(): Promise { + if (droppedKeys) { + logger.warn('Dropped organization member activity while writes were behind', { droppedKeys }) + droppedKeys = 0 + } + if (!pending.size) return + const entries = [...pending.values()] + pending = new Map() + for (let start = 0; start < entries.length; start += FLUSH_THRESHOLD) + await writeBatch(entries.slice(start, start + FLUSH_THRESHOLD)) +} + +async function writeBatch(batch: PendingActivity[]): Promise { + const rows = batch.map( + (entry) => sql`(${entry.scope.kind}::text, ${scopeId(entry.scope)}::text, + ${entry.userId}::text, ${entry.surface}::text, ${entry.day}::date, ${entry.count}::int, + ${entry.firstAt.toISOString()}::timestamptz, ${entry.lastAt.toISOString()}::timestamptz)` + ) try { await db.transaction(async (tx) => { - await tx.execute(sql`SET LOCAL statement_timeout = '2s'`) + await tx.execute(sql`SET LOCAL statement_timeout = '5s'`) await tx.execute(sql` INSERT INTO ${organizationMemberActivityDaily} (organization_id, user_id, day, surface, event_count, first_at, last_at) - SELECT ${member.organizationId}, ${member.userId}, (now() AT TIME ZONE 'UTC')::date, - ${input.surface}, 1, now(), now() - FROM ${member} - WHERE ${member.userId} = ${input.userId} AND ${member.organizationId} = ${organizationId} + SELECT m.organization_id, m.user_id, v.day, v.surface, + sum(v.uses)::int, min(v.first_at), max(v.last_at) + FROM (VALUES ${sql.join(rows, sql`, `)}) + AS v(scope_kind, scope_id, user_id, surface, day, uses, first_at, last_at) + LEFT JOIN ${workspace} w ON v.scope_kind = 'workspace' AND w.id = v.scope_id + JOIN ${member} m ON m.user_id = v.user_id AND m.organization_id = + CASE WHEN v.scope_kind = 'organization' THEN v.scope_id ELSE w.organization_id END + GROUP BY m.organization_id, m.user_id, v.day, v.surface + ORDER BY m.organization_id, v.day, v.surface, m.user_id ON CONFLICT (organization_id, day, surface, user_id) DO UPDATE SET - event_count = ${organizationMemberActivityDaily}.event_count + 1, + event_count = ${organizationMemberActivityDaily}.event_count + EXCLUDED.event_count, first_at = LEAST(${organizationMemberActivityDaily}.first_at, EXCLUDED.first_at), last_at = GREATEST(${organizationMemberActivityDaily}.last_at, EXCLUDED.last_at)`) }) } catch (error) { logger.warn('Failed to record organization member activity', { - surface: input.surface, + uses: batch.length, + error: getErrorMessage(error), + }) + } +} + +/** How long the same search by the same person counts once: refetches and re-renders repeat it. */ +const SEARCH_REPEAT_WINDOW_MS = 60_000 + +/** + * Counts a Search page query as one `search` use. Only the Search page counts (other surfaces of + * the same search use case record their own activity), and the same query with the same filters + * by the same person counts once a minute on each UTC day, across every app replica, so the page + * refetching it is not counted as new use. If the shared check is unavailable the query counts. + */ +export async function recordSearchPageActivity(input: { + surface: string | undefined + userId: string | undefined + scope: ResourceScope + search: unknown +}): Promise { + if (input.surface !== 'dashboard' || !input.userId) return + const day = new Date().toISOString().slice(0, 10) + const key = `member-activity:search:${createHash('sha256') + .update(JSON.stringify([input.userId, input.scope, input.search, day])) + .digest('base64url')}` + try { + const first = await getRedisClient().set(key, '1', 'PX', SEARCH_REPEAT_WINDOW_MS, 'NX') + if (first === null) return + } catch (error) { + logger.warn('Search repeat check unavailable; counting the query', { error: getErrorMessage(error), }) } + recordMemberActivity({ userId: input.userId, surface: 'search', scope: input.scope }) } diff --git a/apps/sim/lib/organizations/member-activity/retention.ts b/apps/sim/lib/organizations/member-activity/retention.ts index 00c2efc4c9d..fdf378206ce 100644 --- a/apps/sim/lib/organizations/member-activity/retention.ts +++ b/apps/sim/lib/organizations/member-activity/retention.ts @@ -5,9 +5,12 @@ import { type SQL, sql } from 'drizzle-orm' const cleanupDb = dbFor('cleanup') -/** Daily counts are kept 400 days, so a year compares with the same weeks of the year before. */ -export const MEMBER_ACTIVITY_RETENTION_DAYS = 400 -export const SEARCH_MCP_INVOCATION_RETENTION_DAYS = 270 +/** + * Adoption history is kept 400 days, so a year compares with the same weeks of the year before. + * Daily counts and Search MCP call metadata share it, so no period can show Search MCP use whose + * breakdown has already been swept. + */ +export const ADOPTION_HISTORY_RETENTION_DAYS = 400 const DAY_MS = 86_400_000 const DELETE_BATCH = 5_000 @@ -41,18 +44,15 @@ async function drain(statement: SQL): Promise<{ deleted: number; finished: boole } /** - * Removes adoption history past its retention: daily member activity older than - * {@link MEMBER_ACTIVITY_RETENTION_DAYS} and Search MCP invocations older than - * {@link SEARCH_MCP_INVOCATION_RETENTION_DAYS}. Batched by age index and time-boxed per table, so a + * Removes adoption history older than {@link ADOPTION_HISTORY_RETENTION_DAYS}: daily member + * activity and Search MCP invocations. Batched by age index and time-boxed per table, so a * backlog drains over several runs without one long transaction. */ export async function sweepActivityHistory(now = new Date()) { - const dayCutoff = new Date(now.getTime() - MEMBER_ACTIVITY_RETENTION_DAYS * DAY_MS) - .toISOString() - .slice(0, 10) - const invocationCutoff = new Date( - now.getTime() - SEARCH_MCP_INVOCATION_RETENTION_DAYS * DAY_MS - ).toISOString() + const cutoff = new Date(now.getTime() - ADOPTION_HISTORY_RETENTION_DAYS * DAY_MS) + const dayCutoff = cutoff.toISOString().slice(0, 10) + // Whole UTC days, as the daily counts keep them, so a kept day keeps its Search MCP breakdown. + const invocationCutoff = `${dayCutoff}T00:00:00.000Z` const memberActivityDays = await drain( sql` diff --git a/apps/sim/lib/sim-search/live/application.ts b/apps/sim/lib/sim-search/live/application.ts index cbdfebf49f8..fc2a30f754c 100644 --- a/apps/sim/lib/sim-search/live/application.ts +++ b/apps/sim/lib/sim-search/live/application.ts @@ -1,5 +1,5 @@ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js' -import { requirePrincipalSubjectUserId } from '@sim/auth/principal' +import { requirePrincipalSubjectUserId, resolvePrincipalSubjectUserId } from '@sim/auth/principal' import { safeCompare } from '@sim/security/compare' import { hmacSha256Hex } from '@sim/security/hmac' import { canonicalJson } from '@sim/utils/object' @@ -53,7 +53,7 @@ import { RRF_K } from '@/lib/knowledge/search/recency' import { matchPassage } from '@/lib/knowledge/search/snippet' import { isKnowledgeSourceUrl } from '@/lib/knowledge/search/source-url' import { organizationRoutes } from '@/lib/navigation/paths' -import { recordMemberActivity } from '@/lib/organizations/member-activity/record' +import { recordSearchPageActivity } from '@/lib/organizations/member-activity/record' import { connectorDisplayName } from '@/lib/sim-search/connectors' import { type LiveAccountSession, @@ -963,11 +963,11 @@ const liveKnowledgeSearch = defineAuthorizedKnowledgeUseCase({ } }, afterSuccess({ principal, input }) { - if (input.surface !== 'dashboard') return - void recordMemberActivity({ - userId: requirePrincipalSubjectUserId(principal), - surface: 'search', + void recordSearchPageActivity({ + surface: input.surface, + userId: resolvePrincipalSubjectUserId(principal), scope: resourceScopeFromOwner(input), + search: [input.query, input.filters, input.nativeQueries, input.involving], }) }, }) diff --git a/apps/sim/scripts/backfill-member-activity-daily.ts b/apps/sim/scripts/backfill-member-activity-daily.ts index 5f1431eae16..5bf582f3335 100644 --- a/apps/sim/scripts/backfill-member-activity-daily.ts +++ b/apps/sim/scripts/backfill-member-activity-daily.ts @@ -5,17 +5,17 @@ * shows the months before the live recorder shipped. * * - Assistant, agent and Slack days come from the person's own chat questions in - * `copilot_messages` (automated task and job turns and benchmark chats excluded), each counted - * once even when a forked chat copied it, under the mode it was asked in. Chats the person - * later deleted still count: the use happened. A Search MCP `chat` question is - * indistinguishable from an in-app Assistant question here, so it counts as `assistant`. + * `copilot_messages` (see `lib/organizations/member-activity/backfill.ts` for what counts). A + * Search MCP `chat` question is indistinguishable from an in-app Assistant question here, so + * it counts as `assistant`; v2 Chat API turns count as `agent`, as the live recorder counts them. * - Search MCP days come from `organization_search_mcp_invocation` (rate-limited calls excluded). * - The Search page and workflow runs kept no per-person history, so they start at the deploy. * * Only members of the organization are counted, as the live recorder counts them. Each UTC day in * `[--since, --before)` is replaced by its current count in one transaction, so the script is - * idempotent, resumable by day, and drops counts whose source rows are gone. `--before` must be the first day the live recorder - * counted whole (the day after the deploy); a day it already counts must not be backfilled. + * idempotent, resumable by day, and drops counts whose source rows are gone. `--before` must be + * the first day the live recorder counted whole (the day after the deploy); a day it already + * counts must not be backfilled. * * Usage: * cd apps/sim && DATABASE_URL=... bun scripts/backfill-member-activity-daily.ts \ @@ -23,19 +23,13 @@ */ import { parseArgs } from 'node:util' -import { db } from '@sim/db' -import { - copilotChats, - copilotMessages, - member, - organizationMemberActivityDaily, - organizationSearchMcpInvocation, - workspace, -} from '@sim/db/schema' import { createLogger } from '@sim/logger' import { sleep } from '@sim/utils/helpers' -import { type SQL, sql } from 'drizzle-orm' -import { MEMBER_ACTIVITY_RETENTION_DAYS } from '@/lib/organizations/member-activity/retention' +import { + backfillDays, + backfillMemberActivityDay, +} from '@/lib/organizations/member-activity/backfill' +import { ADOPTION_HISTORY_RETENTION_DAYS } from '@/lib/organizations/member-activity/retention' const logger = createLogger('MemberActivityBackfill', { enabled: true, logLevel: 'INFO' }) @@ -49,46 +43,6 @@ function parseDay(name: string, raw: string): Date { return day } -/** One UTC day of chat questions, as (organization, person, day, surface, count, first, last). */ -function chatActivity(from: string, to: string): SQL { - return sql` - SELECT org.organization_id, c.user_id, m.created_at::date AS day, - CASE - WHEN c.external_conversation_key LIKE 'slack:%' THEN 'slack' - WHEN c.organization_id IS NOT NULL AND coalesce( - m.content->>'requestMode', c.config->>'conversationMode', 'assistant' - ) = 'assistant' THEN 'assistant' - ELSE 'agent' - END AS surface, - count(DISTINCT m.message_id)::int AS event_count, - min(m.created_at) AT TIME ZONE 'UTC' AS first_at, - max(m.created_at) AT TIME ZONE 'UTC' AS last_at - FROM ${copilotMessages} m - JOIN ${copilotChats} c ON c.id = m.chat_id - LEFT JOIN ${workspace} w ON w.id = c.workspace_id - CROSS JOIN LATERAL (SELECT coalesce(c.organization_id, w.organization_id) AS organization_id) org - JOIN ${member} mb ON mb.user_id = c.user_id AND mb.organization_id = org.organization_id - WHERE m.role = 'user' AND m.deleted_at IS NULL - AND m.created_at >= ${from}::timestamp AND m.created_at < ${to}::timestamp - AND m.content->>'origin' IS NULL - AND c.config->'benchmark' IS NULL - GROUP BY 1, 2, 3, 4` -} - -/** One UTC day of Search MCP calls by members, in the same shape as {@link chatActivity}. */ -function searchMcpActivity(from: string, to: string): SQL { - return sql` - SELECT i.organization_id, i.user_id, (i.created_at AT TIME ZONE 'UTC')::date AS day, - 'search_mcp' AS surface, count(*)::int AS event_count, - min(i.created_at) AS first_at, max(i.created_at) AS last_at - FROM ${organizationSearchMcpInvocation} i - JOIN ${member} mb ON mb.user_id = i.user_id AND mb.organization_id = i.organization_id - WHERE i.user_id IS NOT NULL AND i.outcome <> 'rate_limited' - AND i.created_at >= (${from}::timestamp AT TIME ZONE 'UTC') - AND i.created_at < (${to}::timestamp AT TIME ZONE 'UTC') - GROUP BY 1, 2, 3, 4` -} - async function main(): Promise { const { values } = parseArgs({ args: process.argv.slice(2), @@ -103,35 +57,16 @@ async function main(): Promise { const before = parseDay('before', values.before) const since = values.since ? parseDay('since', values.since) - : new Date(before.getTime() - MEMBER_ACTIVITY_RETENTION_DAYS * DAY_MS) + : new Date(before.getTime() - ADOPTION_HISTORY_RETENTION_DAYS * DAY_MS) if (since >= before) throw new Error('--since must be before --before') const dryRun = values['dry-run'] const pauseMs = Number.parseInt(values['pause-ms'] ?? '200', 10) const countKey = dryRun ? 'wouldWrite' : 'written' let rows = 0 - for (let day = since.getTime(); day < before.getTime(); day += DAY_MS) { - const from = new Date(day).toISOString().slice(0, 10) - const to = new Date(day + DAY_MS).toISOString().slice(0, 10) - const activity = sql`${chatActivity(from, to)} UNION ALL ${searchMcpActivity(from, to)}` - if (dryRun) { - const [counted] = await db.execute<{ rows: number }>( - sql`SELECT count(*)::int AS rows FROM (${activity}) a` - ) - rows += counted?.rows ?? 0 - } else { - const written = await db.transaction(async (tx) => { - await tx.execute(sql` - DELETE FROM ${organizationMemberActivityDaily} - WHERE day = ${from}::date AND surface IN ('assistant', 'agent', 'slack', 'search_mcp')`) - return tx.execute(sql` - INSERT INTO ${organizationMemberActivityDaily} - (organization_id, user_id, day, surface, event_count, first_at, last_at) - SELECT * FROM (${activity}) a`) - }) - rows += written.count - } - logger.info('Backfilled day', { day: from, [countKey]: rows }) + for (const day of backfillDays(since, before)) { + rows += await backfillMemberActivityDay(day, dryRun) + logger.info('Backfilled day', { day, [countKey]: rows }) await sleep(pauseMs) } diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index b8720395d92..108aa8c98bb 100644 --- a/helm/sim/Chart.yaml +++ b/helm/sim/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: sim description: A Helm chart for Sim - the open-source AI workspace where teams build, deploy, and manage AI agents type: application -version: 1.15.6 +version: 1.15.7 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index e2f8f200bde..c1d2309d0cf 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1444,8 +1444,8 @@ cronjobs: successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 1 - # Deletes organization adoption history past its retention (daily member activity after - # 400 days, Search MCP call metadata after 270 days). + # Deletes organization adoption history past its retention (daily member activity and + # Search MCP call metadata after 400 days). cleanupActivityHistory: enabled: true name: cleanup-activity-history