Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

93.5 KB
Raw Blame
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["views", "relationJoins", "metrics"]
  // rhel-openssl-3.0.x: UBI9 runtime images (glibc); these engines link the
  // system libcrypto.so.3, so Postgres TLS runs inside the platform's
  // FIPS-validated OpenSSL module.
  binaryTargets   = ["native", "rhel-openssl-3.0.x"]
}

datasource db {
  provider          = "postgresql"
  url               = env("DATABASE_URL")
  directUrl         = env("DIRECT_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

// Necessary for Next auth
model Account {
  id                       String  @id @default(cuid())
  userId                   String  @map("user_id")
  type                     String
  provider                 String
  providerAccountId        String
  refresh_token            String? // @db.Text
  access_token             String? // @db.Text
  expires_at               Int?
  expires_in               Int?
  ext_expires_in           Int?
  token_type               String?
  scope                    String?
  id_token                 String? // @db.Text
  session_state            String?
  refresh_token_expires_in Int?
  created_at               Int? // GitLab
  user                     User    @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
  @@index([userId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique @map("session_token")
  userId       String   @map("user_id")
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id                        String                      @id @default(cuid())
  name                      String?
  email                     String?                     @unique
  emailVerified             DateTime?                   @map("email_verified")
  password                  String?
  sessionsExpiredAt         DateTime?                   @map("sessions_expired_at")
  image                     String?
  admin                     Boolean                     @default(false)
  v4BetaEnabled             Boolean                     @default(false) @map("v4_beta_enabled")
  supportAccess             Json?                       @map("support_access")
  accounts                  Account[]
  sessions                  Session[]
  organizationMemberships   OrganizationMembership[]
  projectMemberships        ProjectMembership[]
  invitations               MembershipInvitation[]
  createdAt                 DateTime                    @default(now()) @map("created_at")
  updatedAt                 DateTime                    @default(now()) @updatedAt @map("updated_at")
  featureFlags              String[]                    @default([]) @map("feature_flags")
  annotatedLockedItem       AnnotationQueueItem[]       @relation("LockedByUser")
  annotatedCompletedItem    AnnotationQueueItem[]       @relation("AnnotatorUser")
  dashboardWidgetsCreated   DashboardWidget[]           @relation("CreatedByUser")
  dashboardWidgetsUpdated   DashboardWidget[]           @relation("UpdatedByUser")
  dashboardCreated          Dashboard[]                 @relation("CreatedByUser")
  dashboardUpdated          Dashboard[]                 @relation("UpdatedByUser")
  tableViewPresetCreated    TableViewPreset[]           @relation("CreatedByUser")
  tableViewPresetUpdated    TableViewPreset[]           @relation("UpdatedByUser")
  monitorsCreated           Monitor[]                   @relation("CreatedByUser")
  monitorsUpdated           Monitor[]                   @relation("UpdatedByUser")
  topicConfigsCreated       TopicConfig[]               @relation("CreatedByUser")
  topicConfigsUpdated       TopicConfig[]               @relation("UpdatedByUser")
  tracingReadinessCreated   TracingReadinessSettings[]  @relation("CreatedByUser")
  tracingReadinessUpdated   TracingReadinessSettings[]  @relation("UpdatedByUser")
  annotationQueueAssignment AnnotationQueueAssignment[]
  surveys                   Survey[]
  commentReactions          CommentReaction[]
  notificationPreferences   NotificationPreference[]
  defaultViews              DefaultView[]               @relation("DefaultViewUser")
  inAppAgentConversations   InAppAgentConversation[]    @relation("InAppAgentConversationCreatedByUser")
  inAppAgentRuns            InAppAgentRun[]             @relation("InAppAgentRunTriggeredByUser")
  apiKeysCreated            ApiKey[]                    @relation("ApiKeyCreatedByUser")
  apiKeys                   ApiKey[]                    @relation("ApiKeyUser")
  roleAssignments           RoleAssignment[]
  evaluatorsCreated         Evaluator[]                 @relation("EvaluatorCreatedByUser")
  evaluatorVersionsCreated  EvaluatorVersion[]          @relation("EvaluatorVersionCreatedByUser")
  evaluationRulesCreated    EvaluationRule[]            @relation("EvaluationRuleCreatedByUser")

  deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentUser") @ignore

  @@map("users")
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
  @@map("verification_tokens")
}

model Organization {
  id                               String                   @id @default(cuid())
  name                             String
  createdAt                        DateTime                 @default(now()) @map("created_at")
  updatedAt                        DateTime                 @default(now()) @updatedAt @map("updated_at")
  cloudConfig                      Json?                    @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema
  metadata                         Json?
  cloudBillingCycleAnchor          DateTime?                @default(now()) @map("cloud_billing_cycle_anchor")
  cloudBillingCycleUpdatedAt       DateTime?                @map("cloud_billing_cycle_updated_at")
  cloudCurrentCycleUsage           Int?                     @map("cloud_current_cycle_usage")
  cloudFreeTierUsageThresholdState String?                  @map("cloud_free_tier_usage_threshold_state")
  aiFeaturesEnabled                Boolean                  @default(false) @map("ai_features_enabled")
  aiTelemetryEnabled               Boolean                  @default(true) @map("ai_telemetry_enabled")
  // Opt-in for read-access audit events (EE). Takes effect only when
  // LANGFUSE_AUDIT_LOG_ACCESS_EVENTS is "org" and the org has the audit-logs
  // entitlement.
  accessAuditLogEnabled            Boolean                  @default(false) @map("access_audit_log_enabled")
  featureFlagOrgDefaults           String[]                 @default([]) @map("feature_flag_org_defaults")
  // SFDC Account / Organization ID returned by the Mulesoft org endpoint on
  // Langfuse Cloud. NULL for self-hosted or pre-integration orgs. A mismatch
  // between the stored value and a subsequently returned ID indicates an SFDC
  // side merge — logged as an error but does not throw (no retry loop).
  sfdcOrgId                        String?                  @map("sfdc_org_id")
  organizationMemberships          OrganizationMembership[]
  projects                         Project[]
  MembershipInvitation             MembershipInvitation[]
  ApiKey                           ApiKey[]
  surveys                          Survey[]
  cloudSpendAlerts                 CloudSpendAlert[]
  verifiedDomains                  VerifiedDomain[]
  gatewayConfig                    GatewayConfig?
  gatewayAiConnections             GatewayAiConnection[]
  organizationLlmApiKeys           LlmApiKeys[]             @relation("OrganizationLlmApiKeys")
  roleAssignments                  RoleAssignment[]         @relation("RoleAssignmentTenant")

  deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentOrganization") @ignore

  @@map("organizations")
}

model Project {
  id                                String                              @id @default(cuid())
  orgId                             String                              @map("org_id")
  createdAt                         DateTime                            @default(now()) @map("created_at")
  updatedAt                         DateTime                            @default(now()) @updatedAt @map("updated_at")
  deletedAt                         DateTime?                           @map("deleted_at")
  name                              String
  retentionDays                     Int?                                @map("retention_days")
  hasTraces                         Boolean                             @default(false) @map("has_traces")
  metadata                          Json?
  // Which dashboard renders on the project home page; null = the
  // Langfuse-curated default (LANGFUSE_HOME_DASHBOARD_ID).
  homeDashboardId                   String?                             @map("home_dashboard_id")
  homeDashboard                     Dashboard?                          @relation("ProjectHomeDashboard", fields: [homeDashboardId], references: [id], onDelete: SetNull)
  projectMembers                    ProjectMembership[]
  organization                      Organization                        @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
  apiKeys                           ApiKey[]
  roleAssignments                   RoleAssignment[]
  dataset                           Dataset[]
  invitations                       MembershipInvitation[]
  sessions                          TraceSession[]
  Prompt                            Prompt[]
  Skill                             Skill[]
  SkillFile                         SkillFile[]
  SkillBlob                         SkillBlob[]
  Model                             Model[]
  EvalTemplate                      EvalTemplate[]
  JobConfiguration                  JobConfiguration[]
  JobExecution                      JobExecution[]
  Evaluator                         Evaluator[]
  EvaluationRule                    EvaluationRule[]
  EvaluationRuleEvaluatorAssignment EvaluationRuleEvaluatorAssignment[]
  tracingReadinessSettings          TracingReadinessSettings?
  LlmApiKeys                        LlmApiKeys[]
  PosthogIntegration                PosthogIntegration[]
  MixpanelIntegration               MixpanelIntegration[]
  BlobStorageIntegration            BlobStorageIntegration[]
  ExternalMediaStorageIntegration   ExternalMediaStorageIntegration?
  webCalloutEndpoints               WebCalloutEndpoint[]
  scoreConfig                       ScoreConfig[]
  BatchExport                       BatchExport[]
  BatchAction                       BatchAction[]
  comment                           Comment[]
  commentReactions                  CommentReaction[]
  annotationQueue                   AnnotationQueue[]
  annotationQueueItem               AnnotationQueueItem[]
  Media                             Media[]
  PromptDependency                  PromptDependency[]
  LlmSchema                         LlmSchema[]
  LlmTool                           LlmTool[]
  PromptProtectedLabels             PromptProtectedLabels[]
  Dashboard                         Dashboard[]
  DashboardWidget                   DashboardWidget[]
  TableViewPreset                   TableViewPreset[]
  actions                           Action[]
  triggers                          Trigger[]
  automationExecutions              AutomationExecution[]
  Automation                        Automation[]
  monitors                          Monitor[]
  DefaultLlmModel                   DefaultLlmModel[]
  TopicConfig                       TopicConfig?
  Price                             Price[]
  SlackIntegration                  SlackIntegration?
  PendingDeletion                   PendingDeletion[]
  AnnotationQueueAssignment         AnnotationQueueAssignment[]
  NotificationPreference            NotificationPreference[]
  DefaultView                       DefaultView[]
  InAppAgentConversation            InAppAgentConversation[]
  InAppAgentEvent                   InAppAgentEvent[]
  InAppAgentRun                     InAppAgentRun[]
  InAppAgentPendingToolApproval     InAppAgentPendingToolApproval[]
  topicClusteringRuns               TopicClusteringRun[]
  gatewayConfigs                    GatewayConfig[]                     @relation("GatewayDefaultIngestionProject")

  deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentProject") @ignore

  @@index([orgId])
  @@map("projects")
}

enum ApiKeyScope {
  ORGANIZATION
  PROJECT
}

model ApiKey {
  id                  String                    @id @unique @default(cuid())
  createdAt           DateTime                  @default(now()) @map("created_at")
  note                String?
  publicKey           String                    @unique @map("public_key")
  // bcrypt hash for keys created before fastHashedSecretKey existed; newer keys store a non-secret placeholder
  hashedSecretKey     String                    @unique @map("hashed_secret_key")
  fastHashedSecretKey String?                   @unique @map("fast_hashed_secret_key")
  displaySecretKey    String                    @map("display_secret_key")
  lastUsedAt          DateTime?                 @map("last_used_at")
  expiresAt           DateTime?                 @map("expires_at")
  isInAppAgentKey     Boolean                   @default(false) @map("is_in_app_agent_key")
  projectId           String?                   @map("project_id")
  project             Project?                  @relation(fields: [projectId], references: [id], onDelete: Cascade)
  orgId               String?                   @map("organization_id")
  organization        Organization?             @relation(fields: [orgId], references: [id], onDelete: Cascade)
  scope               ApiKeyScope               @default(PROJECT) @map("scope")
  createdByUserId     String?                   @map("created_by_user_id")
  createdByUser       User?                     @relation("ApiKeyCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
  // user the key is bound to; the key is revoked when that user leaves the org
  userId              String?                   @map("user_id")
  user                User?                     @relation("ApiKeyUser", fields: [userId], references: [id], onDelete: Cascade)
  createdByApiKeyId   String?                   @map("created_by_api_key_id")
  createdByApiKey     ApiKey?                   @relation("ApiKeyCreatedByApiKey", fields: [createdByApiKeyId], references: [id], onDelete: SetNull)
  apiKeysCreated      ApiKey[]                  @relation("ApiKeyCreatedByApiKey")
  gatewayAssociation  GatewayApiKeyAssociation?
  roleAssignments     RoleAssignment[]

  deprecatedRoleAssignments RoleAssignment[] @relation("DeprecatedRoleAssignmentApiKey") @ignore

  @@index(orgId)
  @@index(projectId)
  @@index(createdByApiKeyId)
  @@index([userId, orgId])
  @@index(publicKey)
  @@index(hashedSecretKey)
  @@index(fastHashedSecretKey)
  @@map("api_keys")
}

enum SystemRole {
  OWNER
  ADMIN
  MEMBER
  VIEWER
  NONE
  LEGACY_PROJECT_API_KEY
  LEGACY_ORGANIZATION_API_KEY
  SCORES_INGEST
  INGEST
  AI_GATEWAY
}

model RoleAssignment {
  id           String       @id @default(cuid())
  ownerId      String       @map("owner_id")
  projectId    String?      @map("project_id")
  project      Project?     @relation(fields: [projectId], references: [id], onDelete: Cascade)
  orgId        String       @map("org_id")
  organization Organization @relation("RoleAssignmentTenant", fields: [orgId], references: [id], onDelete: Cascade)
  principalId  String       @map("principal_id")
  userId       String?      @map("user_id")
  user         User?        @relation(fields: [userId], references: [id], onDelete: Cascade)
  apiKeyId     String?      @map("api_key_id")
  apiKey       ApiKey?      @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)
  roleId       String       @map("role_id")
  systemRole   SystemRole   @map("system_role")
  createdAt    DateTime     @default(now()) @map("created_at")
  updatedAt    DateTime     @default(now()) @updatedAt @map("updated_at")

  deprecatedOwnerOrgId        String?       @map("owner_org_id") @ignore
  deprecatedOwnerOrg          Organization? @relation("DeprecatedRoleAssignmentOrganization", fields: [deprecatedOwnerOrgId], references: [id], onDelete: Cascade) @ignore
  deprecatedOwnerProjectId    String?       @map("owner_project_id") @ignore
  deprecatedOwnerProject      Project?      @relation("DeprecatedRoleAssignmentProject", fields: [deprecatedOwnerProjectId], references: [id], onDelete: Cascade) @ignore
  deprecatedPrincipalUserId   String?       @map("principal_user_id") @ignore
  deprecatedPrincipalUser     User?         @relation("DeprecatedRoleAssignmentUser", fields: [deprecatedPrincipalUserId], references: [id], onDelete: Cascade) @ignore
  deprecatedPrincipalApiKeyId String?       @map("principal_api_key_id") @ignore
  deprecatedPrincipalApiKey   ApiKey?       @relation("DeprecatedRoleAssignmentApiKey", fields: [deprecatedPrincipalApiKeyId], references: [id], onDelete: Cascade) @ignore

  @@unique([deprecatedPrincipalUserId, deprecatedOwnerOrgId, systemRole], map: "role_assignments_user_org_role_key")
  @@unique([deprecatedPrincipalUserId, deprecatedOwnerProjectId, systemRole], map: "role_assignments_user_project_role_key")
  @@unique([deprecatedPrincipalApiKeyId, deprecatedOwnerOrgId, systemRole], map: "role_assignments_api_key_org_role_key")
  @@unique([deprecatedPrincipalApiKeyId, deprecatedOwnerProjectId, systemRole], map: "role_assignments_api_key_project_role_key")
  @@unique([ownerId, principalId, roleId])
  @@index([deprecatedOwnerOrgId], map: "role_assignments_owner_org_id_idx")
  @@index([deprecatedOwnerProjectId], map: "role_assignments_owner_project_id_idx")
  @@index([orgId])
  @@index([projectId])
  @@index([principalId])
  @@index([userId])
  @@index([apiKeyId])
  @@map("role_assignments")
}

enum GatewayIngestionMode {
  NONE  @map("none")
  USAGE @map("usage")
  FULL  @map("full")
}

enum GatewayProvider {
  OPENAI    @map("openai")
  ANTHROPIC @map("anthropic")
}

enum GatewayConnectionStatus {
  ENABLED  @map("enabled")
  DISABLED @map("disabled")
  ERROR    @map("error")
}

model GatewayConfig {
  organizationId            String               @id @map("organization_id")
  organization              Organization         @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  defaultIngestionProjectId String?              @map("default_ingestion_project_id")
  defaultIngestionProject   Project?             @relation("GatewayDefaultIngestionProject", fields: [defaultIngestionProjectId], references: [id], onDelete: SetNull)
  ingestionMode             GatewayIngestionMode @default(USAGE) @map("ingestion_mode")
  createdAt                 DateTime             @default(now()) @map("created_at")
  updatedAt                 DateTime             @default(now()) @updatedAt @map("updated_at")

  @@map("gateway_configs")
}

model GatewayAiConnection {
  id                  String                  @id @default(cuid())
  organizationId      String                  @map("organization_id")
  organization        Organization            @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  name                String
  provider            GatewayProvider
  encryptedCredential String                  @map("encrypted_credentials")
  displaySecret       String                  @map("display_secret_key")
  createdById         String?                 @map("created_by_id")
  status              GatewayConnectionStatus @default(ENABLED)
  allowedModels       Json?                   @map("allowed_models") @db.JsonB
  createdAt           DateTime                @default(now()) @map("created_at")
  updatedAt           DateTime                @default(now()) @updatedAt @map("updated_at")

  @@unique([organizationId, name])
  @@index([organizationId, createdAt, id], map: "gateway_ai_conn_org_created_at_id_idx")
  @@index([organizationId, status, createdAt, id], map: "gateway_ai_conn_org_status_created_at_id_idx")
  @@map("gateway_ai_connections")
}

model GatewayApiKeyAssociation {
  apiKeyId String @id @map("api_key_id")
  apiKey   ApiKey @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)
  metadata Json   @default("{}") @db.JsonB

  @@map("gateway_api_key_associations")
}

enum InAppAgentConversationVisibilityScope {
  PERSONAL
  PROJECT
}

model InAppAgentConversation {
  id                 String
  projectId          String                                @map("project_id")
  project            Project                               @relation(fields: [projectId], references: [id], onDelete: Cascade)
  createdByUserId    String?                               @map("created_by_user_id")
  createdByUser      User?                                 @relation("InAppAgentConversationCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
  title              String?
  renamedByUserAt    DateTime?                             @map("renamed_by_user_at")
  visibilityScope    InAppAgentConversationVisibilityScope @default(PERSONAL) @map("visibility_scope")
  providerSessionId  String?                               @map("provider_session_id")
  // Prefixed tool grants are revalidated against the registry and owner's role each run.
  alwaysAllowedTools String[]                              @default([]) @map("always_allowed_tools")
  deletedAt          DateTime?                             @map("deleted_at")
  createdAt          DateTime                              @default(now()) @map("created_at")
  updatedAt          DateTime                              @default(now()) @updatedAt @map("updated_at")

  events               InAppAgentEvent[]
  runs                 InAppAgentRun[]
  pendingToolApprovals InAppAgentPendingToolApproval[]

  @@id([id, projectId])
  @@index([projectId, createdByUserId, deletedAt, updatedAt, id], map: "in_app_agent_conversations_project_user_list_idx")
  @@index([projectId, updatedAt], map: "in_app_agent_conversations_project_updated_at_idx")
  @@map("in_app_agent_conversations")
}

model InAppAgentEvent {
  projectId      String                 @map("project_id")
  project        Project                @relation(fields: [projectId], references: [id], onDelete: Cascade)
  conversationId String                 @map("conversation_id")
  conversation   InAppAgentConversation @relation(fields: [conversationId, projectId], references: [id, projectId], onDelete: Cascade)
  runId          String                 @map("run_id")
  run            InAppAgentRun          @relation(fields: [runId, projectId], references: [id, projectId], onDelete: Cascade)
  sequenceNumber Int                    @map("sequence_number")
  type           String
  event          Json                   @db.JsonB
  createdAt      DateTime               @default(now()) @map("created_at")

  @@id([projectId, conversationId, sequenceNumber])
  @@index([projectId, runId], map: "in_app_agent_events_project_run_idx")
  @@map("in_app_agent_events")
}

model InAppAgentRun {
  id                String
  projectId         String                 @map("project_id")
  project           Project                @relation(fields: [projectId], references: [id], onDelete: Cascade)
  conversationId    String                 @map("conversation_id")
  conversation      InAppAgentConversation @relation(fields: [conversationId, projectId], references: [id, projectId], onDelete: Cascade)
  triggeredByUserId String?                @map("triggered_by_user_id")
  triggeredByUser   User?                  @relation("InAppAgentRunTriggeredByUser", fields: [triggeredByUserId], references: [id], onDelete: SetNull)
  model             String?
  mcpApiKeyId       String?                @map("mcp_api_key_id")
  errorCode         String?                @map("error_code")
  errorMessage      String?                @map("error_message")
  finishedAt        DateTime?              @map("finished_at")
  // Nullable until the first status reader ships (see RFC-background-execution
  // PR 4), whose migration backfills NULLs and sets DEFAULT/NOT NULL.
  // NULL means "row written by code that predates the status column".
  status            String?
  request           Json?
  claimedAt         DateTime?              @map("claimed_at")
  heartbeatAt       DateTime?              @map("heartbeat_at")
  cancelRequestedAt DateTime?              @map("cancel_requested_at")
  createdAt         DateTime               @default(now()) @map("created_at")
  updatedAt         DateTime               @default(now()) @updatedAt @map("updated_at")

  events InAppAgentEvent[]

  // A conversation can have at most one unfinished run, enforced via the
  // partial unique index in_app_agent_runs_active_conversation_key on
  // (project_id, conversation_id) WHERE finished_at IS NULL, added in the
  // migration since Prisma cannot express partial uniqueness in the schema DSL.
  @@id([id, projectId])
  @@index([projectId, conversationId, createdAt], map: "in_app_agent_runs_project_conversation_created_idx")
  @@map("in_app_agent_runs")
}

model InAppAgentPendingToolApproval {
  // Background execution never reads or writes this table. Retain it
  // temporarily so existing rows and relations remain valid.
  projectId           String                 @map("project_id")
  project             Project                @relation(fields: [projectId], references: [id], onDelete: Cascade)
  conversationId      String                 @map("conversation_id")
  conversation        InAppAgentConversation @relation(fields: [conversationId, projectId], references: [id, projectId], onDelete: Cascade)
  toolCallId          String                 @map("tool_call_id")
  approvalFingerprint String                 @map("approval_fingerprint")
  expiresAt           DateTime               @map("expires_at")
  createdAt           DateTime               @default(now()) @map("created_at")
  updatedAt           DateTime               @default(now()) @updatedAt @map("updated_at")

  @@id([projectId, conversationId, toolCallId])
  @@index([expiresAt], map: "in_app_agent_pending_tool_approvals_expires_at_idx")
  @@map("in_app_agent_pending_tool_approvals")
}

model BackgroundMigration {
  id           String    @id @default(cuid())
  name         String    @unique
  script       String    @map("script")
  args         Json      @map("args")
  state        Json      @default("{}") @map("state")
  finishedAt   DateTime? @map("finished_at")
  failedAt     DateTime? @map("failed_at")
  failedReason String?   @map("failed_reason")
  workerId     String?   @map("worker_id")
  lockedAt     DateTime? @map("locked_at")

  @@map("background_migrations")
}

model LlmApiKeys {
  id        String   @id @unique @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  provider          String
  adapter           String // This controls the interface that is used to connect with the LLM, e.g. 'openai' or 'anthropic'
  displaySecretKey  String   @map("display_secret_key")
  secretKey         String   @map("secret_key")
  baseURL           String?  @map("base_url")
  customModels      String[] @default([]) @map("custom_models")
  withDefaultModels Boolean  @default(true) @map("with_default_models")
  extraHeaders      String?  @map("extra_headers")
  extraHeaderKeys   String[] @default([]) @map("extra_header_keys")
  config            Json?

  projectId      String?       @map("project_id")
  project        Project?      @relation(fields: [projectId], references: [id], onDelete: Cascade)
  organizationId String?       @map("organization_id")
  organization   Organization? @relation("OrganizationLlmApiKeys", fields: [organizationId], references: [id], onDelete: Cascade)

  DefaultLlmModel DefaultLlmModel[] @relation("LlmApiKeyId")
  topicSummaryConfigs    TopicConfig[] @relation("TopicConfigSummaryLlmApiKey")
  topicEmbeddingConfigs  TopicConfig[] @relation("TopicConfigEmbeddingLlmApiKey")
  topicClusteringConfigs TopicConfig[] @relation("TopicConfigClusteringLlmApiKey")

  @@unique([projectId, provider])
  @@unique([organizationId, provider])
  @@map("llm_api_keys")
}

model OrganizationMembership {
  id                 String              @id @default(cuid())
  orgId              String              @map("org_id")
  organization       Organization        @relation(fields: [orgId], references: [id], onDelete: Cascade)
  userId             String              @map("user_id")
  user               User                @relation(fields: [userId], references: [id], onDelete: Cascade)
  role               Role                @map("role")
  createdAt          DateTime            @default(now()) @map("created_at")
  updatedAt          DateTime            @default(now()) @updatedAt @map("updated_at")
  ProjectMemberships ProjectMembership[]

  @@unique([orgId, userId])
  @@index([userId])
  @@map("organization_memberships")
}

// Set a project-specific role for a user in an organization
model ProjectMembership {
  orgMembershipId        String                 @map("org_membership_id")
  organizationMembership OrganizationMembership @relation(fields: [orgMembershipId], references: [id], onDelete: Cascade)
  projectId              String                 @map("project_id")
  project                Project                @relation(fields: [projectId], references: [id], onDelete: Cascade)
  userId                 String                 @map("user_id")
  user                   User                   @relation(fields: [userId], references: [id], onDelete: Cascade)
  role                   Role
  createdAt              DateTime               @default(now()) @map("created_at")
  updatedAt              DateTime               @default(now()) @updatedAt @map("updated_at")

  @@id([projectId, userId])
  @@index([userId])
  @@index([projectId])
  @@index([orgMembershipId])
  @@map("project_memberships")
}

model MembershipInvitation {
  id              String       @id @unique @default(cuid())
  email           String
  orgId           String       @map("org_id")
  organization    Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
  orgRole         Role         @map("org_role")
  projectId       String?      @map("project_id")
  project         Project?     @relation(fields: [projectId], references: [id], onDelete: SetNull)
  projectRole     Role?        @map("project_role")
  invitedByUserId String?      @map("invited_by_user_id")
  invitedByUser   User?        @relation(fields: [invitedByUserId], references: [id], onDelete: SetNull)
  createdAt       DateTime     @default(now()) @map("created_at")
  updatedAt       DateTime     @default(now()) @updatedAt @map("updated_at")

  @@unique([email, orgId]) // do not include projectId as this leads to issues when processing the invites, needs new logic
  @@index([projectId])
  @@index([orgId])
  @@index([email])
  @@map("membership_invitations")
}

enum Role {
  OWNER
  ADMIN
  MEMBER
  VIEWER
  NONE
  AI_GATEWAY
}

model TraceSession {
  id          String   @default(cuid())
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @default(now()) @updatedAt @map("updated_at")
  projectId   String   @map("project_id")
  project     Project  @relation(fields: [projectId], references: [id], onDelete: Cascade)
  bookmarked  Boolean  @default(false)
  public      Boolean  @default(false)
  environment String   @default("default")

  @@id([id, projectId])
  @@index([projectId, createdAt(sort: Desc)])
  @@map("trace_sessions")
}

model ScoreConfig {
  id          String              @id @default(cuid())
  createdAt   DateTime            @default(now()) @map("created_at")
  updatedAt   DateTime            @default(now()) @updatedAt @map("updated_at")
  projectId   String              @map("project_id")
  project     Project             @relation(fields: [projectId], references: [id], onDelete: Cascade)
  name        String
  dataType    ScoreConfigDataType @map("data_type")
  isArchived  Boolean             @default(false) @map("is_archived")
  minValue    Float?              @map("min_value")
  maxValue    Float?              @map("max_value")
  categories  Json?               @map("categories")
  description String?

  @@unique([id, projectId]) // used for upserts via prisma
  @@index([dataType])
  @@index([isArchived])
  @@index([projectId])
  @@index([categories])
  @@index([createdAt])
  @@index([updatedAt])
  @@map("score_configs")
}

enum ScoreConfigDataType {
  CATEGORICAL
  NUMERIC
  BOOLEAN
  TEXT
}

model AnnotationQueue {
  id                        String                      @id @default(cuid())
  name                      String
  description               String?
  scoreConfigIds            String[]                    @default([]) @map("score_config_ids")
  projectId                 String                      @map("project_id")
  project                   Project                     @relation(fields: [projectId], references: [id], onDelete: Cascade)
  createdAt                 DateTime                    @default(now()) @map("created_at")
  updatedAt                 DateTime                    @default(now()) @updatedAt @map("updated_at")
  annotationQueueItem       AnnotationQueueItem[]
  annotationQueueAssignment AnnotationQueueAssignment[]

  @@unique([projectId, name])
  @@index([id, projectId])
  @@index([projectId, createdAt])
  @@map("annotation_queues")
}

model AnnotationQueueItem {
  id              String                    @id @default(cuid())
  queueId         String                    @map("queue_id")
  queue           AnnotationQueue           @relation(fields: [queueId], references: [id], onDelete: Cascade)
  objectId        String                    @map("object_id")
  objectType      AnnotationQueueObjectType @map("object_type")
  status          AnnotationQueueStatus     @default(PENDING)
  lockedAt        DateTime?                 @map("locked_at")
  lockedByUserId  String?                   @map("locked_by_user_id")
  lockedByUser    User?                     @relation("LockedByUser", fields: [lockedByUserId], references: [id], onDelete: SetNull)
  annotatorUserId String?                   @map("annotator_user_id")
  annotatorUser   User?                     @relation("AnnotatorUser", fields: [annotatorUserId], references: [id], onDelete: SetNull)
  completedAt     DateTime?                 @map("completed_at")
  projectId       String                    @map("project_id")
  project         Project                   @relation(fields: [projectId], references: [id], onDelete: Cascade)
  createdAt       DateTime                  @default(now()) @map("created_at")
  updatedAt       DateTime                  @default(now()) @updatedAt @map("updated_at")

  @@index([id, projectId])
  @@index([projectId, queueId, status])
  @@index([objectId, objectType, projectId, queueId])
  @@index([annotatorUserId])
  @@index([createdAt])
  @@map("annotation_queue_items")
}

enum AnnotationQueueStatus {
  PENDING
  COMPLETED
}

enum AnnotationQueueObjectType {
  TRACE
  OBSERVATION
  SESSION
}

model AnnotationQueueAssignment {
  id        String          @id @default(cuid())
  projectId String          @map("project_id")
  project   Project         @relation(fields: [projectId], references: [id], onDelete: Cascade)
  userId    String          @map("user_id")
  user      User            @relation(fields: [userId], references: [id], onDelete: Cascade)
  queueId   String          @map("queue_id")
  queue     AnnotationQueue @relation(fields: [queueId], references: [id], onDelete: Cascade)
  createdAt DateTime        @default(now()) @map("created_at")
  updatedAt DateTime        @default(now()) @updatedAt @map("updated_at")

  @@unique([projectId, queueId, userId])
  @@map("annotation_queue_assignments")
}

model CronJobs {
  name         String    @id
  lastRun      DateTime? @map("last_run")
  jobStartedAt DateTime? @map("job_started_at")
  state        String?

  @@map("cron_jobs")
}

model Dataset {
  id                               String        @default(cuid())
  projectId                        String        @map("project_id")
  name                             String
  description                      String?
  metadata                         Json?
  remoteExperimentUrl              String?       @map("remote_experiment_url")
  remoteExperimentPayload          Json?         @map("remote_experiment_payload")
  remoteExperimentEnabled          Boolean       @default(true) @map("remote_experiment_enabled")
  // Signing secret and custom request headers for the remote experiment trigger.
  // SecretKey and secret header values are encrypted at rest; the client omits
  // remoteExperimentSecretKey and remoteExperimentRequestHeaders globally
  // (see db.ts) so only the delivery path can select them explicitly.
  remoteExperimentSecretKey        String?       @map("remote_experiment_secret_key")
  remoteExperimentDisplaySecretKey String?       @map("remote_experiment_display_secret_key")
  remoteExperimentRequestHeaders   Json?         @map("remote_experiment_request_headers")
  remoteExperimentDisplayHeaders   Json?         @map("remote_experiment_display_headers")
  inputSchema                      Json?         @map("input_schema") @db.Json
  expectedOutputSchema             Json?         @map("expected_output_schema") @db.Json
  project                          Project       @relation(fields: [projectId], references: [id], onDelete: Cascade)
  createdAt                        DateTime      @default(now()) @map("created_at")
  updatedAt                        DateTime      @default(now()) @updatedAt @map("updated_at")
  datasetItems                     DatasetItem[]
  datasetRuns                      DatasetRuns[]

  @@id([id, projectId])
  @@unique([projectId, name])
  @@index([createdAt])
  @@index([updatedAt])
  @@map("datasets")
}

model DatasetItem {
  id                  String         @default(cuid())
  projectId           String         @map("project_id")
  status              DatasetStatus? @default(ACTIVE)
  input               Json?
  expectedOutput      Json?          @map("expected_output")
  metadata            Json?
  sourceTraceId       String?        @map("source_trace_id")
  sourceObservationId String?        @map("source_observation_id")
  datasetId           String         @map("dataset_id")
  dataset             Dataset        @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)
  createdAt           DateTime       @default(now()) @map("created_at")
  updatedAt           DateTime       @default(now()) @updatedAt @map("updated_at")
  // dataset version cols
  validFrom           DateTime       @default(now()) @map("valid_from")
  validTo             DateTime?      @map("valid_to")
  isDeleted           Boolean        @default(false) @map("is_deleted")

  @@id([id, projectId, validFrom])
  @@index([projectId, validTo])
  @@index([projectId, id, validFrom])
  @@index([sourceTraceId], type: Hash)
  @@index([sourceObservationId], type: Hash)
  @@index([datasetId], type: Hash)
  @@index([createdAt])
  @@index([updatedAt])
  @@map("dataset_items")
}

enum DatasetStatus {
  ACTIVE
  ARCHIVED
}

model DatasetRuns {
  id          String   @default(cuid())
  projectId   String   @map("project_id")
  name        String
  description String?
  metadata    Json?
  datasetId   String   @map("dataset_id")
  dataset     Dataset  @relation(fields: [datasetId, projectId], references: [id, projectId], onDelete: Cascade)
  createdAt   DateTime @default(now()) @map("created_at")
  updatedAt   DateTime @default(now()) @updatedAt @map("updated_at")

  @@id([id, projectId])
  @@unique([datasetId, projectId, name])
  @@index([datasetId], type: Hash)
  @@index([createdAt])
  @@index([updatedAt])
  @@map("dataset_runs")
}

model Comment {
  id           String            @id @default(cuid())
  projectId    String            @map("project_id")
  project      Project           @relation(fields: [projectId], references: [id], onDelete: Cascade)
  objectType   CommentObjectType @map("object_type")
  objectId     String            @map("object_id")
  createdAt    DateTime          @default(now()) @map("created_at")
  updatedAt    DateTime          @default(now()) @updatedAt @map("updated_at")
  content      String
  authorUserId String?           @map("author_user_id") // no fk constraint, user can be deleted
  reactions    CommentReaction[]

  // Inline comment positioning (all must be set together or all null/empty)
  // dataField: which IO field the comment is on ('input' | 'output' | 'metadata')
  // path: Array of JSON Path expressions, e.g., ["$.messages[1].text"]
  // rangeStart/rangeEnd: parallel arrays for start/end offsets per path (exclusive end, UTF-16 code units)
  dataField  String?  @map("data_field")
  path       String[] @default([]) @map("path")
  rangeStart Int[]    @default([]) @map("range_start")
  rangeEnd   Int[]    @default([]) @map("range_end")

  @@index([projectId, objectType, objectId])
  @@map("comments")
}

model CommentReaction {
  id        String   @id @default(cuid())
  projectId String   @map("project_id")
  project   Project  @relation(fields: [projectId], references: [id], onDelete: Cascade)
  commentId String   @map("comment_id")
  comment   Comment  @relation(fields: [commentId], references: [id], onDelete: Cascade)
  userId    String   @map("user_id")
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  emoji     String // Unicode emoji (e.g., "👍", "❤️")
  createdAt DateTime @default(now()) @map("created_at")

  @@unique([commentId, userId, emoji])
  @@map("comment_reactions")
}

enum CommentObjectType {
  TRACE
  OBSERVATION
  SESSION
  PROMPT
}

enum NotificationChannel {
  EMAIL
  // Extend by adding: IN_APP, SLACK
}

enum NotificationType {
  COMMENT_MENTION
  // Extend by adding: COMMENT_REPLY, COMMENT_NEW, EVAL_COMPLETE, EXPORT_READY
}

model NotificationPreference {
  id        String  @id @default(cuid())
  userId    String  @map("user_id")
  user      User    @relation(fields: [userId], references: [id], onDelete: Cascade)
  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  channel NotificationChannel
  type    NotificationType
  enabled Boolean             @default(true)

  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@unique([userId, projectId, channel, type])
  @@map("notification_preferences")
}

model Prompt {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  createdBy String @map("created_by")

  prompt           Json
  name             String
  version          Int
  type             String             @default("text")
  isActive         Boolean?           @map("is_active") // Deprecated. To be removed once 'production' labels work as expected.
  config           Json               @default("{}") @db.Json
  tags             String[]           @default([])
  labels           String[]           @default([])
  commitMessage    String?            @map("commit_message")
  PromptDependency PromptDependency[]

  @@unique([projectId, name, version])
  @@index([projectId, id])
  @@index([createdAt])
  @@index([updatedAt])
  @@index([tags(ops: ArrayOps)], type: Gin)
  @@map("prompts")
}

model PromptDependency {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  parentId String @map("parent_id")
  parent   Prompt @relation(fields: [parentId], references: [id], onDelete: Cascade)

  childName    String  @map("child_name")
  childLabel   String? @map("child_label")
  childVersion Int?    @map("child_version")

  @@index([projectId, parentId], map: "prompt_dependencies_project_id_parent_id")
  @@index([projectId, childName], map: "prompt_dependencies_project_id_child_name")
  @@map("prompt_dependencies")
}

model PromptProtectedLabels {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
  projectId String   @map("project_id")
  project   Project  @relation(fields: [projectId], references: [id], onDelete: Cascade)
  label     String

  @@unique([projectId, label])
  @@map("prompt_protected_labels")
}

model Skill {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  createdBy     String      @map("created_by")
  name          String
  description   String
  frontmatter   Json        @default("{}")
  version       Int
  tags          String[]    @default([])
  labels        String[]    @default([])
  commitMessage String?     @map("commit_message")
  files         SkillFile[]

  @@unique([projectId, name, version])
  @@index([createdAt])
  @@index([updatedAt])
  @@index([tags(ops: ArrayOps)], type: Gin)
  @@index([labels(ops: ArrayOps)], type: Gin)
  @@map("skills")
}

model SkillFile {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  skillId String @map("skill_id")
  skill   Skill  @relation(fields: [skillId], references: [id], onDelete: Cascade)

  blobId String    @map("blob_id")
  blob   SkillBlob @relation(fields: [blobId], references: [id], onDelete: Restrict)

  path String

  @@unique([projectId, skillId, path])
  @@index([projectId, blobId])
  @@map("skill_files")
}

model SkillBlob {
  id         String    @id @default(cuid())
  createdAt  DateTime  @default(now()) @map("created_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  sha256Hash    String @map("sha_256_hash") @db.Char(44)
  contentType   String @map("content_type")
  contentLength Int @map("content_length")
  content       String @db.Text

  files SkillFile[]

  @@unique([projectId, sha256Hash])
  @@map("skill_blobs")
}

// Update ObservationView below when making changes to this model!
model Model {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String?  @map("project_id")
  project   Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)

  modelName       String        @map("model_name")
  matchPattern    String        @map("match_pattern")
  startDate       DateTime?     @map("start_date")
  inputPrice      Decimal?      @map("input_price")
  outputPrice     Decimal?      @map("output_price")
  totalPrice      Decimal?      @map("total_price")
  unit            String? // TOKENS, CHARACTERS, MILLISECONDS, SECONDS, REQUESTS, or IMAGES
  tokenizerId     String?       @map("tokenizer_id")
  tokenizerConfig Json?         @map("tokenizer_config")
  Price           Price[]
  pricingTiers    PricingTier[]

  @@unique([projectId, modelName, startDate, unit])
  @@index(modelName)
  @@map("models")
}

model Price {
  id            String      @id @default(cuid())
  createdAt     DateTime    @default(now()) @map("created_at")
  updatedAt     DateTime    @default(now()) @updatedAt @map("updated_at")
  modelId       String      @map("model_id") // Model is already linked to project (or default), so we don't need projectId here
  Model         Model       @relation(fields: [modelId], references: [id], onDelete: Cascade)
  projectId     String?     @map("project_id")
  project       Project?    @relation(fields: [projectId], references: [id], onDelete: Cascade)
  pricingTierId String      @map("pricing_tier_id")
  pricingTier   PricingTier @relation(fields: [pricingTierId], references: [id], onDelete: Cascade)
  usageType     String      @map("usage_type")
  price         Decimal

  @@unique([modelId, usageType, pricingTierId])
  @@index(pricingTierId)
  @@map("prices")
}

model PricingTier {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  modelId String @map("model_id")
  model   Model  @relation(fields: [modelId], references: [id], onDelete: Cascade)

  name       String  @map("name")
  isDefault  Boolean @default(false) @map("is_default")
  priority   Int     @map("priority")
  conditions Json    @map("conditions") @db.JsonB

  prices Price[]

  @@unique([modelId, priority])
  @@unique([modelId, name])
  @@map("pricing_tiers")
}

enum AuditLogRecordType {
  USER
  API_KEY
}

// No FK constraints to preserve audit logs
model AuditLog {
  id              String             @id @default(cuid())
  createdAt       DateTime           @default(now()) @map("created_at")
  updatedAt       DateTime           @default(now()) @updatedAt @map("updated_at")
  type            AuditLogRecordType @default(USER)
  apiKeyId        String?            @map("api_key_id")
  userId          String?            @map("user_id")
  orgId           String             @map("org_id")
  userOrgRole     String?            @map("user_org_role")
  projectId       String?            @map("project_id")
  userProjectRole String?            @map("user_project_role")
  resourceType    String             @map("resource_type")
  resourceId      String             @map("resource_id")
  action          String
  before          String? // stringified JSON
  after           String? // stringified JSON

  @@index([projectId])
  @@index([apiKeyId])
  @@index([userId])
  @@index([orgId])
  @@index([createdAt])
  @@index([updatedAt])
  @@map("audit_logs")
}

// Outbox for audit events on their way to the ClickHouse `audit_logs` table.
// A row is deleted once ClickHouse has acknowledged its insert, so the table
// stays near-empty. `payload` holds an `AuditLogStagingPayload`.
model AuditLogStaging {
  id        String    @id @db.Uuid // UUIDv7, so id order follows creation time
  createdAt DateTime  @default(now()) @map("created_at")
  payload   Json
  // Set when the relay could not map `payload` to a ClickHouse row. The row
  // stays and is retried after a delay, e.g. once a newer worker that knows
  // its schema is deployed.
  failedAt  DateTime? @map("failed_at")
  lastError String?   @map("last_error")

  @@map("audit_log_staging")
}

model EvalTemplate {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String?  @map("project_id")
  project   Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name    String
  version Int
  prompt  String?
  type    EvalTemplateType @default(LLM_AS_JUDGE)

  partner String? // e.g. "ragas", describes the partner that created the template

  model              String?
  provider           String?
  modelParams        Json?                           @map("model_params")
  vars               String[]                        @default([])
  outputDefinition   Json?                           @map("output_schema")
  sourceCode         String?                         @map("source_code") @db.VarChar(262144)
  sourceCodeLanguage EvalTemplateSourceCodeLanguage? @map("source_code_language")
  JobConfiguration   JobConfiguration[]

  @@unique([projectId, name, version])
  @@index([projectId, id])
  @@map("eval_templates")
}

model Evaluator {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name            String
  type            EvalTemplateType
  isBuiltIn       Boolean              @default(false) @map("is_built_in")
  description     String?
  createdByUserId String?               @map("created_by_user_id")
  createdByUser   User?                 @relation("EvaluatorCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
  blockedAt       DateTime?             @map("blocked_at")
  blockReason     EvaluatorBlockReason? @map("block_reason")
  blockMessage    String?               @map("block_message")

  versions    EvaluatorVersion[]
  assignments EvaluationRuleEvaluatorAssignment[]

  @@index([projectId, createdAt(sort: Desc)])
  @@map("evaluators")
}

model EvaluatorVersion {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")

  evaluatorId String    @map("evaluator_id")
  evaluator   Evaluator @relation(fields: [evaluatorId], references: [id], onDelete: Cascade)
  version     Int

  createdByUserId String? @map("created_by_user_id")
  createdByUser   User?   @relation("EvaluatorVersionCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)

  prompt             String?
  promptMessages     Json?                        @map("prompt_messages")
  partner            String?
  model              String?
  provider           String?
  modelParams        Json?                        @map("model_params")
  vars               String[]                     @default([])
  variableMapping    Json?                        @map("variable_mapping")
  outputDefinition   Json?                        @map("output_definition")
  sourceCode         String?                      @map("source_code") @db.VarChar(262144)
  sourceCodeLanguage EvaluatorSourceCodeLanguage? @map("source_code_language")
  questions          Json?

  topicClusteringRuns TopicClusteringRun[]

  @@unique([evaluatorId, version(sort: Desc)])
  @@map("evaluator_versions")
}

enum EvalTemplateType {
  LLM_AS_JUDGE
  CODE
  DECISION_MODEL
  FACET
}

enum EvalTemplateSourceCodeLanguage {
  PYTHON
  TYPESCRIPT
}

enum EvaluatorSourceCodeLanguage {
  PYTHON
  TYPESCRIPT
}

// We currently assume in evaluator execution-count queries that _all_ job_executions are for EVAL job_configs.
// If we ever extend this, we need to adjust the filter condition there. ref.: getEvaluatorExecutionStatusCounts.
enum JobType {
  EVAL
}

enum JobConfigState {
  ACTIVE
  INACTIVE
}

enum EvaluatorBlockReason {
  LLM_CONNECTION_AUTH_INVALID
  LLM_CONNECTION_BILLING_EXHAUSTED
  LLM_CONNECTION_ENDPOINT_UNREACHABLE
  LLM_CONNECTION_MISSING
  DEFAULT_EVAL_MODEL_MISSING
  EVAL_MODEL_CONFIG_INVALID
  EVAL_MODEL_UNAVAILABLE
  PROVIDER_ACCOUNT_NOT_READY
}

model JobConfiguration {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  jobType        JobType               @map("job_type")
  status         JobConfigState        @default(ACTIVE)
  blockedAt      DateTime?             @map("blocked_at")
  blockReason    EvaluatorBlockReason? @map("block_reason")
  blockMessage   String?               @map("block_message")
  evalTemplateId String?               @map("eval_template_id")
  evalTemplate   EvalTemplate?         @relation(fields: [evalTemplateId], references: [id], onDelete: SetNull)

  scoreName       String   @map("score_name")
  filter          Json
  targetObject    String   @map("target_object")
  variableMapping Json     @map("variable_mapping")
  sampling        Decimal // ratio of jobs that are executed for sampling (0..1)
  delay           Int // delay in milliseconds
  timeScope       String[] @default(["NEW"]) @map("time_scope")

  @@index([projectId, id])
  @@map("job_configurations")
}

model EvaluationRule {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  createdByUserId String?        @map("created_by_user_id")
  createdByUser   User?          @relation("EvaluationRuleCreatedByUser", fields: [createdByUserId], references: [id], onDelete: SetNull)
  name            String
  status          JobConfigState @default(ACTIVE)
  targetObject    String         @map("target_object")
  filter          Json
  sampling        Decimal
  delay           Int
  // Unused; kept until no deployed version selects it, then dropped.
  idleTime        Int?           @map("idle_time") // milliseconds
  timeScope       String[]       @default(["NEW"]) @map("time_scope")

  assignments EvaluationRuleEvaluatorAssignment[]

  @@index([projectId, updatedAt(sort: Desc)])
  @@map("evaluation_rules")
}

// When tracing data is ready for downstream work (Topics, trace-level
// evaluations). One row per project; null columns fall back to the deployment
// default. Session settings join as their own nullable columns.
model TracingReadinessSettings {
  projectId String   @id @map("project_id")
  project   Project  @relation(fields: [projectId], references: [id], onDelete: Cascade)
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  createdBy     String? @map("created_by")
  createdByUser User?   @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)
  updatedBy     String? @map("updated_by")
  updatedByUser User?   @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)

  // A trace is due this long after its latest event. Null uses
  // LANGFUSE_TRACE_BATCH_IDLE_MS. Bounds are enforced on write, not in the DB.
  traceIdleMs Int? @map("trace_idle_ms")

  @@map("tracing_readiness_settings")
}

model EvaluationRuleEvaluatorAssignment {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  evaluationRuleId String         @map("evaluation_rule_id")
  evaluationRule   EvaluationRule @relation(fields: [evaluationRuleId], references: [id], onDelete: Cascade)
  evaluatorId      String         @map("evaluator_id")
  evaluator        Evaluator      @relation(fields: [evaluatorId], references: [id], onDelete: Cascade)
  variableMapping  Json?          @map("variable_mapping")

  @@unique([evaluationRuleId, evaluatorId], map: "evaluation_rule_assignments_rule_evaluator_key")
  @@index([projectId], map: "evaluation_rule_assignments_project_id_idx") // for efficient project deletes
  @@index([evaluatorId], map: "evaluation_rule_assignments_evaluator_id_idx")
  @@map("evaluation_rule_evaluator_assignments")
}

enum JobExecutionStatus {
  COMPLETED
  ERROR
  PENDING
  CANCELLED
  DELAYED
}

model JobExecution {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  jobConfigurationId String @map("job_configuration_id") // no fk constraint - deletion handled in application code (deleteJobConfigurationWithExecutions) and via project cascade

  jobTemplateId String? @map("job_template_id")

  status    JobExecutionStatus
  startTime DateTime?          @map("start_time")
  endTime   DateTime?          @map("end_time")
  error     String?

  jobInputTraceId String? @map("job_input_trace_id") // no fk constraint - traces in ClickHouse, deletion handled via project cascade

  jobInputTraceTimestamp DateTime? @map("job_input_trace_timestamp")

  jobInputObservationId String? @map("job_input_observation_id") // no fk constraint - observations in ClickHouse, deletion handled via project cascade

  jobInputDatasetItemId String? @map("job_input_dataset_item_id") // no fk constraint - job execution sensible standalone

  jobInputDatasetItemValidFrom DateTime? @map("job_input_dataset_item_valid_from")

  jobOutputScoreId String? @map("job_output_score_id")

  executionTraceId String? @map("execution_trace_id")

  @@index([projectId, jobConfigurationId, jobInputTraceId])
  @@index([projectId, jobOutputScoreId])
  @@index([jobConfigurationId])
  @@map("job_executions")
}

model DefaultLlmModel {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  Project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  llmApiKeyId String     @map("llm_api_key_id")
  LlmApiKey   LlmApiKeys @relation("LlmApiKeyId", fields: [llmApiKeyId], references: [id], onDelete: Cascade)

  provider    String
  adapter     String // This controls the interface that is used to connect with the LLM, e.g. 'openai' or 'anthropic'
  model       String
  modelParams Json?  @map("model_params")

  @@unique([projectId])
  @@map("default_llm_models")
}

// Per-project Topics configuration: the switch, pause state, and the three model
// slots, each referencing one of the project's LLM connections.
model TopicConfig {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  createdBy     String? @map("created_by")
  createdByUser User?   @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)
  updatedBy     String? @map("updated_by")
  updatedByUser User?   @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)

  projectId String  @unique @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  // Kill switch for automatic trace processing; facet rules are kept while off.
  enabled Boolean @default(false)
  // Same columns as Evaluator, set when a configured connection is no longer valid.
  blockedAt    DateTime?             @map("blocked_at")
  blockReason  EvaluatorBlockReason? @map("block_reason")
  blockMessage String?               @map("block_message")

  summaryLlmApiKeyId String?     @map("summary_llm_api_key_id")
  summaryLlmApiKey   LlmApiKeys? @relation("TopicConfigSummaryLlmApiKey", fields: [summaryLlmApiKeyId], references: [id], onDelete: SetNull)
  summaryModel       String?     @map("summary_model")

  embeddingLlmApiKeyId String?     @map("embedding_llm_api_key_id")
  embeddingLlmApiKey   LlmApiKeys? @relation("TopicConfigEmbeddingLlmApiKey", fields: [embeddingLlmApiKeyId], references: [id], onDelete: SetNull)
  embeddingModel       String?     @map("embedding_model")
  embeddingDimensions  Int         @default(1024) @map("embedding_dimensions")

  // Names and describes each cluster during Update topics.
  clusteringLlmApiKeyId String?     @map("clustering_llm_api_key_id")
  clusteringLlmApiKey   LlmApiKeys? @relation("TopicConfigClusteringLlmApiKey", fields: [clusteringLlmApiKeyId], references: [id], onDelete: SetNull)
  clusteringModel       String?     @map("clustering_model")

  @@index([summaryLlmApiKeyId])
  @@index([embeddingLlmApiKeyId])
  @@index([clusteringLlmApiKeyId])
  @@map("topic_configs")
}

// Single Sign-On configuration for a domain
// This feature is part of the Enterprise Edition
model SsoConfig {
  domain       String   @id @default(cuid()) // e.g. "google.com"
  createdAt    DateTime @default(now()) @map("created_at")
  updatedAt    DateTime @default(now()) @updatedAt @map("updated_at")
  authProvider String   @map("auth_provider") // e.g. "okta", ee/sso/types.ts

  authConfig Json? @map("auth_config")

  // e.g. { "clientId": "1234", "clientSecret": "5678" }, null if credentials from env should be used
  // secrets like clientSecret are encrypted on the application level
  @@map("sso_configs")
}

// Domain ownership claim for an organization, verified via DNS TXT record.
// Required before an SsoConfig can be created for that domain.
model VerifiedDomain {
  id                String       @id @default(uuid())
  organizationId    String       @map("organization_id")
  organization      Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  domain            String
  verificationToken String       @unique @default(uuid()) @map("verification_token")
  verifiedAt        DateTime?    @map("verified_at")
  createdByUserId   String?      @map("created_by_user_id")
  createdAt         DateTime     @default(now()) @map("created_at")
  updatedAt         DateTime     @default(now()) @updatedAt @map("updated_at")

  // A domain can have at most one pending claim per org (idempotency for
  // create) and at most one verified claim across the whole instance
  // (enforced via a partial unique index added in the migration, since
  // Prisma cannot express partial uniqueness in the schema DSL).
  @@unique([organizationId, domain])
  @@index([organizationId])
  @@map("verified_domains")
}

model PosthogIntegration {
  projectId              String                           @id @map("project_id")
  project                Project                          @relation(fields: [projectId], references: [id], onDelete: Cascade)
  encryptedPosthogApiKey String                           @map("encrypted_posthog_api_key")
  posthogHostName        String                           @map("posthog_host_name")
  lastSyncAt             DateTime?                        @map("last_sync_at")
  enabled                Boolean
  createdAt              DateTime                         @default(now()) @map("created_at")
  exportSource           AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")

  // True while the integration is exporting history (new, re-enabled, or export
  // mode reset), so the export staleness gauge can separate it from steady
  // state. Cleared by the worker once a run lands within an hour of its start.
  backfill               Boolean                          @default(true)

  // Last deterministic customer-config fault (bad hostname) that disabled the
  // integration. Written by the worker, surfaced in the integration settings
  // status section, and cleared on a successful run.
  lastError   String?   @map("last_error")
  lastErrorAt DateTime? @map("last_error_at")

  @@map("posthog_integrations")
}

model MixpanelIntegration {
  projectId                     String                           @id @map("project_id")
  project                       Project                          @relation(fields: [projectId], references: [id], onDelete: Cascade)
  encryptedMixpanelProjectToken String                           @map("encrypted_mixpanel_project_token")
  mixpanelRegion                String                           @map("mixpanel_region")
  lastSyncAt                    DateTime?                        @map("last_sync_at")
  enabled                       Boolean
  createdAt                     DateTime                         @default(now()) @map("created_at")
  exportSource                  AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")

  // True while the integration is exporting history (new, re-enabled, or export
  // mode reset), so the export staleness gauge can separate it from steady
  // state. Cleared by the worker once a run lands within an hour of its start.
  backfill                      Boolean                          @default(true)

  @@map("mixpanel_integrations")
}

model BlobStorageIntegration {
  projectId String  @id @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  // Blob Storage Config
  type            BlobStorageIntegrationType @map("type")
  bucketName      String                     @map("bucket_name")
  prefix          String                     @map("prefix")
  accessKeyId     String?                    @map("access_key_id")
  secretAccessKey String?                    @map("secret_access_key")
  region          String                     @map("region")
  endpoint        String?                    @map("endpoint")
  forcePathStyle  Boolean                    @map("force_path_style")

  // Integration Config
  nextSyncAt        DateTime?                        @map("next_sync_at")
  lastSyncAt        DateTime?                        @map("last_sync_at")
  enabled           Boolean
  exportFrequency   String                           @map("export_frequency")
  fileType          BlobStorageIntegrationFileType   @default(CSV) @map("file_type")
  exportMode        BlobStorageExportMode            @default(FULL_HISTORY) @map("export_mode")
  exportStartDate   DateTime?                        @map("export_start_date")
  exportSource      AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")
  exportFieldGroups String[]                         @default(["core", "basic", "time", "io", "metadata", "model", "usage", "prompt", "metrics", "tools", "trace_context"]) @map("export_field_groups")
  compressed        Boolean                          @default(true) @map("compressed")

  // Per-project blob-export tuning (set via DB directly for now; no UI/tRPC
  // write path). Validated/clamped at job time; null/malformed → defaults.
  // Shared with LFE-10394; extend the zod schema, do not duplicate the column.
  exportTuning Json? @map("export_tuning")

  // Run tracking
  runStartedAt DateTime? @map("run_started_at")

  // True while the integration is exporting history (new, re-enabled, or export
  // mode reset), so the export staleness gauge can separate it from steady
  // state. Cleared by the worker once a run lands within an hour of its start.
  backfill     Boolean   @default(true)

  // Error tracking
  lastError   String?   @map("last_error")
  lastErrorAt DateTime? @map("last_error_at")

  // Notification tracking
  lastFailureNotificationSentAt DateTime? @map("last_failure_notification_sent_at")

  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@map("blob_storage_integrations")
}

model ExternalMediaStorageIntegration {
  projectId String  @id @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  type            ExternalMediaStorageIntegrationType @map("type")
  bucketName      String                              @map("bucket_name")
  prefix          String?                             @map("prefix")
  accessKeyId     String?                             @map("access_key_id")
  secretAccessKey String?                             @map("secret_access_key")
  region          String                              @map("region")
  endpoint        String?                             @map("endpoint")
  forcePathStyle  Boolean                             @map("force_path_style")

  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@map("external_media_storage_integrations")
}

model WebCalloutEndpoint {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name              String   @default("Default")
  url               String
  enabled           Boolean  @default(true)
  toastMessage      String   @default("Callout sent") @map("toast_message")
  requestHeaders    String?  @map("request_headers")
  requestHeaderKeys String[] @default([]) @map("request_header_keys")

  @@index([projectId])
  @@index([projectId, enabled])
  @@map("web_callout_endpoints")
}

enum BlobStorageIntegrationFileType {
  JSON
  CSV
  JSONL
  PARQUET

  @@map("BlobStorageIntegrationFileType")
}

enum BlobStorageIntegrationType {
  S3
  S3_COMPATIBLE
  AZURE_BLOB_STORAGE
  GOOGLE_CLOUD_STORAGE

  @@map("BlobStorageIntegrationType")
}

enum ExternalMediaStorageIntegrationType {
  S3
  S3_COMPATIBLE
}

enum BlobStorageExportMode {
  FULL_HISTORY
  FROM_TODAY
  FROM_CUSTOM_DATE

  @@map("BlobStorageExportMode")
}

enum AnalyticsIntegrationExportSource {
  TRACES_OBSERVATIONS
  TRACES_OBSERVATIONS_EVENTS
  EVENTS

  @@map("AnalyticsIntegrationExportSource")
}

model BatchExport {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
  userId    String  @map("user_id")

  finishedAt DateTime? @map("finished_at")
  expiresAt  DateTime? @map("expires_at")

  name   String
  status String
  query  Json
  format String
  url    String?
  log    String?

  @@index([projectId, userId])
  @@index([status])
  @@map("batch_exports")
}

model BatchAction {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
  userId    String  @map("user_id")

  actionType String @map("action_type")
  tableName  String @map("table_name")

  status     String
  finishedAt DateTime? @map("finished_at")

  query  Json
  config Json?

  totalCount     Int?    @map("total_count")
  processedCount Int?    @map("processed_count")
  failedCount    Int?    @map("failed_count")
  log            String?

  @@index([projectId, userId])
  @@index([status])
  @@index([projectId, actionType])
  @@map("batch_actions")
}

model Media {
  id               String
  sha256Hash       String    @map("sha_256_hash") @db.Char(44)
  projectId        String    @map("project_id")
  project          Project   @relation(fields: [projectId], references: [id], onDelete: Cascade)
  createdAt        DateTime  @default(now()) @map("created_at")
  updatedAt        DateTime  @default(now()) @updatedAt @map("updated_at")
  uploadedAt       DateTime? @map("uploaded_at")
  uploadHttpStatus Int?      @map("upload_http_status")
  uploadHttpError  String?   @map("upload_http_error")
  bucketPath       String    @map("bucket_path")
  bucketName       String    @map("bucket_name")
  contentType      String    @map("content_type")
  contentLength    BigInt    @map("content_length")

  @@unique([projectId, id])
  @@unique([projectId, sha256Hash])
  @@index([projectId, createdAt])
  @@map("media")
}

enum MediaAssociationOrigin {
  UNKNOWN
  CLIENT_UPLOAD
  INGESTION_MEDIA_EXTRACTION
  INGESTION_FIELD_OVERFLOW
}

model TraceMedia {
  id        String                 @id @default(cuid())
  projectId String                 @map("project_id")
  createdAt DateTime               @default(now()) @map("created_at")
  updatedAt DateTime               @default(now()) @updatedAt @map("updated_at")
  mediaId   String                 @map("media_id")
  traceId   String                 @map("trace_id")
  field     String                 @map("field")
  origin    MediaAssociationOrigin @default(UNKNOWN)

  @@unique([projectId, traceId, mediaId, field])
  @@index([projectId, mediaId])
  @@map("trace_media")
}

model ObservationMedia {
  id            String                 @id @default(cuid())
  projectId     String                 @map("project_id")
  createdAt     DateTime               @default(now()) @map("created_at")
  updatedAt     DateTime               @default(now()) @updatedAt @map("updated_at")
  mediaId       String                 @map("media_id")
  traceId       String                 @map("trace_id")
  observationId String                 @map("observation_id")
  field         String                 @map("field")
  origin        MediaAssociationOrigin @default(UNKNOWN)

  @@unique([projectId, traceId, observationId, mediaId, field])
  @@index([projectId, mediaId])
  @@map("observation_media")
}

model DatasetItemMedia {
  id                   String    @id @default(cuid())
  projectId            String    @map("project_id")
  createdAt            DateTime  @default(now()) @map("created_at")
  updatedAt            DateTime  @default(now()) @updatedAt @map("updated_at")
  mediaId              String    @map("media_id")
  // dataset items cascade on dataset deletion, but these rows have no FK;
  // datasetId lets the dataset-delete worker clean them up directly
  datasetId            String    @map("dataset_id")
  datasetItemId        String    @map("dataset_item_id")
  // null while pending: the row is declared at media upload and stamped with
  // the item version's validFrom when the item is written.
  datasetItemValidFrom DateTime? @map("dataset_item_valid_from")
  // dataset item field containing the reference: input | expectedOutput | metadata
  field                String    @map("field")
  // null while pending; the dataset service fills it from the item JSON on claim.
  // JSONPath of the string holding the media reference within the field, e.g. $['images'][0]
  jsonPath             String?   @map("json_path")
  // null while pending; the original @@@langfuseMedia:...@@@ string, filled on
  // claim so reads need no JSON parsing
  referenceString      String?   @map("reference_string")

  @@unique([projectId, datasetItemId, datasetItemValidFrom, field, jsonPath], map: "dataset_item_media_item_version_field_path_key")
  @@index([projectId, mediaId])
  @@index([projectId, datasetId])
  @@map("dataset_item_media")
}

model BillingMeterBackup {
  // unique
  stripeCustomerId String   @map("stripe_customer_id")
  meterId          String   @map("meter_id")
  startTime        DateTime @map("start_time")
  endTime          DateTime @map("end_time")

  // value
  aggregatedValue Int @map("aggregated_value")

  // labels
  eventName String @map("event_name")
  orgId     String @map("org_id")

  // ts
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@unique([stripeCustomerId, meterId, startTime, endTime])
  @@index([stripeCustomerId, meterId, startTime, endTime])
  @@map("billing_meter_backups")
}

model LlmSchema {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name        String @map("name")
  description String @map("description")
  schema      Json   @map("schema") @db.Json

  @@unique([projectId, name])
  @@map("llm_schemas")
}

model LlmTool {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name        String @map("name")
  description String @map("description")
  parameters  Json   @map("parameters") @db.Json

  @@unique([projectId, name])
  @@map("llm_tools")
}

model Dashboard {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  createdBy     String? @map("created_by")
  createdByUser User?   @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)
  updatedBy     String? @map("updated_by")
  updatedByUser User?   @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)

  // Optional to account for Langfuse-managed dashboards
  projectId String?  @map("project_id")
  project   Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name        String @map("name")
  description String @map("description")

  definition Json @map("definition")
  filters    Json @default("[]") @map("filters")

  homeDashboardProjects Project[] @relation("ProjectHomeDashboard")

  @@map("dashboards")
}

