repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
onyx
backend/onyx/document_index/document_metadata.py
.py
"""Document-level metadata used during indexing. Previously declared in the now-removed `onyx.document_index.interfaces` module. Used by the indexing pipeline / Postgres upsert layer; not part of the search backend interface. """ from dataclasses import dataclass from datetime import datetime from typing import Any ...
41
1,277
onyx
backend/onyx/document_index/factory.py
.py
import httpx from sqlalchemy.orm import Session from onyx.configs.app_configs import ( DISABLE_VECTOR_DB, ENABLE_OPENSEARCH_INDEXING_FOR_ONYX, ONYX_DISABLE_VESPA, ) from onyx.db.models import SearchSettings from onyx.db.opensearch_migration import get_opensearch_retrieval_state from onyx.document_index.dis...
175
6,574
onyx
backend/onyx/document_index/document_index_utils.py
.py
import math import uuid from uuid import UUID from sqlalchemy.orm import Session from onyx.configs.app_configs import ENABLE_MULTIPASS_INDEXING from onyx.db.models import SearchSettings from onyx.db.search_settings import ( get_current_search_settings, get_secondary_search_settings, ) from onyx.document_index...
206
7,215
onyx
backend/onyx/document_index/vespa_constants.py
.py
from onyx.configs.app_configs import ( VESPA_CLOUD_URL, VESPA_CONFIG_SERVER_HOST, VESPA_HOST, VESPA_PORT, VESPA_TENANT_PORT, ) from onyx.configs.constants import SOURCE_TYPE # config server VESPA_CONFIG_SERVER_URL = ( VESPA_CLOUD_URL or f"http://{VESPA_CONFIG_SERVER_HOST}:{VESPA_TENANT_PORT}"...
113
3,517
onyx
backend/onyx/document_index/vespa/internal_types.py
.py
"""Vespa-internal data types. These were previously declared in the now-removed `onyx.document_index.interfaces` module. They survive only to support Vespa's chunk-id deletion / range-retrieval plumbing, which has not been ported to the new generic DocumentIndex interface. """ from dataclasses import dataclass @dat...
46
1,277
onyx
backend/onyx/document_index/vespa/deletion.py
.py
import concurrent.futures from uuid import UUID import httpx from onyx.document_index.vespa_constants import DOCUMENT_ID_ENDPOINT, NUM_THREADS from onyx.utils.logger import setup_logger from onyx.utils.retry_wrapper import retry_builder logger = setup_logger() CONTENT_SUMMARY = "content_summary" @retry_builder(t...
69
2,028
onyx
backend/onyx/document_index/vespa/chunk_retrieval.py
.py
import json import string import time from collections.abc import Callable, Mapping from datetime import datetime, timezone from typing import Any, cast import httpx from onyx.background.celery.tasks.opensearch_migration.constants import ( FINISHED_VISITING_SLICE_CONTINUATION_TOKEN, ) from onyx.background.celery....
688
24,991
onyx
backend/onyx/document_index/vespa/indexing_utils.py
.py
import concurrent.futures import json import random import time import uuid from abc import ABC, abstractmethod from collections.abc import Callable from datetime import datetime, timezone from http import HTTPStatus import httpx from onyx.connectors.cross_connector_utils.miscellaneous_utils import ( get_experts_...
440
15,871
onyx
backend/onyx/document_index/vespa/kg_interactions.py
.py
from onyx.db.document import ( get_document_kg_entities_and_relationships, get_num_chunks_for_document, ) from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.document_index.interfaces_new import TenantState from onyx.document_index.vespa.vespa_document_index import ( KGUChunkUpda...
64
2,023
onyx
backend/onyx/document_index/vespa/vespa_document_index.py
.py
import concurrent.futures import io import logging import os import random import re import time import urllib.parse import zipfile from collections.abc import Generator, Iterable from datetime import datetime, timedelta from typing import Any, BinaryIO, cast from uuid import UUID import httpx import jinja2 import req...
1,369
52,937
onyx
backend/onyx/document_index/vespa/shared_utils/utils.py
.py
import time from typing import cast import httpx from onyx.configs.app_configs import ( MANAGED_VESPA, VESPA_CLOUD_CERT_PATH, VESPA_CLOUD_KEY_PATH, VESPA_REQUEST_TIMEOUT, ) from onyx.document_index.vespa_constants import VESPA_APP_CONTAINER_URL from onyx.utils.logger import setup_logger logger = setu...
115
3,927
onyx
backend/onyx/document_index/vespa/shared_utils/vespa_request_builders.py
.py
from datetime import datetime, timedelta, timezone from onyx.configs.constants import INDEX_SEPARATOR from onyx.context.search.models import IndexFilters from onyx.document_index.vespa.internal_types import VespaChunkRequest from onyx.document_index.vespa_constants import ( ACCESS_CONTROL_LIST, CHUNK_ID, D...
294
10,347
onyx
backend/onyx/document_index/opensearch/opensearch_document_index.py
.py
import json from collections.abc import Iterable from typing import Any from opensearchpy.helpers.errors import BulkIndexError from onyx.access.models import DocumentAccess from onyx.configs.app_configs import ( MAX_CHUNKS_PER_DOC_BATCH, VERIFY_CREATE_OPENSEARCH_INDEX_ON_INIT_MT, ) from onyx.configs.constants...
1,158
50,241
onyx
backend/onyx/document_index/opensearch/port_copy.py
.py
"""PRESENT -> FUTURE chunk copy for the reindex port. Reads a document's existing chunks from the PRESENT OpenSearch index via the PIT scan, re-embeds them under the FUTURE model, and writes them to the FUTURE index create-only (it never overwrites a chunk a live/forward writer already owns, so a stale backlog write c...
215
10,004
onyx
backend/onyx/document_index/opensearch/constants.py
.py
# Default value for the maximum number of tokens a chunk can hold, if none is # specified when creating an index. import os from enum import Enum DEFAULT_MAX_CHUNK_SIZE = 512 # By default OpenSearch will only return a maximum of this many results in a # given search. This value is configurable in the index settings....
116
4,912
onyx
backend/onyx/document_index/opensearch/string_filtering.py
.py
import re MAX_DOCUMENT_ID_ENCODED_LENGTH: int = 512 class DocumentIDTooLongError(ValueError): """Raised when a document ID is too long for OpenSearch after filtering.""" def filter_and_validate_document_id( document_id: str, max_encoded_length: int = MAX_DOCUMENT_ID_ENCODED_LENGTH ) -> str: """ Fil...
49
1,736
onyx
backend/onyx/document_index/opensearch/client.py
.py
import json import logging import time from collections import Counter from collections.abc import Iterator from contextlib import AbstractContextManager, nullcontext from http import HTTPStatus from typing import Any, Generic, TypeVar import boto3 from opensearchpy import ( NotFoundError, OpenSearch, Tran...
2,119
85,595
onyx
backend/onyx/document_index/opensearch/schema.py
.py
import hashlib from datetime import datetime, timezone from typing import Any, Self from pydantic import ( BaseModel, Field, SerializerFunctionWrapHandler, ValidationInfo, field_serializer, field_validator, model_serializer, model_validator, ) from onyx.configs.app_configs import ( ...
618
26,302
onyx
backend/onyx/document_index/opensearch/search.py
.py
import random from datetime import datetime, timedelta, timezone from typing import Any, TypeAlias, TypeVar from onyx.configs.app_configs import ( DEFAULT_OPENSEARCH_QUERY_TIMEOUT_S, OPENSEARCH_EXPLAIN_ENABLED, OPENSEARCH_MATCH_HIGHLIGHTS_DISABLED, OPENSEARCH_PROFILING_DISABLED, ) from onyx.configs.con...
1,398
61,284
onyx
backend/onyx/document_index/opensearch/index_reclaim.py
.py
"""OpenSearch-side primitive for reclaiming an old (PAST) index's data after a reindex. Deployment-mode-aware and idempotent — safe to re-run until it reports COMPLETE. Driven by the reclaim beat task (background/celery/tasks/index_reclaim). """ from enum import Enum from onyx.configs.app_configs import OLD_INDEX_REC...
66
2,895
onyx
backend/onyx/document_index/opensearch/cluster_settings.py
.py
from typing import Any OPENSEARCH_CLUSTER_SETTINGS: dict[str, Any] = { "persistent": { # By default, when you index a document to a non-existent index, # OpenSearch will automatically create the index. This behavior is # undesirable so this function exposes the ability to disable it. ...
19
906
onyx
backend/onyx/db/slack_channel_config.py
.py
from collections.abc import Sequence from typing import Any from sqlalchemy import select from sqlalchemy.orm import Session, joinedload from onyx.db.constants import ( DEFAULT_PERSONA_SLACK_CHANNEL_NAME, SLACK_BOT_PERSONA_PREFIX, ) from onyx.db.models import ( ChannelConfig, Persona, Persona__Doc...
294
9,634
onyx
backend/onyx/db/search_settings.py
.py
from sqlalchemy import and_, delete, func, select from sqlalchemy import inspect as sa_inspect from sqlalchemy.orm import Session from onyx.configs.model_configs import ( DEFAULT_DOCUMENT_ENCODER_MODEL, DOCUMENT_ENCODER_MODEL, ) from onyx.context.search.models import SavedSearchSettings from onyx.db.llm import...
385
14,440
onyx
backend/onyx/db/external_app.py
.py
import re from collections.abc import Iterable from dataclasses import dataclass from typing import Any, cast from uuid import UUID from sqlalchemy import and_, delete, func, select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session, selectinload from onyx.db.enums import ( Endpo...
795
27,002
onyx
backend/onyx/db/document_set.py
.py
from collections.abc import Sequence from typing import cast from uuid import UUID from sqlalchemy import Select, and_, delete, exists, func, or_, select from sqlalchemy.orm import Session, aliased, selectinload from onyx.configs.app_configs import DISABLE_VECTOR_DB from onyx.db.connector_credential_pair import ( ...
837
29,937
onyx
backend/onyx/db/index_attempt_metrics.py
.py
"""Stage-level metric write helpers for an `IndexAttempt`. The canonical pipeline-stage taxonomy (``IndexAttemptStage``, ``StageScope``, ``STAGE_SCOPE``) lives in ``onyx.db.index_attempt_metrics_models`` so that ``onyx.db.models`` can import the enum as a column type without creating a circular dependency through this...
402
13,896
onyx
backend/onyx/db/feedback.py
.py
from datetime import datetime, timezone from uuid import UUID from fastapi import HTTPException from sqlalchemy import Select, and_, asc, delete, desc, exists, select from sqlalchemy.orm import Session, aliased from onyx.configs.constants import MessageType, SearchFeedbackType from onyx.db.chat import get_chat_messag...
272
8,700
onyx
backend/onyx/db/voice.py
.py
from typing import Any from uuid import UUID from sqlalchemy import select, update from sqlalchemy.orm import Session from onyx.db.models import User, VoiceProvider from onyx.error_handling.error_codes import OnyxErrorCode from onyx.error_handling.exceptions import OnyxError MIN_VOICE_PLAYBACK_SPEED = 0.5 MAX_VOICE_...
243
7,249
onyx
backend/onyx/db/entity_type.py
.py
from collections import defaultdict from sqlalchemy import update from sqlalchemy.orm import Session from onyx.db.connector import fetch_unique_document_sources from onyx.db.document import DocumentSource from onyx.db.models import Connector, KGEntityType from onyx.kg.models import KGAttributeEntityOption from onyx.s...
152
4,485
onyx
backend/onyx/db/federated.py
.py
from datetime import datetime from typing import Any from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session, joinedload, selectinload from onyx.configs.constants import FederatedConnectorSource from onyx.db.engine.sql_engine import get_session_with_current_tenant from onyx.db.models im...
331
11,373
onyx
backend/onyx/db/persona_sharing.py
.py
"""Pure helpers over loaded Persona share relations. Kept import-light so both the persona db layer and the API snapshot models can use them without cycles.""" from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.enums import ( ...
95
3,420
onyx
backend/onyx/db/incognito.py
.py
"""Membership query and file cleanup for incognito chats. A file's privacy is decided when it is uploaded. The client mints the session id when incognito is switched on and sends it with every upload, so a file names its session before that session exists and the server never has to take the client's word for whether ...
182
6,809
onyx
backend/onyx/db/utils.py
.py
from enum import Enum from typing import Any, Final, TypeGuard, TypeVar from psycopg2 import OperationalError, errorcodes from psycopg2.errors import ForeignKeyViolation, UniqueViolation from pydantic import BaseModel from sqlalchemy import inspect from sqlalchemy.exc import IntegrityError from onyx.db.models import ...
103
3,423
onyx
backend/onyx/db/mcp.py
.py
import datetime from uuid import UUID from sqlalchemy import Select, and_, delete, select from sqlalchemy.orm import Session, aliased, selectinload from sqlalchemy.orm.attributes import flag_modified from onyx.db.constants import UNSET, UnsetType from onyx.db.enums import ( MCPAuthenticationPerformer, MCPOAut...
537
18,779
onyx
backend/onyx/db/hierarchy.py
.py
"""CRUD operations for HierarchyNode.""" from collections import defaultdict from uuid import UUID from sqlalchemy import delete, select from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.engine import CursorResult from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Sessio...
940
30,114
onyx
backend/onyx/db/chunk.py
.py
from datetime import datetime, timezone from sqlalchemy import delete from sqlalchemy.orm import Session from onyx.db.models import ChunkStats from onyx.indexing.models import UpdatableChunkData def update_chunk_boost_components__no_commit( chunk_data: list[UpdatableChunkData], db_session: Session, ) -> Non...
63
1,920
onyx
backend/onyx/db/relationships.py
.py
from typing import List from sqlalchemy import or_ from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.orm import Session import onyx.db.document as dbdocument from onyx.db.models import ( KGEntity, KGEntityExtractionStaging, KGRelation...
617
20,482
onyx
backend/onyx/db/gated_app.py
.py
"""The ``gated_app`` identity row: get-or-create, lookup, and the per-action policy read/write shared by every gated target (external app or MCP server). All mapping between a gated target ``(kind, target_id)`` and its ``gated_app`` row lives here; consumers reference ``gated_app_id`` only, never the per-catalog colum...
102
3,753
onyx
backend/onyx/db/scheduled_task.py
.py
"""Database operations for Craft Scheduled Tasks. Mirrors the style of ``backend/onyx/db/persona.py`` — every function takes ``db_session: Session`` first, all queries live here (per CLAUDE.md), and ownership / NOT_FOUND raising is consistent. The dispatcher's hot path (``claim_due_scheduled_tasks``) is the only func...
624
20,052
onyx
backend/onyx/db/tenant_shard.py
.py
"""Writes to the `public.tenant_shard` catalog table. Reads live in `shard_routing`. Schema-qualified raw SQL, matching the read side: `schema_translate_map` only rewrites SQLAlchemy `Table` constructs, so an unqualified name in `text()` would resolve against whatever `search_path` the pooled connection happens to car...
69
2,842
onyx
backend/onyx/db/persona.py
.py
from collections.abc import Sequence from datetime import datetime from enum import Enum from uuid import UUID from fastapi import HTTPException from sqlalchemy import Select, exists, func, not_, or_, select, update from sqlalchemy.orm import Session, aliased, selectinload from onyx.access.hierarchy_access import get...
1,877
70,111
onyx
backend/onyx/db/models.py
.py
import datetime import json from typing import Any, Literal, NotRequired from uuid import UUID, uuid4 from fastapi_users_db_sqlalchemy import ( SQLAlchemyBaseOAuthAccountTableUUID, SQLAlchemyBaseUserTableUUID, ) from fastapi_users_db_sqlalchemy.access_token import SQLAlchemyBaseAccessTokenTableUUID from fastap...
7,176
261,180
onyx
backend/onyx/db/discord_bot.py
.py
"""CRUD operations for Discord bot models.""" from datetime import datetime, timezone from sqlalchemy import delete, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, joinedload from onyx.auth.api_key import build_displayable_api_key, generate_api_key, hash_api_key from onyx.auth.s...
451
13,981
onyx
backend/onyx/db/release_notes.py
.py
"""Database functions for release notes functionality.""" from urllib.parse import urlencode from sqlalchemy import select from sqlalchemy.orm import Session from onyx.configs.app_configs import INSTANCE_TYPE from onyx.configs.constants import ( DANSWER_API_KEY_DUMMY_EMAIL_DOMAIN, ONYX_UTM_SOURCE, Notifi...
102
3,415
onyx
backend/onyx/db/token_limit.py
.py
from collections import defaultdict from collections.abc import Sequence from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session from onyx.configs.constants import TokenRateLimitScope from onyx.db.models import TokenRateLimit, TokenRateLimit__UserGroup, User__UserGroup from onyx.error_h...
159
5,056
onyx
backend/onyx/db/swap_index.py
.py
import time from uuid import UUID from sqlalchemy.orm import Session from onyx.configs.app_configs import DISABLE_VECTOR_DB, VESPA_NUM_ATTEMPTS_ON_STARTUP from onyx.configs.constants import KV_REINDEX_KEY from onyx.db.connector_credential_pair import ( fetch_indexable_standard_connector_credential_pair_ids, g...
373
14,737
onyx
backend/onyx/db/dal.py
.py
"""Base Data Access Layer (DAL) for database operations. The DAL pattern groups related database operations into cohesive classes with explicit session management. It supports two usage modes: 1. **External session** (FastAPI endpoints) — the caller provides a session whose lifecycle is managed by FastAPI's de...
75
2,288
onyx
backend/onyx/db/file_record.py
.py
from sqlalchemy import String, and_, case, cast, func, select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session from onyx.background.task_utils import QUERY_REPORT_NAME_PREFIX from onyx.configs.constants import FileOrigin, FileType from onyx.db.enums import IndexingStatus fro...
263
8,939
onyx
backend/onyx/db/chat.py
.py
from collections.abc import Sequence from datetime import datetime, timedelta, timezone from typing import Tuple from uuid import UUID from fastapi import HTTPException from sqlalchemy import Row, delete, desc, func, nullsfirst, or_, select, update from sqlalchemy.exc import MultipleResultsFound from sqlalchemy.orm im...
1,160
40,528
onyx
backend/onyx/db/saml.py
.py
import datetime from typing import cast from uuid import UUID from sqlalchemy import and_, func, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session, selectinload from onyx.configs.app_configs import SESSION_EXPIRE_TIME_SECONDS from onyx.db.models import SamlAccount def upsert_...
70
1,979
onyx
backend/onyx/db/oauth_config.py
.py
from typing import Any from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.models import OAuthConfig, OAuthUserToken, Tool from onyx.utils.logger import setup_logger logger = setup_logger() # OAuth Config CRUD operations def create_oauth_config( name: str, ...
193
5,882
onyx
backend/onyx/db/users.py
.py
from collections.abc import Callable, Sequence from typing import Any from uuid import UUID from fastapi import HTTPException from fastapi_users.password import PasswordHelper from sqlalchemy import Select, case, delete, func, literal, select, update from sqlalchemy.dialects.postgresql import insert as pg_insert from ...
830
28,693
onyx
backend/onyx/db/rotate_encryption_key.py
.py
"""Rotate encryption key for all encrypted columns. Dynamically discovers all columns using EncryptedString / EncryptedJson, decrypts each value with the old key, and re-encrypts with the current ENCRYPTION_KEY_SECRET. The operation is idempotent: rows already encrypted with the current key are skipped. Commits are m...
163
5,908
onyx
backend/onyx/db/api_key.py
.py
import uuid from typing import NamedTuple from fastapi_users.password import PasswordHelper from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session, contains_eager, joinedload from onyx.auth.api_key import ( ApiKeyDescriptor, build_displayable_a...
281
9,458
onyx
backend/onyx/db/constants.py
.py
SLACK_BOT_PERSONA_PREFIX = "__slack_bot_persona__" DEFAULT_PERSONA_SLACK_CHANNEL_NAME = "DEFAULT_SLACK_CHANNEL" CONNECTOR_VALIDATION_ERROR_MESSAGE_PREFIX = "ConnectorValidationError:" # Sentinel value to distinguish between "not provided" and "explicitly set to None" class UnsetType: def __repr__(self) -> str: ...
14
366
onyx
backend/onyx/db/sso_provider.py
.py
import json import os import re from pathlib import Path from typing import Any from email_validator import EmailNotValidError, validate_email from pydantic import BaseModel, ConfigDict, Field, ValidationError from sqlalchemy import select from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import As...
391
14,391
onyx
backend/onyx/db/opensearch_migration.py
.py
"""Database operations for OpenSearch migration tracking. This module provides functions to track the progress of migrating documents from Vespa to OpenSearch. """ import json from datetime import datetime, timezone from sqlalchemy import select, text from sqlalchemy.dialects.postgresql import insert from sqlalchemy...
441
15,440
onyx
backend/onyx/db/permission_sync_attempt.py
.py
"""Permission sync attempt CRUD operations and utilities. This module contains all CRUD operations for both DocPermissionSyncAttempt and ExternalGroupPermissionSyncAttempt models, along with shared utilities. """ from typing import Any, cast from sqlalchemy import delete, func, select from sqlalchemy.engine.cursor i...
581
19,727
onyx
backend/onyx/db/llm.py
.py
from sqlalchemy import delete, or_, select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session, load_only, selectinload from onyx.auth.schemas import UserRole from onyx.db.enums import LLMModelFlowType from onyx.db.models import CloudEmbeddingProvider as CloudEmbeddingProviderM...
1,312
44,081
onyx
backend/onyx/db/connector.py
.py
from datetime import datetime, timezone from sqlalchemy import and_, exists, func, select from sqlalchemy.orm import Session, aliased from onyx.configs.app_configs import DEFAULT_PRUNING_FREQ from onyx.configs.constants import DocumentSource from onyx.connectors.models import InputType from onyx.db.enums import Index...
401
13,166
onyx
backend/onyx/db/background_error.py
.py
from sqlalchemy.orm import Session from onyx.db.models import BackgroundError def create_background_error( db_session: Session, message: str, cc_pair_id: int | None ) -> None: db_session.add(BackgroundError(message=message, cc_pair_id=cc_pair_id)) db_session.commit()
11
283
onyx
backend/onyx/db/code_interpreter.py
.py
from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.models import CodeInterpreterServer def fetch_code_interpreter_server( db_session: Session, ) -> CodeInterpreterServer: server = db_session.scalars(select(CodeInterpreterServer)).one() return server def update_code_interprete...
22
557
onyx
backend/onyx/db/connector_credential_pair.py
.py
from datetime import datetime from enum import Enum from typing import TypeVarTuple from uuid import UUID from fastapi import HTTPException from pydantic import BaseModel from sqlalchemy import Select, and_, delete, desc, exists, func, or_, select, update from sqlalchemy.orm import Session, aliased, joinedload, select...
931
30,748
onyx
backend/onyx/db/auth.py
.py
from collections.abc import AsyncGenerator, Callable from typing import Any, Dict, TypeVar from fastapi import Depends from fastapi_users.models import ID, UP from fastapi_users_db_sqlalchemy import SQLAlchemyUserDatabase from fastapi_users_db_sqlalchemy.access_token import SQLAlchemyAccessTokenDatabase from sqlalchem...
122
4,532
onyx
backend/onyx/db/tenant_invite_counter.py
.py
from sqlalchemy import func, update from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.orm import Session from onyx.db.models import TenantInviteCounter def reserve_trial_invites( shared_session: Session, tenant_id: str, num_invites: int, ) -> int: """Atomically increment ...
62
2,212
onyx
backend/onyx/db/enums.py
.py
from __future__ import annotations from enum import Enum as PyEnum from typing import ClassVar class AccountType(str, PyEnum): """ What kind of account this is — determines whether the user enters the group-based permission system. STANDARD + SERVICE_ACCOUNT → participate in group system BOT, EX...
793
23,972
onyx
backend/onyx/db/index_attempt_metrics_models.py
.py
"""Stage taxonomy for `IndexAttempt` metrics. This module owns the canonical pipeline-stage enum, its display-scope companion enum, and the static mapping between them. It is intentionally a leaf module — it imports nothing from the rest of the Onyx codebase — so it can be safely imported by both ``onyx.db.models`` (w...
117
5,075
onyx
backend/onyx/db/entities.py
.py
import uuid from datetime import datetime, timezone from typing import List from sqlalchemy import func, literal, select, update from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.orm import Session import onyx.db.document as dbdocument from...
334
11,252
onyx
backend/onyx/db/user_file.py
.py
import datetime from uuid import UUID from sqlalchemy import exists, func, select, update from sqlalchemy.orm import Session, joinedload, selectinload from onyx.db.enums import UserFileStatus from onyx.db.models import Persona, Project__UserFile, User, UserFile def fetch_chunk_counts_for_user_files( user_file_i...
293
10,468
onyx
backend/onyx/db/usage.py
.py
"""Database interactions for tenant usage tracking (cloud usage limits).""" from datetime import datetime, timezone from enum import Enum from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.orm import Session from onyx.db.models ...
189
5,809
onyx
backend/onyx/db/encrypted_kv_store.py
.py
"""Encrypted-at-rest key/value storage for instance-level secrets. Backed by the ``encrypted_key_value_store`` table and never mirrored to the cache, so secrets stay encrypted at rest and out of Redis. Tenant context is picked up from the current-tenant contextvar, matching the plain KV store.""" from typing import A...
44
1,729
onyx
backend/onyx/db/pat.py
.py
"""Database operations for Personal Access Tokens.""" import asyncio from datetime import datetime, timezone from typing import NamedTuple from uuid import UUID from sqlalchemy import select, update from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import Session, contains_eager from onyx.auth.pat ...
210
6,929
onyx
backend/onyx/db/tracing.py
.py
from __future__ import annotations from uuid import UUID from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.models import TracingProviderConfig from shared_configs.enums import TracingProviderType def fetch_all_tracing_providers(db_session: Session) -> list[TracingProviderConfig]: st...
64
1,904
onyx
backend/onyx/db/projects.py
.py
import datetime import uuid from typing import List from uuid import UUID from fastapi import HTTPException, UploadFile from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import func from sqlalchemy.orm import Session from starlette.background import BackgroundTasks from onyx.configs.app_configs import...
263
8,951
onyx
backend/onyx/db/web_search.py
.py
from __future__ import annotations from sqlalchemy import select, update from sqlalchemy.orm import Session from onyx.db.models import InternetContentProvider, InternetSearchProvider from onyx.tools.tool_implementations.web_search.models import WebContentProviderConfig from shared_configs.enums import WebContentProvi...
326
10,062
onyx
backend/onyx/db/port_attempt.py
.py
"""DB helpers for the reindexing port-attempt lifecycle. One PortAttempt per (cc_pair, FUTURE SearchSettings) drives the backlog port. The partial-unique index `ix_port_attempt_active_unique` guarantees at most one active (NOT_STARTED / IN_PROGRESS) attempt per pair; terminal rows accumulate as history. Nothing here e...
837
32,570
onyx
backend/onyx/db/index_attempt.py
.py
from collections.abc import Sequence from datetime import datetime, timedelta, timezone from typing import TypeVarTuple from sqlalchemy import Select, and_, delete, desc, func, select, update from sqlalchemy.orm import Session, joinedload from onyx.connectors.models import ConnectorFailure from onyx.db.engine.sql_eng...
1,214
41,710
onyx
backend/onyx/db/deletion_attempt.py
.py
from sqlalchemy.orm import Session from onyx.db.index_attempt import get_last_attempt from onyx.db.models import ConnectorCredentialPair, IndexingStatus from onyx.db.search_settings import get_current_search_settings def check_deletion_attempt_is_allowed( connector_credential_pair: ConnectorCredentialPair, d...
52
1,727
onyx
backend/onyx/db/sync_record.py
.py
from sqlalchemy import and_, desc, func, select, update from sqlalchemy.orm import Session from onyx.db.enums import SyncStatus, SyncType from onyx.db.models import SyncRecord from onyx.utils.logger import setup_logger logger = setup_logger() def insert_sync_record( db_session: Session, entity_id: int, ...
159
4,809
onyx
backend/onyx/db/user_usage.py
.py
"""Daily per-user LLM usage rollup for cost/token attribution. A window rollup: rows accumulate in place per (user, window, model, flow, provider, incognito), not an append-only per-call ledger.""" from collections import defaultdict from collections.abc import Iterator, Sequence from datetime import datetime, timede...
561
18,675
onyx
backend/onyx/db/document_access.py
.py
"""SQL filters matching indexed document visibility.""" from uuid import UUID from sqlalchemy import Select, String, and_, any_, cast, or_, select from sqlalchemy.dialects import postgresql from sqlalchemy.orm import Session from sqlalchemy.sql.elements import ColumnElement from onyx.db.connector_credential_pair imp...
78
2,524
onyx
backend/onyx/db/permissions.py
.py
""" DB operations for recomputing user effective_permissions. These live in onyx/db/ (not onyx/auth/) because they are pure DB operations that query PermissionGrant rows and update the User.effective_permissions JSONB column. Keeping them here avoids circular imports when called from other onyx/db/ modules such as us...
133
4,616
onyx
backend/onyx/db/input_prompt.py
.py
from uuid import UUID from fastapi import HTTPException from sqlalchemy import or_, select from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, aliased from onyx.db.models import InputPrompt, InputPrompt__User, User from onyx.util...
250
7,325
onyx
backend/onyx/db/pydantic_type.py
.py
import json from typing import Any, Optional, Type from pydantic import BaseModel from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.types import TypeDecorator class PydanticType(TypeDecorator): impl = JSONB def __init__( self, pydantic_model: Type[BaseModel], *args: Any, **kwargs: Any...
63
1,741
onyx
backend/onyx/db/tag.py
.py
from typing import Any from sqlalchemy import and_, delete, or_, select from sqlalchemy.dialects.postgresql import insert as pg_insert from sqlalchemy.orm import Session, aliased from onyx.configs.constants import DocumentSource from onyx.db.models import Document, Document__Tag, Tag from onyx.utils.logger import set...
304
9,997
onyx
backend/onyx/db/hook.py
.py
import datetime from uuid import UUID from sqlalchemy import delete, select from sqlalchemy.engine import CursorResult from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, selectinload from onyx.db.constants import UNSET, UnsetType from onyx.db.enums import HookFailStrategy, HookPoint from on...
230
7,183
onyx
backend/onyx/db/chat_search.py
.py
from typing import List, Optional, Tuple from uuid import UUID from sqlalchemy import ColumnElement, column, desc, func, select from sqlalchemy.orm import Session, joinedload from sqlalchemy.sql.expression import ColumnClause from onyx.db.models import ChatMessage, ChatSession def search_chat_sessions( user_id:...
107
3,508
onyx
backend/onyx/db/notification.py
.py
from datetime import datetime, timezone from uuid import UUID from sqlalchemy import JSON, cast, select, update from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql import insert from sqlalchemy.orm import Session from sqlalchemy.sql import func from sqlalchemy.sql.elements import ColumnEleme...
315
10,363
onyx
backend/onyx/db/targeted_reindex.py
.py
"""DB helpers for the targeted-reindex flow. The API path takes a list of error IDs (failure-driven retry) or a list of `(cc_pair_id, document_id)` tuples (arbitrary reindex), validates + dedups them, then writes: 1. one `targeted_reindex_job` row, 2. N `targeted_reindex_job_target` rows (one per doc), 3....
401
14,163
onyx
backend/onyx/db/user_preferences.py
.py
from collections.abc import Sequence from uuid import UUID from sqlalchemy import Column, delete, desc, select, update from sqlalchemy.orm import Session from onyx.auth.schemas import UserRole from onyx.db.enums import AccountType, DefaultAppMode, ThemePreference from onyx.db.models import ( AccessToken, Assi...
409
12,286
onyx
backend/onyx/db/port_orphan_candidate.py
.py
"""Tracking of docs deleted mid-port so a delete that races the reindex port isn't left resurrected in the target index — the port's create-only write can't tell a just-deleted chunk from a never-written one, so a copy landing after the delete re-adds the doc (which then has no Postgres row and is never cleaned up). Th...
202
7,676
onyx
backend/onyx/db/indexing_coordination.py
.py
"""Database-based indexing coordination to replace Redis fencing.""" from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session from onyx.db.enums import IndexingStatus from onyx.db.index_attempt import ( count_error_rows_for_index_at...
268
9,262
onyx
backend/onyx/db/skill.py
.py
"""DB operations for skill rows. Management authorization: - `VIEW` includes associated custom rows but excludes associated built-in provider rows, applies normal ownership and sharing visibility, and lets admins view all remaining skills. - `EDIT` is the skill mutation policy. It excludes built-in rows and only ...
684
21,280
onyx
backend/onyx/db/document.py
.py
import contextlib import time from collections.abc import Generator, Iterable, Sequence from datetime import datetime, timedelta, timezone from typing import Any from uuid import UUID from sqlalchemy import ( CompoundSelect, Select, and_, delete, distinct, exists, func, literal, or_...
1,974
68,597
onyx
backend/onyx/db/slack_bot.py
.py
from collections.abc import Sequence from sqlalchemy import select from sqlalchemy.orm import Session from onyx.db.models import SlackBot def insert_slack_bot( db_session: Session, name: str, enabled: bool, bot_token: str, app_token: str, user_token: str | None = None, ) -> SlackBot: sla...
81
1,944
onyx
backend/onyx/db/credentials.py
.py
from typing import Any from sqlalchemy import Select, exists, select, update from sqlalchemy.orm import Session from sqlalchemy.sql.expression import and_, or_ from onyx.auth.schemas import UserRole from onyx.configs.constants import DocumentSource, NotificationType from onyx.db.connector_alerts import clear_connecto...
483
15,808
onyx
backend/onyx/db/tools.py
.py
from typing import TYPE_CHECKING, Any, Type, cast from uuid import UUID from sqlalchemy import func, or_, select from sqlalchemy.orm import Session from onyx.db.constants import UNSET, UnsetType from onyx.db.enums import MCPServerStatus from onyx.db.models import MCPServer, OAuthConfig, Tool, ToolCall from onyx.serve...
296
9,700
onyx
backend/onyx/db/image_generation.py
.py
from sqlalchemy import select, update from sqlalchemy.orm import Session, selectinload from onyx.db.models import ImageGenerationConfig, LLMProvider, ModelConfiguration from onyx.llm.model_capabilities import get_max_input_tokens from onyx.utils.logger import setup_logger logger = setup_logger() # Default image gene...
242
7,528
onyx
backend/onyx/db/admin_banner.py
.py
from datetime import datetime, timezone from pydantic import BaseModel from onyx.key_value_store.factory import get_kv_store from onyx.key_value_store.interface import KvKeyNotFoundError from onyx.utils.logger import setup_logger logger = setup_logger() # The banner's authored content is one global fact, stored as ...
58
1,686
onyx
backend/onyx/db/tasks.py
.py
from datetime import datetime from sqlalchemy import desc, func, select from sqlalchemy.orm import Session from sqlalchemy.sql import delete from onyx.configs.app_configs import JOB_TIMEOUT from onyx.db.engine.time_utils import get_db_current_time from onyx.db.models import TaskQueueState, TaskStatus def get_latest...
162
4,086