enum DashboardWidgetViews {
  TRACES
  OBSERVATIONS
  SCORES_NUMERIC
  SCORES_CATEGORICAL
  SCORES_BOOLEAN
}

enum DashboardWidgetChartType {
  LINE_TIME_SERIES
  AREA_TIME_SERIES
  BAR_TIME_SERIES
  HORIZONTAL_BAR
  VERTICAL_BAR
  PIE
  NUMBER
  HISTOGRAM
  PIVOT_TABLE
}

model DashboardWidget {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  createdBy     String? @map("created_by")
  createdByUser User?   @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)
  updatedBy     String? @map("updated_by")
  updatedByUser User?   @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)

  // Optional to account for Langfuse-managed dashboards
  projectId String?  @map("project_id")
  project   Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name        String @map("name")
  description String @map("description")

  view       DashboardWidgetViews @map("view")
  dimensions Json                 @map("dimensions")
  metrics    Json                 @map("metrics")
  filters    Json                 @map("filters")

  chartType   DashboardWidgetChartType @map("chart_type")
  chartConfig Json                     @map("chart_config")
  minVersion  Int                      @default(1) @map("min_version")

  @@map("dashboard_widgets")
}

model TableViewPreset {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  name      String @map("name")
  tableName String @map("table_name")

  createdBy     String? @map("created_by")
  createdByUser User?   @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)
  updatedBy     String? @map("updated_by")
  updatedByUser User?   @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)

  // view configuration
  filters          Json    @map("filters")
  columnOrder      Json    @map("column_order")
  columnVisibility Json    @map("column_visibility")
  searchQuery      String? @map("search_query")
  orderBy          Json?   @map("order_by")

  @@unique([projectId, tableName, name])
  @@map("table_view_presets")
}

model DefaultView {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  userId String? @map("user_id")
  user   User?   @relation("DefaultViewUser", fields: [userId], references: [id], onDelete: Cascade)

  viewName String @map("view_name")
  viewId   String @map("view_id") // no FK - to allow system presets (i.e. frontend defined starting in __langfuse_)

  // Uniqueness enforced via partial indexes in migration (PostgreSQL 12+ compatible)
  // - User defaults: UNIQUE(project_id, user_id, view_name) WHERE user_id IS NOT NULL
  // - Project defaults: UNIQUE(project_id, view_name) WHERE user_id IS NULL
  @@index([projectId, viewName])
  @@map("default_views")
}

model Action {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  type ActionType

  // Configuration specific to each action type
  config Json // Structured JSON for different action types
  // For WEBHOOK: { version: "1.0", url: "...", method: "POST", headers: {...}, secretId: "..." }
  // For ANNOTATION_QUEUE: { version: "1.0", queueId: "..." }

  automations          Automation[]
  automationExecutions AutomationExecution[]

  @@index([projectId])
  @@map("actions")
}

model Trigger {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  // When should this trigger fire
  eventSource  String // trace, prompt, etc.
  eventActions String[] // created, updated, deleted
  filter       Json? // Filter conditions (format: { field: "name", operator: "equals", value: "my_trace" })

  // Additional attributes
  status JobConfigState @default(ACTIVE) @map("status")

  // Link to executions
  automationExecutions AutomationExecution[]
  automations          Automation[]

  @@index([projectId])
  @@map("triggers")
}

model Automation {
  id                  String                @id @default(cuid())
  name                String                @map("name")
  trigger             Trigger               @relation(fields: [triggerId], references: [id], onDelete: Cascade)
  triggerId           String                @map("trigger_id")
  action              Action                @relation(fields: [actionId], references: [id], onDelete: Cascade)
  actionId            String                @map("action_id")
  createdAt           DateTime              @default(now()) @map("created_at")
  projectId           String                @map("project_id")
  project             Project               @relation(fields: [projectId], references: [id], onDelete: Cascade)
  AutomationExecution AutomationExecution[]

  @@index([projectId, actionId, triggerId])
  @@index([projectId, name])
  @@map("automations")
}

enum ActionType {
  WEBHOOK
  SLACK
  GITHUB_DISPATCH
  PAGERDUTY
  // More action types can be added as needed
}

enum ActionExecutionStatus {
  COMPLETED
  ERROR
  PENDING
  CANCELLED
}

model AutomationExecution {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
  sourceId  String   @map("source_id")

  automationId String     @map("automation_id")
  automation   Automation @relation(fields: [automationId], references: [id], onDelete: Cascade)

  triggerId String  @map("trigger_id")
  trigger   Trigger @relation(fields: [triggerId], references: [id], onDelete: Cascade)

  actionId String @map("action_id")
  action   Action @relation(fields: [actionId], references: [id], onDelete: Cascade)

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  status     ActionExecutionStatus @default(PENDING) @map("status")
  input      Json                  @map("input")
  output     Json?                 @map("output")
  startedAt  DateTime?             @map("started_at")
  finishedAt DateTime?             @map("finished_at")
  error      String?               @map("error")

  @@index([triggerId])
  @@index([actionId])
  @@index([projectId])
  @@map("automation_executions")
}

enum MonitorThresholdOperator {
  GT
  GTE
  LT
  LTE
  EQ
  NEQ
}

enum MonitorView {
  OBSERVATIONS
  SCORES_NUMERIC
  SCORES_CATEGORICAL
  SCORES_BOOLEAN
}

enum MonitorSeverity {
  PAUSED
  UNKNOWN
  NO_DATA
  OK
  WARNING
  ALERT
}

// Scheduler evaluates only ACTIVE; any other state is skipped.
enum MonitorStatus {
  PAUSED
  ACTIVE
  ERROR_BAD_QUERY
}

model Monitor {
  id        String   @id @default(cuid())
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  createdBy     String? @map("created_by")
  createdByUser User?   @relation("CreatedByUser", fields: [createdBy], references: [id], onDelete: SetNull)
  updatedBy     String? @map("updated_by")
  updatedByUser User?   @relation("UpdatedByUser", fields: [updatedBy], references: [id], onDelete: SetNull)

  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  // === Query shape (mirrors DashboardWidget, minus TRACES) ===
  view    MonitorView
  filters Json
  metric  Json

  // === Monitor Evaluation ===
  windowMs          BigInt                   @map("window_ms")
  cadenceMs         BigInt                   @map("cadence_ms")
  thresholdOperator MonitorThresholdOperator @map("threshold_operator")
  alertThreshold    Decimal                  @map("alert_threshold")
  warningThreshold  Decimal?                 @map("warning_threshold")

  severity          MonitorSeverity @default(UNKNOWN)
  severityChangedAt DateTime?       @map("severity_changed_at")

  noData   Json @map("no_data")
  renotify Json

  // === Scheduling ===
  status           MonitorStatus @default(ACTIVE)
  schedulerBatchId BigInt        @map("scheduler_batch_id")
  nextRunAt        DateTime?     @map("next_run_at")
  lastPublishedAt  DateTime?     @map("last_published_at")
  lastClaimedAt    DateTime?     @map("last_claimed_at")
  lastCompletedAt  DateTime?     @map("last_completed_at")

  // === Alerts ===
  name       String
  tags       String[]  @default([])
  triggerIds String[]  @default([]) @map("trigger_ids")
  alertedAt  DateTime? @map("alerted_at")

  @@index([projectId])
  @@index([schedulerBatchId])
  @@index([nextRunAt, schedulerBatchId], map: "monitors_scheduler_tick_idx")
  @@map("monitors")
}

// Slack Integration: Stores centralized Slack workspace connection for each project
// One project can connect to one Slack workspace, supporting multiple channel automations
model SlackIntegration {
  id        String  @id @default(cuid())
  projectId String  @unique @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  // Installation details (encrypted using shared encryption utilities)
  teamId    String @map("team_id") // Slack workspace ID
  teamName  String @map("team_name") // Human-readable workspace name
  botToken  String @map("bot_token") // Encrypted bot token for API calls
  botUserId String @map("bot_user_id") // Bot user ID for workspace

  // Only the installer may list and use private channels, since the bot token sees every private channel it was invited to
  installerUserId      String? @map("installer_user_id") // Langfuse user who connected Slack
  installerSlackUserId String? @map("installer_slack_user_id") // Slack user who authorized the install

  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@index([teamId])
  @@map("slack_integrations")
}

// Pending Deletions: Tracks objects (like traces) that are scheduled for batch deletion
model PendingDeletion {
  id        String  @id @default(cuid())
  projectId String  @map("project_id")
  project   Project @relation(fields: [projectId], references: [id], onDelete: Cascade)

  object    String  @map("object") // e.g., "trace", "observation", etc.
  objectId  String  @map("object_id") // The ID of the object to be deleted
  isDeleted Boolean @default(false) @map("is_deleted")

  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@index([projectId, object, isDeleted, objectId, id])
  @@index([objectId, object])
  @@map("pending_deletions")
}

model Survey {
  id         String        @id @default(cuid())
  createdAt  DateTime      @default(now()) @map("created_at")
  surveyName SurveyName    @map("survey_name")
  response   Json
  userId     String?       @map("user_id")
  userEmail  String?       @map("user_email")
  orgId      String?       @map("org_id")
  org        Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
  user       User?         @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("surveys")
}

enum SurveyName {
  ORG_ONBOARDING  @map("org_onboarding")
  USER_ONBOARDING @map("user_onboarding")

  @@map("SurveyName")
}

model CloudSpendAlert {
  id    String       @id @default(cuid())
  orgId String       @map("org_id")
  org   Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)

  title     String // e.g., "Production Alert"
  threshold Decimal @map("threshold") // USD amount

  triggeredAt DateTime? @map("triggered_at") // Last trigger timestamp

  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @default(now()) @updatedAt @map("updated_at")

  @@index([orgId])
  @@map("cloud_spend_alerts")
}

model TopicClusteringRun {
  id              String           @id @default(cuid())
  projectId       String           @map("project_id")
  facetId         String           @map("facet_id")
  facetVersion    Int              @map("facet_version")
  project         Project          @relation(fields: [projectId], references: [id], onDelete: Cascade)
  facet           EvaluatorVersion @relation(fields: [facetId, facetVersion], references: [evaluatorId, version], onDelete: Cascade)
  status          String           @default("pending")
  config          Json             @default("{}")
  error           String?
  createdAt       DateTime         @default(now()) @map("created_at") @db.Timestamptz(3)
  startedAt       DateTime?        @map("started_at") @db.Timestamptz(3)
  finishedAt      DateTime?        @map("finished_at") @db.Timestamptz(3)
  topicVersionIds String[]         @default([]) @map("topic_version_ids")
  // Topics rule of a continuous map, or the batch action of a one-off analysis; null on runs written before either existed.
  ruleId          String?          @map("rule_id")
  batchActionId   String?          @map("batch_action_id")

  @@index([projectId, facetId, status, facetVersion(sort: Desc), createdAt(sort: Desc), id(sort: Desc)], map: "topic_clustering_runs_serving_map_idx")
  @@index([projectId, ruleId, facetId, status], map: "topic_clustering_runs_rule_serving_map_idx")
  @@index([projectId, batchActionId])
  @@map("topic_clustering_runs")
}