diff --git a/.github/workflows/gaussdb-smoke.yml b/.github/workflows/gaussdb-smoke.yml new file mode 100644 index 000000000..91e7cc0d4 --- /dev/null +++ b/.github/workflows/gaussdb-smoke.yml @@ -0,0 +1,177 @@ +name: openGauss dialect smoke + +# 手动触发:在真实 openGauss 容器上验证数据库方言层 +# (create_all + 方言 DDL 索引 + Alembic 基线 + JSONB 路径回退 + advisory lock + 渠道锁)。 +# 说明:本工作流只验证数据库层,不启动完整应用(应用启动还依赖 Harness v3 运行时构建产物)。 +on: + workflow_dispatch: + +# CodeQL(actions/missing-workflow-permissions):最小权限运行,仅需读取代码 +permissions: + contents: read + +jobs: + smoke: + runs-on: ubuntu-latest + timeout-minutes: 40 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Start openGauss + run: | + set -euo pipefail + GAUSS_PASSWORD="Gs$(openssl rand -hex 9)_aB1" + echo "GAUSS_PASSWORD=$GAUSS_PASSWORD" >> "$GITHUB_ENV" + docker run -d --name opengauss --privileged=true \ + -e GS_PASSWORD="$GAUSS_PASSWORD" \ + -p 5432:5432 \ + opengauss/opengauss:5.0.0 + for i in $(seq 1 180); do + if docker exec -u opengauss opengauss sh -c \ + 'export GAUSSHOME=/usr/local/opengauss; export LD_LIBRARY_PATH=$GAUSSHOME/lib; $GAUSSHOME/bin/gsql -d postgres -c "select 1"' >/dev/null 2>&1; then + echo "openGauss ready after ${i}s" + break + fi + sleep 1 + if [ "$i" -eq 180 ]; then + echo "openGauss failed to become ready" + docker logs opengauss + exit 1 + fi + done + # openGauss 默认 0.0.0.0/0 使用 sha256 认证,psycopg3 不支持该 SASL 机制; + # CI 冒烟改为 trust(仅容器内网测试用),真实部署请配置 md5/证书等。 + docker exec -u root opengauss sh -c \ + "sed -i 's|host all all 0.0.0.0/0 sha256|host all all 0.0.0.0/0 trust|' /var/lib/opengauss/data/pg_hba.conf" + docker exec -u opengauss opengauss sh -c \ + 'export GAUSSHOME=/usr/local/opengauss; export LD_LIBRARY_PATH=$GAUSSHOME/lib; $GAUSSHOME/bin/gsql -d postgres -c "select pg_reload_conf()"' >/dev/null + docker exec -u opengauss opengauss sh -c \ + 'export GAUSSHOME=/usr/local/opengauss; export LD_LIBRARY_PATH=$GAUSSHOME/lib; $GAUSSHOME/bin/gsql -d postgres -c "select version()"' | head -3 + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install backend deps + run: | + set -euo pipefail + python -m venv .venv + .venv/bin/pip install -q -e "backend[dev,postgres]" + + - name: Dialect smoke on openGauss + env: + DATABASE_URL: opengauss+psycopg://gaussdb:unused@127.0.0.1:5432/postgres + APP_SECRET: openGauss-smoke + STAFFDECK_ROLE: all + working-directory: backend + run: | + set -euo pipefail + ../.venv/bin/python - <<'PY' + from sqlalchemy import func, inspect + from sqlmodel import Session, select + + from app.db.database import engine, init_db + from app.db.dialect import get_dialect + + assert engine.url.get_backend_name() == "opengauss" + init_db() # 全新空库:create_all + Alembic 基线 stamp + insp = inspect(engine) + tables = insp.get_table_names() + assert "alembic_version" in tables, "missing alembic_version" + assert len(tables) >= 76, f"unexpected table count: {len(tables)}" + index_names = { + index["name"] + for table in ("sessions", "model_configs") + for index in insp.get_indexes(table) + } + assert "uq_sessions_agent_channel_extconv" in index_names, "missing sessions index" + assert "uq_model_configs_tenant_default" in index_names, "missing default-model partial index" + print("create_all + dialect DDL indexes on openGauss: OK") + + init_db() # 已有 alembic_version:upgrade head 幂等 + print("second init_db (alembic upgrade path): OK") + + from app.api.knowledge import _safe_document_bucket_rows + from app.channels.config_store import patch_binding_config + from app.channels.delivery_days import delivery_day_bucket + from app.db.models import ( + AgentProfile, + ChannelBinding, + ChannelDelivery, + ChatSession, + KnowledgeBucket, + KnowledgeChunk, + Tenant, + User, + utc_now, + ) + + dialect = get_dialect(engine.url.get_backend_name()) + assert dialect.supports_partial_index is True + + with Session(engine) as db: + db.add(Tenant(id="tenant_smoke", name="Smoke", created_at=utc_now(), updated_at=utc_now())) + db.add(User(id="user_smoke", tenant_id="tenant_smoke", username="smoke", + password_hash="x", role="admin")) + db.add(AgentProfile(id="agent_smoke", tenant_id="tenant_smoke", name="Smoke Agent")) + db.add(ChatSession(id="sess_smoke", tenant_id="tenant_smoke", + user_id="user_smoke", agent_id="agent_smoke")) + db.add(ChannelBinding(id="bind_smoke", tenant_id="tenant_smoke", agent_id="agent_smoke", + channel="wecom", status="active", + created_at=utc_now(), updated_at=utc_now())) + db.commit() + + # openGauss 的 jsonb_set 与上游 PG 参数语义不同 -> 走通用 ORM 回退 + assert patch_binding_config(db, "bind_smoke", tenant_id="tenant_smoke", + set_values={"auto_route": False, "n": 1}) + db.commit() + db.refresh(db.get(ChannelBinding, "bind_smoke")) + assert db.get(ChannelBinding, "bind_smoke").config_json["n"] == 1 + assert patch_binding_config(db, "bind_smoke", remove_keys=("auto_route",), + require_active=True) + db.commit() + print("config patch (generic ORM fallback): OK") + + db.add(ChannelDelivery(id="del_smoke", tenant_id="tenant_smoke", + binding_id="bind_smoke", session_id="sess_smoke", + kind="reply", status="sent", idempotency_key="idem_smoke", + created_at=utc_now(), updated_at=utc_now())) + db.add(KnowledgeBucket(id="bucket_smoke", tenant_id="tenant_smoke", + knowledge_base_id="kb_smoke", document_id="doc_smoke", + bucket_key="b", title="中文标题", summary="S", + token_estimate=1, metadata_json={"a": 1}, + created_at=utc_now(), updated_at=utc_now())) + db.add(KnowledgeChunk(id="chunk_smoke", tenant_id="tenant_smoke", + knowledge_base_id="kb_smoke", document_id="doc_smoke", + bucket_id="bucket_smoke", chunk_index=0, + content="hello 世界", metadata_json={"x": [1, 2]}, + created_at=utc_now(), updated_at=utc_now())) + db.commit() + day_expr = delivery_day_bucket(db) + row = db.exec(select(day_expr, func.count()).group_by(day_expr)).first() + assert row is not None + buckets = _safe_document_bucket_rows(db, "tenant_smoke", "doc_smoke") + assert buckets and buckets[0]["title"] == "中文标题" + print("delivery_day_bucket + knowledge ORM (UTF-8): OK") + + with Session(engine) as lock_session: + assert dialect.acquire_advisory_lock(lock_session, "smoke-connector") + assert dialect.check_advisory_lock(lock_session, "smoke-connector") + dialect.release_advisory_lock(lock_session, "smoke-connector") + assert not dialect.check_advisory_lock(lock_session, "smoke-connector") + print("advisory lock acquire/check/release: OK") + + from app.channels import ( + _acquire_connector_process_lock, + _connector_lock_healthy, + _release_connector_process_lock, + ) + + assert _acquire_connector_process_lock() is True + assert _connector_lock_healthy() is True + _release_connector_process_lock() + print("channel connector single-instance lock: OK") + print("OPENGAUSS DIALECT SMOKE ALL OK") + PY diff --git a/README.md b/README.md index 1e1ec24d9..82cae8f12 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,35 @@ Digital employees can serve users directly over IM channels: users chat with emp - Channel credentials (bot tokens/secrets) are stored Fernet-encrypted and never returned by any API; - Binding management is restricted to admins or the binding creator; mounting an employee exposes it to all users of that channel — grant with care. +## Database Backends + +StaffDeck keeps all state in one SQL database and defaults to local SQLite (zero setup). The data layer is dialect-pluggable: business code goes through SQLAlchemy ORM, and the few dialect-specific points (day bucketing, JSON config patching, process/advisory locks, partial indexes) are centralized in `backend/app/db/dialect.py`. + +| Backend | Status | Notes | +| --- | --- | --- | +| SQLite (default) | Supported | File database; connector/binding process locks are file locks placed next to the DB file. Schema changes use the built-in startup migrations (behavior unchanged). | +| PostgreSQL | Experimental | Full feature set via the `postgresql` dialect. Install the optional driver first: `pip install "skill-agent-loop-backend[postgres]"`, then set `DATABASE_URL="postgresql+psycopg://user:pass@host:5432/dbname"` in `backend/.env`. Existing databases are upgraded with Alembic (see below). | +| openGauss (高斯) | Experimental | Uses the PostgreSQL protocol through a small compatibility dialect (`opengauss+psycopg://user:pass@host:5432/postgres`, same `[postgres]` driver) that handles the openGauss version string and forces `client_encoding=utf8`. Full dialect capabilities including the partial unique index and session advisory locks; existing databases are upgraded with Alembic. Verified against openGauss 5.0 (Docker). | +| MySQL 8.x | Experimental | Install the optional driver: `pip install "skill-agent-loop-backend[mysql]"` (PyMySQL), then set `DATABASE_URL="mysql+pymysql://user:pass@host:3306/dbname?charset=utf8mb4"`. No partial unique indexes: the "one default model per tenant" invariant is enforced in code plus a startup check. The connector single-instance guard uses `GET_LOCK()` named locks. JSON columns stay native JSON; long-text columns are `TEXT`/`MEDIUMTEXT` (no silent VARCHAR(255) truncation). Verified against MySQL 8.4. | +| Dameng (达梦) | Adapter needed | Requires the `dmPython` driver plus a third-party SQLAlchemy Dameng dialect plugin (not bundled or verified by this repository). JSON columns degrade to CLOB via `PortableJSON`, long-text columns are `TEXT`. Without a native advisory-lock implementation the connector lock fails loudly at startup instead of silently mis-locking. | + +### Database migrations (non-SQLite) + +SQLite keeps its existing startup path (`create_all` plus the built-in migrations). Non-SQLite backends are managed by Alembic, so existing schemas can be upgraded across releases: + +- fresh database: `init_db` creates the schema with `create_all` (including dialect-specific DDL such as the partial unique index) and stamps the baseline revision; +- existing schema without `alembic_version`: stamped at head with a warning — review schema compatibility manually before upgrading; +- database with `alembic_version`: `init_db` runs `alembic upgrade head` at startup. + +To add a schema change: update the models, then run `cd backend && DATABASE_URL=... .venv/bin/python -m alembic revision --autogenerate -m "..."` and commit the new revision. Migration scripts live in `backend/app/db/migrations/` and are shipped with the wheel and the bundled app. + +Limitations when running on PostgreSQL/MySQL/openGauss: + +- **Single-writer startup**: run only one application worker during first boot/upgrades — concurrent `create_all` + demo seeding from multiple workers can race (DuplicateTable / unique conflicts). Initialize once with a single worker. +- `APP_TIMEZONE` only affects PostgreSQL day bucketing; on SQLite, day buckets always use the server's local timezone (setting it there logs a warning and is ignored). +- Run exactly one connector process per database — the single-instance guard uses a session-scoped PostgreSQL/openGauss advisory lock (dedicated autocommit connection) or a MySQL `GET_LOCK()` named lock, with periodic liveness checks (channel services degrade and stop if the lock is lost). +- MySQL/Dameng have no partial unique index for the "one default model per tenant" rule: it is enforced in code plus a startup validation, not by a database constraint. + ## Project Structure ```text diff --git a/README.zh.md b/README.zh.md index 2cb0c1456..8eb9ba803 100644 --- a/README.zh.md +++ b/README.zh.md @@ -285,6 +285,35 @@ curl.exe http://127.0.0.1:5173/api/health 外部业务系统可以通过员工级 API Key 调用数字员工、持续会话、Harness v2 Run、SOP、知识、技能、工具和定时任务。完整的鉴权边界、接口清单、SSE、Webhook 与调用示例见 [数字员工开放 API v1](docs/open-api-v1.md)。 +## 数据库后端 + +StaffDeck 的全部状态存放在一个 SQL 数据库中,默认使用本地 SQLite(零配置)。数据访问层为方言可插拔设计:业务代码统一走 SQLAlchemy ORM,少数方言相关点(日分桶、JSON 配置补丁、进程/advisory 锁、部分索引)集中收口在 `backend/app/db/dialect.py`。 + +| 后端 | 状态 | 说明 | +| --- | --- | --- | +| SQLite(默认) | 支持 | 文件库;connector/binding 进程锁为数据库文件旁的文件锁。schema 变更走内置启动迁移(行为不变)。 | +| PostgreSQL | 实验性 | 通过 `postgresql` 方言提供全能力。需先安装可选驱动:`pip install "skill-agent-loop-backend[postgres]"`,再在 `backend/.env` 设置 `DATABASE_URL="postgresql+psycopg://user:pass@host:5432/dbname"`。存量库由 Alembic 管理升级(见下文)。 | +| openGauss(高斯) | 实验性 | 通过 PostgreSQL 协议 + 轻量兼容方言使用(`DATABASE_URL="opengauss+psycopg://user:pass@host:5432/postgres"`,复用 `[postgres]` 可选驱动):自定义方言处理 openGauss 的版本串并强制 `client_encoding=utf8`。具备全部方言能力(含部分唯一索引与会话级 advisory lock),存量库同样由 Alembic 管理升级。已在 openGauss 5.0(Docker)上验证。 | +| MySQL 8.x | 实验性 | 需先安装可选驱动:`pip install "skill-agent-loop-backend[mysql]"`(PyMySQL),再设置 `DATABASE_URL="mysql+pymysql://user:pass@host:3306/dbname?charset=utf8mb4"`。不支持部分唯一索引:"每租户至多一条默认模型"改由代码层维护 + 启动校验兜底(运行期无 DB 级约束)。connector 单实例锁使用 `GET_LOCK()` 命名锁。JSON 列保持原生 JSON,长文本列显式 `TEXT`/`MEDIUMTEXT`(不会静默退化为 VARCHAR(255) 截断)。已在 MySQL 8.4 上验证。 | +| 达梦(Dameng) | 需适配器 | 需要 `dmPython` 驱动 + 部署方提供第三方 SQLAlchemy 达梦方言插件(本仓库未预装、未真机验证)。JSON 列经 `PortableJSON` 降级为 CLOB,长文本列显式 `TEXT`。未实现原生 advisory lock 时,connector 锁会在启动期响亮失败,而不是静默错锁。 | + +### 数据库迁移(非 SQLite) + +SQLite 保持既有启动路径(`create_all` + 内置迁移)不变;非 SQLite 后端由 Alembic 管理,存量 schema 可跨版本升级: + +- 全新空库:`init_db` 用 `create_all` 建当前 schema(含部分唯一索引等方言 DDL),并按 Alembic 基线版本 stamp; +- 已有应用表但没有 `alembic_version`:按基线 stamp head 并输出告警——升级前请人工核对既有 schema 与当前版本是否一致; +- 已有 `alembic_version`:启动时执行 `alembic upgrade head` 应用未执行的迁移。 + +新增 schema 变更:修改 models 后执行 `cd backend && DATABASE_URL=... .venv/bin/python -m alembic revision --autogenerate -m "..."`,提交生成的 revision。迁移脚本位于 `backend/app/db/migrations/`,随 wheel 与打包产物一并分发。 + +在 PostgreSQL/MySQL/openGauss 上运行的当前限制: + +- **单写者启动**:首次启动/升级只跑一个应用 worker——多 worker 并发 `create_all` + 演示数据播种会撞键,请先用单 worker 完成初始化; +- `APP_TIMEZONE` 只对 PostgreSQL 日分桶生效;SQLite 的日分桶恒为服务器本地时区(该配置在 SQLite 下会输出告警并被忽略); +- 每个数据库只允许运行一个 connector 进程——单实例守护使用会话级 PostgreSQL/openGauss advisory lock(专属 AUTOCOMMIT 连接)或 MySQL `GET_LOCK()` 命名锁,并带定期存活校验(锁失效时渠道服务主动降级停止); +- MySQL/达梦没有部分唯一索引,"每租户至多一条默认模型"由代码层维护 + 启动校验兜底,不是数据库约束。 + ## 项目结构 ```text diff --git a/backend/.env.example b/backend/.env.example index acdc24dfa..c15db4b5a 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,5 +1,12 @@ APP_NAME="Skill Agent Loop Service" +# 默认 SQLite;PostgreSQL 改为 postgresql+psycopg://user:pass@host:5432/dbname, +# openGauss(高斯)改为 opengauss+psycopg://user:pass@host:5432/postgres +# (两者都需先安装可选驱动:pip install "skill-agent-loop-backend[postgres]") +# MySQL 8.x:mysql+pymysql://user:pass@host:3306/dbname?charset=utf8mb4 +# (可选驱动:pip install "skill-agent-loop-backend[mysql]") DATABASE_URL="sqlite:///./skill_agent_loop.db" +# 应用时区(如 Asia/Shanghai):仅 PostgreSQL 日分桶换算使用,SQLite 恒为服务器本地时区 +APP_TIMEZONE="" # Leave empty on a fresh install to generate and persist a random signing key. # On upgrades retain the original APP_SECRET exactly. APP_SECRET="" diff --git a/backend/alembic.ini b/backend/alembic.ini new file mode 100644 index 000000000..829e85025 --- /dev/null +++ b/backend/alembic.ini @@ -0,0 +1,15 @@ +# Alembic 迁移配置。 +# +# - script_location 用 %(here)s 展开为 backend/app/db/migrations 的绝对路径,不依赖 +# 执行时的 CWD;迁移目录放在 app 包内,便于 wheel/PyInstaller 一并分发; +# - sqlalchemy.url 留空:alembic/env.py 会回退到应用配置 +# (app.config.get_settings().database_url);程序化调用(init_db)通过 +# Config.set_main_option("sqlalchemy.url", ...) 显式传入运行时 URL。 +# - 本地验证示例: +# cd backend && DATABASE_URL=sqlite:////tmp/staffdeck-alembic.db \ +# .venv/bin/python -m alembic upgrade head +[alembic] +script_location = %(here)s/app/db/migrations +prepend_sys_path = . +path_separator = os +sqlalchemy.url = diff --git a/backend/app/api/knowledge.py b/backend/app/api/knowledge.py index 6fd7c67ea..b9c65bb52 100644 --- a/backend/app/api/knowledge.py +++ b/backend/app/api/knowledge.py @@ -936,67 +936,125 @@ def bucket_read_with_stats(row: KnowledgeBucket, chunk_count: int) -> KnowledgeB return item +_BUCKET_ROW_FIELDS = ( + "id", + "tenant_id", + "knowledge_base_id", + "knowledge_base_version_id", + "document_id", + "bucket_key", + "title", + "summary", + "token_estimate", + "metadata_json", + "created_at", + "updated_at", +) +_CHUNK_ROW_FIELDS = ( + "id", + "tenant_id", + "knowledge_base_id", + "knowledge_base_version_id", + "document_id", + "bucket_id", + "chunk_index", + "content", + "summary", + "source_ref", + "metadata_json", + "created_at", + "updated_at", +) + + +def _model_row_mapping(row: Any, fields: tuple[str, ...]) -> Mapping[str, Any]: + """ORM 对象转与原 CAST AS BLOB 查询同形的 Mapping(下游统一走 _safe_* 读取)。""" + return {field: getattr(row, field) for field in fields} + + def _safe_document_bucket_rows( db: Session, tenant_id: str, document_id: str ) -> list[Mapping[str, Any]]: - return list( - db.execute( - text( - """ - SELECT - id, - tenant_id, - knowledge_base_id, - knowledge_base_version_id, - document_id, - CAST(bucket_key AS BLOB) AS bucket_key, - CAST(title AS BLOB) AS title, - CAST(summary AS BLOB) AS summary, - token_estimate, - CAST(metadata_json AS BLOB) AS metadata_json, - created_at, - updated_at - FROM knowledge_buckets - WHERE tenant_id = :tenant_id AND document_id = :document_id - ORDER BY created_at ASC - """ - ), - {"tenant_id": tenant_id, "document_id": document_id}, + # SQLite:文本列可能混入非 UTF-8 字节,CAST AS BLOB 取原始字节交给 _safe_text 解码; + # 其它后端走 ORM(驱动返回规范 str,无需 BLOB 兜底) + if db.get_bind().url.get_backend_name() == "sqlite": + return list( + db.execute( + text( + """ + SELECT + id, + tenant_id, + knowledge_base_id, + knowledge_base_version_id, + document_id, + CAST(bucket_key AS BLOB) AS bucket_key, + CAST(title AS BLOB) AS title, + CAST(summary AS BLOB) AS summary, + token_estimate, + CAST(metadata_json AS BLOB) AS metadata_json, + created_at, + updated_at + FROM knowledge_buckets + WHERE tenant_id = :tenant_id AND document_id = :document_id + ORDER BY created_at ASC + """ + ), + {"tenant_id": tenant_id, "document_id": document_id}, + ) + .mappings() + .all() ) - .mappings() - .all() - ) + rows = db.exec( + select(KnowledgeBucket) + .where( + KnowledgeBucket.tenant_id == tenant_id, + KnowledgeBucket.document_id == document_id, + ) + .order_by(KnowledgeBucket.created_at.asc()) + ).all() + return [_model_row_mapping(row, _BUCKET_ROW_FIELDS) for row in rows] def _safe_bucket_chunk_rows(db: Session, tenant_id: str, bucket_id: str) -> list[Mapping[str, Any]]: - return list( - db.execute( - text( - """ - SELECT - id, - tenant_id, - knowledge_base_id, - knowledge_base_version_id, - document_id, - bucket_id, - chunk_index, - CAST(content AS BLOB) AS content, - CAST(summary AS BLOB) AS summary, - CAST(source_ref AS BLOB) AS source_ref, - CAST(metadata_json AS BLOB) AS metadata_json, - created_at, - updated_at - FROM knowledge_chunks - WHERE tenant_id = :tenant_id AND bucket_id = :bucket_id - ORDER BY chunk_index ASC - """ - ), - {"tenant_id": tenant_id, "bucket_id": bucket_id}, + if db.get_bind().url.get_backend_name() == "sqlite": + return list( + db.execute( + text( + """ + SELECT + id, + tenant_id, + knowledge_base_id, + knowledge_base_version_id, + document_id, + bucket_id, + chunk_index, + CAST(content AS BLOB) AS content, + CAST(summary AS BLOB) AS summary, + CAST(source_ref AS BLOB) AS source_ref, + CAST(metadata_json AS BLOB) AS metadata_json, + created_at, + updated_at + FROM knowledge_chunks + WHERE tenant_id = :tenant_id AND bucket_id = :bucket_id + ORDER BY chunk_index ASC + """ + ), + {"tenant_id": tenant_id, "bucket_id": bucket_id}, + ) + .mappings() + .all() ) - .mappings() - .all() - ) + rows = db.exec( + select(KnowledgeChunk) + .where( + KnowledgeChunk.tenant_id == tenant_id, + KnowledgeChunk.bucket_id == bucket_id, + ) + .order_by(KnowledgeChunk.chunk_index.asc()) + ).all() + return [_model_row_mapping(row, _CHUNK_ROW_FIELDS) for row in rows] def _bucket_read_mapping_with_stats( diff --git a/backend/app/channels/__init__.py b/backend/app/channels/__init__.py index 8531e7242..963efaa0a 100644 --- a/backend/app/channels/__init__.py +++ b/backend/app/channels/__init__.py @@ -6,8 +6,6 @@ import time from contextlib import contextmanager, nullcontext from contextvars import ContextVar -from pathlib import Path -from typing import IO from app.config import get_settings @@ -20,78 +18,119 @@ _dingtalk_stream_manager = None _binding_lifecycle_locks: dict[str, threading.RLock] = {} _binding_lifecycle_locks_guard = threading.Lock() -_connector_lock_file: IO[bytes] | None = None +# connector 单实例锁:统一锁 key;PG 持锁连接由方言常驻(_connector_lock_session 仅作 bind 来源) +_CONNECTOR_LOCK_KEY = "staffdeck-connector" _connector_lock_pid: int | None = None +_connector_lock_session = None _intake_sweep_thread: threading.Thread | None = None +_connector_lock_watchdog_thread: threading.Thread | None = None +# PG advisory lock 存活校验周期(秒):连接被服务端掐断后锁会静默释放,须定期核实 +_CONNECTOR_LOCK_CHECK_SECONDS = 15.0 _binding_adapter_scope: ContextVar[dict | None] = ContextVar("binding_adapter_scope", default=None) def _acquire_connector_process_lock() -> bool: - global _connector_lock_file, _connector_lock_pid + """单实例 connector 锁:走方言提供者(PG=advisory lock,其它=数据目录文件锁)。 + + preload+fork 部署下,子进程不得把继承的锁状态当作自己持有。 + """ + global _connector_lock_pid, _connector_lock_session current_pid = os.getpid() - if _connector_lock_file is not None and _connector_lock_pid == current_pid: + if _connector_lock_pid == current_pid: return True - if _connector_lock_file is not None: - # preload 后 fork 的子进程不能把继承句柄当作自己已持有锁。 - _connector_lock_file.close() - _connector_lock_file = None + if _connector_lock_pid is not None: + # fork 子进程:继承的会话/句柄只丢弃引用,不在共享连接上做任何操作 + _connector_lock_session = None _connector_lock_pid = None - from app.db import engine + from sqlmodel import Session - database_path = engine.url.database - if engine.url.get_backend_name() != "sqlite" or not database_path or database_path == ":memory:": - logger.error("渠道服务要求文件 SQLite 进程锁;当前数据库不支持可靠的单实例 Outbox") - return False - lock_path = Path(database_path).resolve().with_name(f"{Path(database_path).name}.connector.lock") - handle = lock_path.open("a+b") - try: - if os.name == "nt": - import msvcrt - - handle.seek(0) - if handle.read(1) == b"": - handle.write(b"0") - handle.flush() - handle.seek(0) - msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) - else: - import fcntl - - fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - except (BlockingIOError, OSError): - handle.close() - return False - _connector_lock_file = handle + from app.db import engine + from app.db.dialect import get_dialect + + dialect = get_dialect(engine.url.get_backend_name()) + if dialect.session_scoped_advisory_lock: + # PG advisory lock 随连接存活:专属连接由方言内部常驻,此会话仅作 bind 来源 + session = Session(engine) + if not dialect.acquire_advisory_lock(session, _CONNECTOR_LOCK_KEY): + session.close() + logger.error("另一 connector 进程已持有该数据库的 advisory lock") + return False + _connector_lock_session = session + else: + # SQLite/其它:数据目录文件锁(锁句柄由方言实例持有,行为不变) + with Session(engine) as session: + if not dialect.acquire_advisory_lock(session, _CONNECTOR_LOCK_KEY): + return False _connector_lock_pid = current_pid return True def _release_connector_process_lock() -> None: - global _connector_lock_file, _connector_lock_pid - handle = _connector_lock_file - if handle is None: + global _connector_lock_pid, _connector_lock_session + if _connector_lock_pid is None: return if _connector_lock_pid != os.getpid(): - handle.close() - _connector_lock_file = None + # fork 子进程:仅丢弃引用,不解父进程的锁 + _connector_lock_session = None _connector_lock_pid = None return - try: - if os.name == "nt": - import msvcrt + from sqlmodel import Session - handle.seek(0) - msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) - else: - import fcntl + from app.db import engine + from app.db.dialect import get_dialect - fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + dialect = get_dialect(engine.url.get_backend_name()) + session, _connector_lock_session = _connector_lock_session, None + try: + try: + if session is not None: + dialect.release_advisory_lock(session, _CONNECTOR_LOCK_KEY) + else: + with Session(engine) as fallback_session: + dialect.release_advisory_lock(fallback_session, _CONNECTOR_LOCK_KEY) + except Exception: + # 会话可能已随连接中断死亡(锁实际已被服务端释放),释放失败只记录不抛出 + logger.exception("释放 connector 锁失败(锁可能已随断连释放)") finally: - handle.close() - _connector_lock_file = None + if session is not None: + session.close() _connector_lock_pid = None +def _connector_lock_healthy() -> bool: + """会话级 advisory lock 存活校验;文件锁无静默失效模式,恒为 True。""" + if _connector_lock_session is None: + return True + from app.db import engine + from app.db.dialect import get_dialect + + dialect = get_dialect(engine.url.get_backend_name()) + try: + return dialect.check_advisory_lock(_connector_lock_session, _CONNECTOR_LOCK_KEY) + except Exception: + logger.exception("connector 锁存活校验异常") + return False + + +def _connector_lock_watchdog() -> None: + """PG advisory lock 断连检测:锁静默失效后主动降级(停渠道服务,避免双 connector)。""" + while True: + time.sleep(_CONNECTOR_LOCK_CHECK_SECONDS) + if _connector_lock_pid != os.getpid() or _connector_lock_session is None: + return # 锁已正常释放或本进程不再持有,看门狗退出 + if _connector_lock_healthy(): + continue + logger.error( + "connector advisory lock 已失效(数据库连接中断),渠道服务主动降级停止;" + "恢复后请重启进程重新接管" + ) + try: + stop_channel_services() + except Exception: + logger.exception("渠道服务降级停止失败") + return + + def get_wechat_poll_manager(): global _wechat_poll_manager if _wechat_poll_manager is None: @@ -134,7 +173,8 @@ def channel_services_enabled() -> bool: def channel_services_running() -> bool: - return _connector_lock_file is not None and _connector_lock_pid == os.getpid() + """本进程是否持有 connector 单实例锁(渠道服务正在运行)。""" + return _connector_lock_pid == os.getpid() def _ensure_adapters_registered() -> None: @@ -250,7 +290,7 @@ def restart_binding_ingress(channel: str, binding_id: str, *, wait_seconds: floa def start_channel_services() -> None: - global _intake_sweep_thread + global _intake_sweep_thread, _connector_lock_watchdog_thread if not channel_services_enabled(): logger.info("staffdeck_role=%s,渠道服务不启动", get_settings().staffdeck_role) return @@ -277,6 +317,14 @@ def start_channel_services() -> None: daemon=True, ) _intake_sweep_thread.start() + if _connector_lock_session is not None: + # 会话级 advisory lock(PG):定期核实锁仍持有,断连静默失效时主动降级 + _connector_lock_watchdog_thread = threading.Thread( + target=_connector_lock_watchdog, + name="staffdeck-connector-lock-watchdog", + daemon=True, + ) + _connector_lock_watchdog_thread.start() except Exception: stop_channel_services() raise diff --git a/backend/app/channels/config_store.py b/backend/app/channels/config_store.py index d65d562c0..bd94c094d 100644 --- a/backend/app/channels/config_store.py +++ b/backend/app/channels/config_store.py @@ -3,34 +3,101 @@ from sqlalchemy import JSON, Text, cast, func, literal, update from sqlalchemy.dialects.postgresql import JSONB, array +from sqlmodel import select +from app.db.dialect import get_dialect from app.db.models import ChannelBinding, utc_now +def _patch_binding_config_generic(db, binding_id, dialect, *, tenant_id=None, set_values=None, + remove_keys=(), expected_revision=None, require_active=False, + expected_values=None, binding_values=None): + """其它方言的通用回退:方言助手 ORM 读-改-写 + 行锁 + config_revision CAS。 + + sqlite/postgresql 有原生 JSON 函数,走上面的单条 UPDATE 原子更新;未注册后端 + (MySQL/达梦等)没有通用 JSON SQL,只能 Python 侧读-改-写。SELECT ... FOR UPDATE + 覆盖读取到写回的窗口(方言不支持时由 SQLAlchemy 自动省略),写回再以读到的 + config_revision 做 CAS,避免与并发补丁互相覆盖。 + """ + hint = get_dialect(dialect) + binding = db.exec( + select(ChannelBinding) + .where(ChannelBinding.id == binding_id) + .with_for_update() + .execution_options(populate_existing=True) + ).first() + if binding is None: + return False + if tenant_id is not None and binding.tenant_id != tenant_id: + return False + if require_active and binding.status != "active": + return False + revision = binding.config_revision + if expected_revision is not None and revision != expected_revision: + return False + for key, value in (expected_values or {}).items(): + if hint.json_config_get(binding.config_json, key) != value: + return False + config = binding.config_json + for key, value in (set_values or {}).items(): + config = hint.json_config_set(config, key, value) + for key in remove_keys: + config = hint.json_config_remove(config, key) + values = {"updated_at": utc_now()} + if set_values or remove_keys: + values["config_json"] = config + values.update(binding_values or {}) + statement = ( + update(ChannelBinding) + .where( + ChannelBinding.id == binding_id, + ChannelBinding.config_revision == revision, + ) + .values(**values) + .execution_options(synchronize_session=False) + ) + return db.exec(statement).rowcount == 1 + + def patch_binding_config(db, binding_id, *, tenant_id=None, set_values=None, remove_keys=(), expected_revision=None, require_active=False, expected_values=None, binding_values=None): - dialect = db.get_bind(mapper=ChannelBinding).dialect.name + for key in (binding_values or {}): + if key not in {"connected", "status"}: + raise ValueError(f"unsupported binding runtime field: {key}") + bind = db.get_bind(mapper=ChannelBinding) + # 按 URL backend 判定(SQLAlchemy 方言名):openGauss 复用 PG 方言,但其 + # jsonb_set 接受 varchar[] 与否/路径语义与上游不同,走下面的通用 ORM 回退。 + backend = bind.url.get_backend_name() column = ChannelBinding.config_json - if dialect == "postgresql": + if backend == "postgresql": expression = cast(func.coalesce(column, literal({}, type_=JSON)), JSONB) for key, value in (set_values or {}).items(): expression = func.jsonb_set(expression, array([key], type_=Text), literal(value, type_=JSONB), True) for key in remove_keys: expression = expression.op("-")(literal(key, type_=Text)) - elif dialect == "sqlite": + elif backend == "sqlite": expression = func.coalesce(column, "{}") for key, value in (set_values or {}).items(): expression = func.json_set(expression, "$." + json.dumps(key), func.json(json.dumps(value, ensure_ascii=False))) for key in remove_keys: expression = func.json_remove(expression, "$." + json.dumps(key)) else: - raise RuntimeError("Selected channel storage does not support atomic JSON updates") + return _patch_binding_config_generic( + db, + binding_id, + bind.dialect.name, + tenant_id=tenant_id, + set_values=set_values, + remove_keys=remove_keys, + expected_revision=expected_revision, + require_active=require_active, + expected_values=expected_values, + binding_values=binding_values, + ) values = {"updated_at": utc_now()} if set_values or remove_keys: values["config_json"] = expression for key, value in (binding_values or {}).items(): - if key not in {"connected", "status"}: - raise ValueError(f"unsupported binding runtime field: {key}") values[key] = value statement = update(ChannelBinding).where(ChannelBinding.id == binding_id) if tenant_id is not None: diff --git a/backend/app/channels/delivery_days.py b/backend/app/channels/delivery_days.py index 5ef71ffa5..9a3fafb56 100644 --- a/backend/app/channels/delivery_days.py +++ b/backend/app/channels/delivery_days.py @@ -7,6 +7,9 @@ from fastapi import HTTPException from sqlalchemy import Date, cast, func +from app.config import get_settings +from app.db.dialect import get_dialect + def server_timezone(): candidates = [] @@ -47,7 +50,10 @@ def delivery_day_bucket(db): return func.date(ChannelDelivery.created_at, 'localtime') if dialect == 'postgresql': # Runtime timestamps are UTC-naive; convert UTC -> named server timezone - # before taking the date, including historical DST offsets. - return cast(func.timezone(server_timezone(), func.timezone('UTC', ChannelDelivery.created_at)), Date) - raise HTTPException(503, {'code':'STORAGE_DIALECT_UNSUPPORTED', - 'message':'当前存储不支持投递日志日期分组'}) + # before taking the date, including historical DST offsets. APP_TIMEZONE + # (应用时区)只对 PostgreSQL 日分桶生效,未配置时回退服务器本地时区。 + tz = (get_settings().app_timezone or '').strip() or server_timezone() + return cast(func.timezone(tz, func.timezone('UTC', ChannelDelivery.created_at)), Date) + # 其它方言:方言助手兜底(标准 SQL cast(col, Date),按数据库服务器时区取日)。 + # 未注册后端(MySQL/达梦等)同样可用,不再一律 503。 + return get_dialect(dialect).day_bucket(ChannelDelivery.created_at) diff --git a/backend/app/channels/feishu_manager.py b/backend/app/channels/feishu_manager.py index a227e55d1..c70982710 100644 --- a/backend/app/channels/feishu_manager.py +++ b/backend/app/channels/feishu_manager.py @@ -6,11 +6,10 @@ import logging import threading import time -from pathlib import Path from typing import Callable from sqlalchemy import update -from sqlmodel import Session, select +from sqlmodel import select from app.channels.feishu_process import ConnectorState, FeishuProcessSupervisor from app.db import engine @@ -31,9 +30,12 @@ def __init__( ): self._engine = db_engine or engine database = self._engine.url.database - if self._engine.url.get_backend_name() != "sqlite" or not database or database == ":memory:": - raise RuntimeError("飞书长连接首版仅支持文件 SQLite") - self._database_path = Path(database).expanduser().resolve() + if self._engine.url.get_backend_name() == "sqlite" and ( + not database or database == ":memory:" + ): + raise RuntimeError("飞书长连接子进程无法共享 SQLite 内存数据库") + # 子进程按完整 SQLAlchemy URL 自建引擎(密码不遮蔽) + self._database_url = self._engine.url.render_as_string(hide_password=False) self._supervisor_factory = supervisor_factory self._supervisor: FeishuProcessSupervisor | None = None self._reconcile_seconds = reconcile_seconds @@ -51,7 +53,7 @@ def _get_supervisor(self) -> FeishuProcessSupervisor: from staffdeck_harness.modules.registry import peek_registry from app.channels.storage import applied_fingerprint options = {"assembly_fingerprint": applied_fingerprint()} if self._engine is engine and peek_registry() else {} - self._supervisor = self._supervisor_factory(database_path=self._database_path, **options) + self._supervisor = self._supervisor_factory(database_url=self._database_url, **options) return self._supervisor def start(self) -> None: diff --git a/backend/app/channels/feishu_process.py b/backend/app/channels/feishu_process.py index b1f6ba746..6bbb95b20 100644 --- a/backend/app/channels/feishu_process.py +++ b/backend/app/channels/feishu_process.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging import multiprocessing import secrets import threading @@ -12,14 +13,19 @@ from pathlib import Path from typing import Any +from sqlalchemy.pool import NullPool +from sqlmodel import Session, create_engine + +from app.db.dialect import get_dialect from feishu_connector_worker import ( - BindingProcessLock, ConnectorChildSpec, PRODUCTION_RUNTIME, - binding_lock_path, + binding_lock_key, connector_child_entry, ) +logger = logging.getLogger(__name__) + class ConnectorState(str, Enum): ABSENT = "absent" @@ -52,6 +58,7 @@ def __init__( self, *, runtime_path: str = PRODUCTION_RUNTIME, + database_url: str | None = None, database_path: Path | None = None, data_dir: Path | None = None, watchdog_seconds: float = 2.5, @@ -70,7 +77,12 @@ def __init__( self._runtime_path = runtime_path self._assembly_fingerprint = assembly_fingerprint root = (data_dir or Path.cwd()).expanduser().resolve() - self._database_path = (database_path or root / "skill_agent_loop.db").expanduser().resolve() + # database_path 为兼容旧参数;子进程统一按完整 SQLAlchemy URL 自建引擎 + if database_url: + self._database_url = database_url + else: + legacy_path = (database_path or root / "skill_agent_loop.db").expanduser().resolve() + self._database_url = f"sqlite:///{legacy_path}" self._watchdog_seconds = watchdog_seconds self._terminate_grace_seconds = terminate_grace_seconds self._max_processes = max_processes @@ -85,7 +97,8 @@ def __init__( self._reserved_process_slots = 0 self._crashes: dict[str, deque[float]] = {} self._backoff_until: dict[str, float] = {} - self._pending_lock_paths: set[Path] = set() + self._pending_lock_bindings: set[str] = set() + self._probe_engine = None self._lock = threading.RLock() self._condition = threading.Condition(self._lock) self._global_stop_lock = threading.Lock() @@ -162,8 +175,7 @@ def _start_binding_core(self, binding_id: str, config_revision: int) -> Connecto def _spawn_reserved_binding( self, binding_id: str, config_revision: int ) -> ConnectorRecord: - lock_path = binding_lock_path(binding_id, self._database_path) - if not self._wait_for_binding_lock(lock_path, self._lock_wait_seconds): + if not self._wait_for_binding_lock(binding_id, self._lock_wait_seconds): raise RuntimeError(f"Feishu connector binding lock is still held: {binding_id}") nonce = secrets.token_hex(16) parent_connection, child_connection = self._ctx.Pipe(duplex=True) @@ -172,8 +184,7 @@ def _spawn_reserved_binding( config_revision=config_revision, child_nonce=nonce, runtime_path=self._runtime_path, - binding_lock_path=str(lock_path), - database_path=str(self._database_path), + database_url=self._database_url, watchdog_seconds=self._watchdog_seconds, assembly_fingerprint=self._assembly_fingerprint, ) @@ -402,7 +413,7 @@ def stop_binding(self, binding_id: str, timeout: float = 5.0) -> bool: self._records.pop(binding_id, None) self._dispose_record(record) self._condition.notify_all() - return stopped and self._binding_lock_is_free(Path(record.spec.binding_lock_path)) + return stopped and self._binding_lock_is_free(record.spec.binding_id) def replace_binding( self, @@ -423,7 +434,7 @@ def replace_binding( current.state = ConnectorState.STOPPING if not self._stop_records([current], deadline): raise TimeoutError("old Feishu connector did not stop before reconfiguration") - if not self._binding_lock_is_free(Path(current.spec.binding_lock_path)): + if not self._binding_lock_is_free(current.spec.binding_id): raise TimeoutError("old Feishu connector binding lock is still held") with self._condition: self._drain_events(current) @@ -481,15 +492,17 @@ def stop(self, timeout: float = 5.0) -> bool: self._dispose_record(record) self._records.clear() self._condition.notify_all() - lock_paths = self._pending_lock_paths | { - Path(record.spec.binding_lock_path) for record in records + lock_bindings = self._pending_lock_bindings | { + record.spec.binding_id for record in records } - blocked_paths = { - path for path in lock_paths if not self._binding_lock_is_free(path) + blocked_bindings = { + binding_id + for binding_id in lock_bindings + if not self._binding_lock_is_free(binding_id) } - locks_free = not blocked_paths + locks_free = not blocked_bindings with self._condition: - self._pending_lock_paths = blocked_paths + self._pending_lock_bindings = blocked_bindings self._closed = stopped and monitor_stopped and locks_free self._condition.notify_all() return stopped and monitor_stopped and locks_free @@ -520,22 +533,35 @@ def _dispose_record(record: ConnectorRecord) -> None: except ValueError: pass - @staticmethod - def _binding_lock_is_free(path: Path) -> bool: - lock = BindingProcessLock(path) + def _lock_probe_engine(self): + # 探测用缓存 engine:NullPool,每次探测开短会话,不常驻连接 + if self._probe_engine is None: + self._probe_engine = create_engine(self._database_url, poolclass=NullPool) + return self._probe_engine + + def _binding_lock_is_free(self, binding_id: str) -> bool: + """方言探测 binding 锁:短会话 try-acquire + release。 + + 探测本身失败(数据库不可达等)按"仍占用"保守处理:宁误拒启动, + 不冒双起 connector 的风险。 + """ + key = binding_lock_key(binding_id) try: - acquired = lock.acquire() - except OSError: - return False - if not acquired: + engine = self._lock_probe_engine() + dialect = get_dialect(engine.url.get_backend_name()) + with Session(engine) as session: + if not dialect.acquire_advisory_lock(session, key): + return False + dialect.release_advisory_lock(session, key) + return True + except Exception: + logger.warning("飞书 binding 锁探测失败 binding=%s", binding_id, exc_info=True) return False - lock.release() - return True - def _wait_for_binding_lock(self, path: Path, timeout: float) -> bool: + def _wait_for_binding_lock(self, binding_id: str, timeout: float) -> bool: deadline = time.monotonic() + max(0.0, timeout) while True: - if self._binding_lock_is_free(path): + if self._binding_lock_is_free(binding_id): return True if time.monotonic() >= deadline: return False diff --git a/backend/app/channels/feishu_runtime.py b/backend/app/channels/feishu_runtime.py index 85772d1ea..48f7ca7a5 100644 --- a/backend/app/channels/feishu_runtime.py +++ b/backend/app/channels/feishu_runtime.py @@ -5,10 +5,9 @@ import json import logging import hashlib -from pathlib import Path from sqlalchemy.pool import NullPool -from sqlmodel import Session, create_engine +from sqlmodel import create_engine from app.channels.adapters.base import ChannelInbound, ChannelInboundAttachment from app.channels.crypto import decrypt_channel_secret @@ -327,15 +326,17 @@ def ignore_lifecycle_event(_event) -> None: def run_feishu_runtime(spec, control, watchdog) -> None: if importlib.metadata.version("lark-channel-sdk") != SDK_CONTRACT_VERSION: raise RuntimeError(f"lark-channel-sdk must be exactly {SDK_CONTRACT_VERSION}") - database_path = Path(spec.database_path).expanduser().resolve() - stage_engine = create_engine( - f"sqlite:///{database_path}", - connect_args={"check_same_thread": False, "timeout": 0.5}, - poolclass=NullPool, + # 子进程按完整 SQLAlchemy URL 自建引擎;非 SQLite 不传 check_same_thread + database_url = spec.database_url + connect_args = ( + {"check_same_thread": False, "timeout": 0.5} + if database_url.startswith("sqlite") + else {} ) + stage_engine = create_engine(database_url, connect_args=connect_args, poolclass=NullPool) from app.channels.storage import channel_session, install_connector_assembly registry = install_connector_assembly(spec.assembly_fingerprint) if spec.assembly_fingerprint else None - # The file path is also the connector lock domain; it is NOT the selected runtime DB. + # 锁域即所选数据库作用域(方言 advisory lock);stage_engine 仅为未装配 registry 时的兜底库。 selected_engine = None if registry is not None else stage_engine with channel_session(selected_engine) as db: binding = db.get(ChannelBinding, spec.binding_id) diff --git a/backend/app/config.py b/backend/app/config.py index cec011953..d0deeb2b3 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -18,6 +18,9 @@ class Settings(BaseSettings): startup_orphan_cleanup_enabled: bool = True app_name: str = "Skill Agent Loop Service" database_url: str = "sqlite:///./skill_agent_loop.db" + # 应用时区(如 Asia/Shanghai):仅 PostgreSQL 日分桶换算使用;留空=服务器本地固定偏移。 + # SQLite 恒为服务器本地时区,配置了也不生效(启动时会告警)。 + app_timezone: str = "" app_secret: str = "change-me-in-development" demo_model_base_url: str = "http://localhost:52010/v1" demo_model_name: str = "qwen3.6-27b" diff --git a/backend/app/db/database.py b/backend/app/db/database.py index 1630de48f..345bf3588 100644 --- a/backend/app/db/database.py +++ b/backend/app/db/database.py @@ -1,16 +1,21 @@ import hashlib import json +import logging from collections.abc import Callable, Generator from contextlib import contextmanager from pathlib import Path -from sqlalchemy import Engine, inspect, text +from sqlalchemy import Engine, func, inspect, text +from sqlalchemy.engine import make_url from sqlmodel import Session, SQLModel, create_engine, select from app.config import get_settings from app.db.database_path import normalize_database_url +from app.db.dialect import ensure_driver_available, get_dialect from app.db.models import new_id, utc_now +logger = logging.getLogger(__name__) + def _normalize_database_url(url: str) -> str: """Backward-compatible import seam for callers and migration tests.""" @@ -20,8 +25,15 @@ def _normalize_database_url(url: str) -> str: settings = get_settings() database_url = _normalize_database_url(settings.database_url) -connect_args = {"check_same_thread": False, "timeout": 30} if database_url.startswith("sqlite") else {} -engine: Engine = create_engine(database_url, echo=False, connect_args=connect_args) +_parsed_url = make_url(database_url) +# 可选驱动缺失时先给出安装指引(create_engine 会在 import DBAPI 时报更晦涩的错误) +ensure_driver_available(_parsed_url) +# 引擎创建参数由方言提供者收口(SQLite=check_same_thread/timeout,行为不变) +_dialect = get_dialect(_parsed_url.get_backend_name()) +engine: Engine = create_engine(database_url, echo=False, **_dialect.engine_kwargs(database_url)) + +# Alembic 迁移目录(app 包内,按本文件位置解析为绝对路径,不依赖执行时 CWD) +_ALEMBIC_DIR = Path(__file__).resolve().parent / "migrations" _DEFAULT_MODEL_OUTPUT_LIMIT_MIGRATION_ID = "20260712_default_model_output_tokens_8192" _LEGACY_DEFAULT_MODEL_OUTPUT_TOKENS = 2048 @@ -62,13 +74,121 @@ def _normalize_database_url(url: str) -> str: def init_db() -> None: import app.db.models # noqa: F401 + _ensure_driver_available() _configure_sqlite_runtime() - SQLModel.metadata.create_all(engine) - _migrate_sqlite_skill_schema() + if engine.url.get_backend_name() == "sqlite": + # SQLite 行为保持不变:create_all + 启动期存量 schema 迁移 + SQLModel.metadata.create_all(engine) + _migrate_sqlite_skill_schema() + else: + # 非 SQLite 后端:全新库 create_all + 基线标记,存量库统一走 Alembic + _prepare_non_sqlite_schema(engine) + _validate_default_model_invariant() + _warn_backend_constraints() if settings.startup_orphan_cleanup_enabled: _purge_orphaned_chat_sessions() +def _ensure_driver_available() -> None: + """可选数据库驱动(PG/MySQL/达梦)缺失时在启动处给出明确安装指引。""" + ensure_driver_available(engine.url) + + +def _alembic_config(database_url: str): + """构造指向本仓库 backend/alembic 的 Alembic Config(惰性 import)。 + + URL 通过 main option 传给 env.py(优先于应用配置);ConfigParser 会把 ``%`` + 当插值符号,URL 中的百分号(如密码里的 %xx)需先转义,读取时会还原。 + """ + from alembic.config import Config + + config = Config() + config.set_main_option("script_location", str(_ALEMBIC_DIR)) + config.set_main_option("sqlalchemy.url", database_url.replace("%", "%%")) + return config + + +def _prepare_non_sqlite_schema(engine: Engine) -> None: + """非 SQLite 后端:用 Alembic 建立/升级 schema(替代"仅全新库初始化")。 + + 三种存量情形: + 1. 全新空库(无应用表、无 alembic_version):create_all 建当前 schema + (含 models.py 的按方言 DDL 事件,如部分唯一索引),再 stamp 基线 head; + 2. 已有应用表但无 alembic_version:视为基线等价的老库,stamp head 并告警, + 避免重复建表;此后升级走 alembic revision; + 3. 已有 alembic_version:upgrade head 应用未执行的迁移。 + """ + try: + from alembic import command + except ImportError as exc: # pragma: no cover - 依赖缺失时的明确指引 + raise RuntimeError( + "非 SQLite 数据库后端需要 Alembic 迁移组件:pip install alembic" + ) from exc + + backend = engine.url.get_backend_name() + tables = set(inspect(engine).get_table_names()) + config = _alembic_config(engine.url.render_as_string(hide_password=False)) + + if "alembic_version" in tables: + command.upgrade(config, "head") + logger.info("数据库后端 %s 已用 Alembic 升级到 head", backend) + return + + if tables: + logger.warning( + "数据库后端 %s 已有应用表但缺少 alembic_version:按基线标记为 head;" + "请确认既有 schema 与当前版本一致,后续升级走 alembic upgrade", + backend, + ) + command.stamp(config, "head") + return + + SQLModel.metadata.create_all(engine) + command.stamp(config, "head") + logger.info("数据库后端 %s 为全新空库:create_all 建表后按基线标记 head", backend) + + +def _validate_default_model_invariant() -> None: + """不支持部分唯一索引的后端:启动校验"每租户至多一条默认模型"未被破坏。 + + 该类后端不会创建 uq_model_configs_tenant_default(见 models.py 的按方言 DDL), + 约束退化为代码层维护(默认切换在同事务先清后设)+ 此处启动兜底。 + """ + if _dialect.supports_partial_index: + return + from app.db.models import ModelConfig + + with Session(engine) as db: + duplicates = db.exec( + select(ModelConfig.tenant_id) + .where(ModelConfig.is_default == True) # noqa: E712 + .group_by(ModelConfig.tenant_id) + .having(func.count() > 1) + ).all() + if duplicates: + raise RuntimeError( + "当前数据库后端不支持部分唯一索引,且检测到以下租户存在多条默认模型: " + f"{sorted(duplicates)};请人工清理至每租户至多一条后再启动" + ) + + +def _warn_backend_constraints() -> None: + """非 SQLite 后端的显式约束与配置陷阱告警(启动期一次性)。""" + backend = engine.url.get_backend_name() + if backend == "sqlite": + if (get_settings().app_timezone or "").strip(): + logger.warning( + "app_timezone 对 SQLite 不生效(日分桶恒为服务器本地时区),该配置将被忽略" + ) + return + logger.warning( + "数据库后端 %s 使用 Alembic 管理 schema:启动时自动 upgrade 到 head" + "(全新空库为 create_all + 基线标记;既有库无版本表时按基线标记);" + "后续 models 变更需配套 alembic revision,不要依赖 create_all 补列", + backend, + ) + + def _purge_orphaned_chat_sessions() -> None: """清理孤儿会话:团队/员工已被删除但会话残留(级联清理上线前的历史数据)。""" from app.db.models import AgentProfile, ChatSession, Team diff --git a/backend/app/db/dialect.py b/backend/app/db/dialect.py new file mode 100644 index 000000000..bd97df5e1 --- /dev/null +++ b/backend/app/db/dialect.py @@ -0,0 +1,534 @@ +"""数据库方言可插拔层. + +ORM 优先:能用 SQLAlchemy ORM/标准 SQL 表达的一律走通用实现,无法通用的 +少数方言点收口到本模块的 DatabaseDialect 提供者。新增数据库 = 新增一个小 +适配器并 register_dialect 注册,业务代码零改动: + +- postgresql:全能力,即 PostgresDialect(psycopg3 驱动,URL + postgresql+psycopg://)。 +- opengauss(高斯):复用 PostgresDialect 全能力;SQLAlchemy 侧由 + app/db/opengauss.py 注册自定义方言 opengauss+psycopg://,处理服务端版本串 + ("(openGauss 5.0.0 ...)")解析与 client_encoding=utf8(openGauss 默认 + SQL_ASCII 初始化库)。 +- mysql(含 MariaDB):pymysql 驱动(mysql+pymysql://),不预装(按需装); + 不支持部分唯一索引——models.py 的 uq_model_configs_tenant_default 只在 + sqlite/postgresql 方言创建,其它后端由 init_db 的启动校验兜底;advisory + lock 用 MySQL 命名锁(GET_LOCK/RELEASE_LOCK/IS_USED_LOCK,专属连接常驻)。 +- dm(达梦):需外部 SQLAlchemy 达梦方言插件 + dmPython 驱动 + (dm+dmPython://),本仓库未预装、未真机验证;Oracle 系语法,同样不支持 + 部分唯一索引;无已验证原生锁 → 文件锁对非 SQLite 文件库响亮拒绝。 + +未注册的后端名回退 GenericDialect:ORM 通用实现开箱可用;适配器只补充各自 +特性(原生 advisory lock、部分索引、日期函数等)。可选驱动(PG/MySQL/达梦) +缺失时由 ensure_driver_available() 在启动处给出带安装指引的 RuntimeError +(见 _OPTIONAL_DRIVERS)。 + +日分桶口径注意:SQLite 为服务器本地自然日(func.date(col,'localtime')); +Postgres 按 app_timezone(缺省=服务器本地固定偏移);Generic 为 +cast(col, Date) 即数据库服务器时区自然日(云上实例常为 UTC),与 SQLite +口径可能不同——跨库迁移数据后按日统计会整体平移,属预期差异。 +""" + +from __future__ import annotations + +import logging +import os +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, Protocol, runtime_checkable + +from sqlalchemy import Date, cast, func, literal, text +from sqlalchemy.types import Interval + +from app.config import get_settings + +logger = logging.getLogger(__name__) + + +@runtime_checkable +class DatabaseDialect(Protocol): + """数据库方言提供者:引擎参数、日分桶、JSON 配置读改写、advisory lock。""" + + name: str # sqlite / postgresql / mysql / dm / ... + supports_partial_index: bool # 部分唯一索引(WHERE 子句)能力 + session_scoped_advisory_lock: bool # advisory lock 是否随连接存活(方言须常驻专属连接) + + def engine_kwargs(self, url: str) -> dict[str, Any]: ... + + def day_bucket(self, column) -> Any: ... + + def json_config_get(self, config: dict | None, key: str) -> Any: ... + + def json_config_set(self, config: dict | None, key: str, value: Any) -> dict: ... + + def json_config_remove(self, config: dict | None, key: str) -> dict: ... + + def acquire_advisory_lock(self, session, key: str) -> bool: ... + + def release_advisory_lock(self, session, key: str) -> None: ... + + def check_advisory_lock(self, session, key: str) -> bool: ... + + +class BaseDialect: + """通用默认实现:JSON 读改写 = Python 侧读-改-写;日分桶 = cast(col, Date) + (标准 SQL,按数据库服务器时区取日);advisory lock = SQLite 数据库文件旁的 + 文件锁(非 SQLite 文件库响亮拒绝,由具体适配器补原生锁实现)。""" + + name = "generic" + supports_partial_index = False + session_scoped_advisory_lock = False + + def __init__(self, backend_name: str = "generic") -> None: + self.name = backend_name + self._lock_handles: dict[str, tuple[int, Any]] = {} + + def engine_kwargs(self, url: str) -> dict[str, Any]: + return {} + + def day_bucket(self, column) -> Any: + return cast(column, Date) + + def json_config_get(self, config: dict | None, key: str) -> Any: + return dict(config or {}).get(key) + + def json_config_set(self, config: dict | None, key: str, value: Any) -> dict: + patched = dict(config or {}) + patched[key] = value + return patched + + def json_config_remove(self, config: dict | None, key: str) -> dict: + patched = dict(config or {}) + patched.pop(key, None) + return patched + + def acquire_advisory_lock(self, session, key: str) -> bool: + """SQLite 数据库文件旁的文件锁;已持有同 key 锁时重入成功。 + + 只对 SQLite 文件库有效:url.database 对 MySQL/达梦等是库名而非文件路径, + 直接拒绝(响亮失败),避免把库名当路径在 CWD 下生成各进程互不可见的锁文件, + 静默破坏单实例保证。 + + fork 防护:继承自父进程的句柄不算持有(只关闭不解锁——解锁会把父进程 + 的锁一起放掉),随后按本进程身份真实抢锁。 + """ + held = self._lock_handles.get(key) + if held is not None: + held_pid, held_handle = held + if held_pid == os.getpid(): + return True + held_handle.close() + self._lock_handles.pop(key, None) + bind = session.get_bind() + url = getattr(bind, "url", None) + backend_name = url.get_backend_name() if url is not None else "" + database_path = getattr(url, "database", None) + if backend_name != "sqlite" or not database_path or database_path == ":memory:": + logger.error( + "方言 %s 无原生 advisory lock 且数据库非 SQLite 文件库,无法提供进程锁;" + "请为该后端实现原生 advisory lock 适配器", + self.name, + ) + return False + lock_path = ( + Path(database_path).resolve().with_name(f"{Path(database_path).name}.{key}.lock") + ) + handle = lock_path.open("a+b") + try: + if os.name == "nt": + import msvcrt + + handle.seek(0) + if handle.read(1) == b"": + handle.write(b"0") + handle.flush() + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except (BlockingIOError, OSError): + handle.close() + return False + self._lock_handles[key] = (os.getpid(), handle) + return True + + def release_advisory_lock(self, session, key: str) -> None: + held = self._lock_handles.pop(key, None) + if held is None: + return + held_pid, handle = held + if held_pid != os.getpid(): + # fork 子进程:仅关闭继承句柄,不解父进程的锁 + handle.close() + return + try: + if os.name == "nt": + import msvcrt + + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + finally: + handle.close() + + def check_advisory_lock(self, session, key: str) -> bool: + """文件锁无静默失效模式(句柄随进程存活):只校验本进程仍持有句柄。""" + held = self._lock_handles.get(key) + return held is not None and held[0] == os.getpid() and not held[1].closed + + +class SQLiteDialect(BaseDialect): + """SQLite:文件锁 + date(localtime) 日分桶(均为现行行为,保持不变)。""" + + supports_partial_index = True + + def __init__(self) -> None: + super().__init__("sqlite") + + def engine_kwargs(self, url: str) -> dict[str, Any]: + return {"connect_args": {"check_same_thread": False, "timeout": 30}} + + def day_bucket(self, column) -> Any: + # 服务器本地时区自然日(既有行为) + return func.date(column, "localtime") + + +class PostgresDialect(BaseDialect): + """PostgreSQL/高斯:psycopg3 驱动(postgresql+psycopg://),全能力。 + + advisory lock 属于**连接**而非会话:持锁期间由本方言常驻一条专属 + `engine.connect()` Connection(AUTOCOMMIT——每条语句即提即放,不留 + idle-in-transaction;Connection 不归池,commit/rollback 不脱钩, + `pg_backend_pid()` 全程稳定)。绝不能用 Session.commit() 代替: + commit 会把连接归还池中,锁静默释放或后续 check 取到别的连接。""" + + supports_partial_index = True + session_scoped_advisory_lock = True + + def __init__(self) -> None: + super().__init__("postgresql") + # key -> (pid, Connection);fork 防护同 BaseDialect 文件锁 + self._pg_lock_conns: dict[str, tuple[int, Any]] = {} + + def engine_kwargs(self, url: str) -> dict[str, Any]: + return { + # 陈旧连接(PG 重启/idle 超时后)首用前先 ping,失效即重连而非报错 + "pool_pre_ping": True, + # 主动回收长闲连接,避开服务端/LB 的 idle 掐断 + "pool_recycle": 1800, + # 后台线程随 binding 数增长,默认 5+10 不够 + "pool_size": 10, + "max_overflow": 20, + } + + def day_bucket(self, column) -> Any: + tz = (get_settings().app_timezone or "").strip() + if tz: + # created_at 为 naive UTC:先按 UTC 还原时刻,再换算到应用时区取自然日 + return cast(func.timezone(tz, func.timezone("UTC", column)), Date) + # 未配置时区:按服务器本地固定偏移换算(与 SQLite localtime 语义对齐) + offset = datetime.now().astimezone().utcoffset() or timedelta(0) + interval = literal(offset, type_=Interval) + return cast(column + interval, Date) + + def _engine_of(self, session): + bind = session.get_bind() + return getattr(bind, "engine", bind) + + def acquire_advisory_lock(self, session, key: str) -> bool: + """以专属 AUTOCOMMIT Connection 取锁并常驻;重入成功,fork 继承不作数。""" + held = self._pg_lock_conns.get(key) + if held is not None: + held_pid, held_conn = held + if held_pid == os.getpid(): + return True + # fork 子进程:继承的连接只丢弃引用,不在共享 socket 上做任何操作 + self._pg_lock_conns.pop(key, None) + # 双 int4 键形式(classid=hashtext(key), objid=0):便于在 pg_locks 中直接校验 + conn = self._engine_of(session).connect().execution_options( + isolation_level="AUTOCOMMIT" + ) + try: + locked = conn.execute( + text("SELECT pg_try_advisory_lock(hashtext(:key), 0)"), + {"key": key}, + ).scalar() + except Exception: + conn.close() + raise + if not locked: + conn.close() + return False + self._pg_lock_conns[key] = (os.getpid(), conn) + return True + + def release_advisory_lock(self, session, key: str) -> None: + held = self._pg_lock_conns.pop(key, None) + if held is None: + return + held_pid, conn = held + if held_pid != os.getpid(): + # fork 子进程:仅丢弃引用,不解父进程的锁 + return + try: + conn.execute(text("SELECT pg_advisory_unlock(hashtext(:key), 0)"), {"key": key}) + finally: + conn.close() + + def check_advisory_lock(self, session, key: str) -> bool: + """校验本进程常驻的那条连接仍持有该 advisory lock。 + + 必须在**同一条专属 Connection** 上查 pg_locks(pid 稳定);连接被服务端 + 掐断后锁已静默释放,查询会抛错——同样判 False。 + """ + held = self._pg_lock_conns.get(key) + if held is None: + return False + held_pid, conn = held + if held_pid != os.getpid(): + return False + try: + row = conn.execute( + text( + "SELECT 1 FROM pg_locks " + "WHERE locktype = 'advisory' AND pid = pg_backend_pid() " + "AND classid = hashtext(:key) AND objid = 0" + ), + {"key": key}, + ).first() + return row is not None + except Exception: + logger.exception("PG advisory lock 存活校验失败 key=%s", key) + return False + + +class MySQLDialect(BaseDialect): + """MySQL/MariaDB:pymysql 驱动(mysql+pymysql://),不支持部分唯一索引。 + + advisory lock 用 MySQL 命名锁:命名锁属于**连接**,持锁期间由本方言常驻一条 + 专属 `engine.connect()` Connection(AUTOCOMMIT——GET_LOCK 本身非事务性,但常驻 + 连接不该挂着一条隐式事务;Connection 不归池,commit/rollback 不脱钩, + `CONNECTION_ID()` 全程稳定)。绝不能用 Session.commit() 代替:commit 会把连接 + 归还池中,锁静默释放或后续 check 取到别的连接。 + """ + + # MySQL 无部分唯一索引(WHERE 子句)能力:models.py 的默认模型部分索引不创建, + # 由 init_db 的启动校验兜底 + supports_partial_index = False + session_scoped_advisory_lock = True + # MySQL 命名锁名上限(SQL 标准规定为 64 个字符,超长服务端会报错) + MAX_LOCK_NAME_LENGTH = 64 + + def __init__(self) -> None: + super().__init__("mysql") + # key -> (pid, Connection);fork 防护同 BaseDialect 文件锁 + self._mysql_lock_conns: dict[str, tuple[int, Any]] = {} + + def engine_kwargs(self, url: str) -> dict[str, Any]: + return { + # 陈旧连接(MySQL 重启/wait_timeout 掐断后)首用前先 ping,失效即重连 + "pool_pre_ping": True, + # 主动回收长闲连接,避开服务端 wait_timeout(默认 8h)掐断 + "pool_recycle": 1800, + # 后台线程随 binding 数增长,默认 5+10 不够 + "pool_size": 10, + "max_overflow": 20, + # 建连接即固定 utf8mb4,避免库/表默认字符集不一致导致的乱码 + "connect_args": {"charset": "utf8mb4"}, + } + + def day_bucket(self, column) -> Any: + # 数据库服务器时区自然日;SQLite 为服务器本地自然日(date(col,'localtime')), + # 云上 MySQL 实例常为 UTC——跨库迁移后按日统计会整体平移,属预期差异 + return cast(column, Date) + + def _engine_of(self, session): + bind = session.get_bind() + return getattr(bind, "engine", bind) + + def _validate_lock_name(self, key: str) -> None: + if len(key) > self.MAX_LOCK_NAME_LENGTH: + raise ValueError( + f"MySQL 命名锁名最长 {self.MAX_LOCK_NAME_LENGTH} 个字符," + f"当前 {len(key)} 个:{key!r};请缩短 advisory lock key" + ) + + def acquire_advisory_lock(self, session, key: str) -> bool: + """以专属 Connection 执行 GET_LOCK(key, 0);重入成功,fork 继承不作数。 + + GET_LOCK 返回 1=成功,0=超时(已被占用),NULL=错误:只有 1 才算持锁。 + """ + self._validate_lock_name(key) + held = self._mysql_lock_conns.get(key) + if held is not None: + held_pid, held_conn = held + if held_pid == os.getpid(): + return True + # fork 子进程:继承的连接只丢弃引用,不在共享 socket 上做任何操作 + # (关闭会向父进程的连接发退出包,可能把父进程的锁一起放掉) + self._mysql_lock_conns.pop(key, None) + conn = self._engine_of(session).connect().execution_options( + isolation_level="AUTOCOMMIT" + ) + try: + locked = conn.execute(text("SELECT GET_LOCK(:key, 0)"), {"key": key}).scalar() + except Exception: + conn.close() + raise + if locked != 1: + conn.close() + return False + self._mysql_lock_conns[key] = (os.getpid(), conn) + return True + + def release_advisory_lock(self, session, key: str) -> None: + held = self._mysql_lock_conns.pop(key, None) + if held is None: + return + held_pid, conn = held + if held_pid != os.getpid(): + # fork 子进程:仅丢弃引用,不解父进程的锁 + return + try: + conn.execute(text("SELECT RELEASE_LOCK(:key)"), {"key": key}) + finally: + conn.close() + + def check_advisory_lock(self, session, key: str) -> bool: + """校验本进程常驻的那条连接仍持有该命名锁。 + + IS_USED_LOCK(key) 返回持锁连接的 CONNECTION_ID()(无人持有时为 NULL), + 在**同一条专属 Connection** 上取 CONNECTION_ID() 比对即可;连接被服务端 + 掐断后锁已静默释放,查询会抛错——同样判 False。 + """ + held = self._mysql_lock_conns.get(key) + if held is None: + return False + held_pid, conn = held + if held_pid != os.getpid(): + return False + try: + same_connection = conn.execute( + text("SELECT IS_USED_LOCK(:key) = CONNECTION_ID()"), + {"key": key}, + ).scalar() + return bool(same_connection) + except Exception: + logger.exception("MySQL advisory lock 存活校验失败 key=%s", key) + return False + + +class DMDialect(BaseDialect): + """达梦(DM8):需外部 SQLAlchemy 达梦方言插件 + dmPython 驱动,未真机验证。 + + 本仓库不预装达梦方言插件/驱动,也不做真机验证;注册该适配器是把「可插拔」 + 落到代码能力位,部署方需自行安装兼容版本插件(dm+dmPython:// URL): + + - 不支持部分唯一索引(无 WHERE 子句):models.py 的部分唯一索引不创建, + 由 init_db 的启动校验兜底"每租户至多一条默认模型"; + - 连接池/驱动参数由部署方方言插件与驱动决定,engine_kwargs 返回 {} 不内置 + 未经验证的项目参数; + - 无已验证原生 advisory lock:session_scoped_advisory_lock=False,复用 + BaseDialect 文件锁——对非 SQLite 文件库响亮拒绝(不会把库名当路径在 CWD + 生成各进程互不可见的锁文件),保留单实例安全语义;该后端需部署方保证单实例 + 或后续补原生锁实现; + - 日分桶 cast(col, Date):按数据库服务器时区取自然日(Oracle 系语法支持)。 + """ + + supports_partial_index = False + session_scoped_advisory_lock = False + + def __init__(self) -> None: + super().__init__("dm") + + def engine_kwargs(self, url: str) -> dict[str, Any]: + # 达梦驱动/方言插件为外部安装物,连接池与字符集参数由部署方负责 + return {} + + def day_bucket(self, column) -> Any: + return cast(column, Date) + + +class OpenGaussDialect(PostgresDialect): + """openGauss(高斯):复用 PostgreSQL 方言全能力,补两处协议兼容。 + + SQLAlchemy 侧用 ``opengauss+psycopg://`` 自定义方言(app/db/opengauss.py): + - 服务端 version 串为 ``(openGauss 5.0.0 build ) ...``,无法按 PG 正则解析; + 自定义方言回退到 openGauss 5.x 对应的 PostgreSQL 9.2 兼容级别; + - openGauss 初始化库默认 SQL_ASCII,client_encoding 未显式指定时驱动可能返回 + bytes;这里统一注入 ``client_encoding=utf8``(纯 ASCII 数据同样安全)。 + """ + + def __init__(self) -> None: + super().__init__() + self.name = "opengauss" + + def engine_kwargs(self, url: str) -> dict[str, Any]: + kwargs = dict(super().engine_kwargs(url)) + kwargs["connect_args"] = {"client_encoding": "utf8"} + return kwargs + + +class GenericDialect(BaseDialect): + """未注册后端的回退:ORM 通用实现;文件锁仅对 SQLite 文件库有效。 + + 扩展新数据库(MySQL/达梦等):继承 BaseDialect 按能力覆写后 + register_dialect("") 注册即可。supports_partial_index=False 的 + 后端不会创建 models.py 的部分唯一索引,由 init_db 启动校验兜底; + 未实现原生 advisory lock 时 BaseDialect 会响亮拒绝而非静默错锁。 + """ + + +# 可选驱动注册表:backend -> (import 名, 安装指引)。缺失时在启动处给出明确 +# 指引而不是连接期栈 trace(桌面端默认 SQLite,不背 PG/MySQL/达梦 驱动)。 +_OPTIONAL_DRIVERS: dict[str, tuple[str, str]] = { + "postgresql": ("psycopg", 'pip install "skill-agent-loop-backend[postgres]"'), + "mysql": ("pymysql", 'pip install "skill-agent-loop-backend[mysql]"'), + "opengauss": ("psycopg", 'pip install "skill-agent-loop-backend[postgres]"'), + "dm": ("dmPython", 'pip install "skill-agent-loop-backend[dm]"'), +} + + +def ensure_driver_available(url: Any) -> None: + """检查可选数据库驱动;缺失时抛出带安装指引的 RuntimeError。""" + backend = url.get_backend_name() if hasattr(url, "get_backend_name") else str(url) + spec = _OPTIONAL_DRIVERS.get(backend) + if spec is None: + return + module_name, hint = spec + try: + __import__(module_name) + except ImportError as exc: + raise RuntimeError(f"数据库后端 {backend} 需要可选驱动:{hint}") from exc + + +_DIALECTS: dict[str, DatabaseDialect] = {} + + +def register_dialect(backend_name: str, dialect: DatabaseDialect) -> None: + """注册方言提供者(backend_name 即 engine.url.get_backend_name())。""" + _DIALECTS[backend_name] = dialect + + +def get_dialect(backend_name: str) -> DatabaseDialect: + """按 SQLAlchemy backend 名取方言提供者;未注册回退 GenericDialect。""" + dialect = _DIALECTS.get(backend_name) + if dialect is None: + dialect = _DIALECTS.setdefault(backend_name, GenericDialect(backend_name)) + return dialect + + +register_dialect("sqlite", SQLiteDialect()) +register_dialect("postgresql", PostgresDialect()) +register_dialect("opengauss", OpenGaussDialect()) +register_dialect("mysql", MySQLDialect()) +register_dialect("dm", DMDialect()) + +# 注册 SQLAlchemy 侧 ``opengauss+psycopg://`` 方言(版本串/编码兼容)。 +# psycopg 未安装时该模块内不注册 SQLAlchemy 方言,SQLite 默认安装无额外依赖。 +from app.db import opengauss as _opengauss # noqa: E402,F401 diff --git a/backend/app/db/migrations/env.py b/backend/app/db/migrations/env.py new file mode 100644 index 000000000..7cbef47e0 --- /dev/null +++ b/backend/app/db/migrations/env.py @@ -0,0 +1,100 @@ +"""Alembic 迁移环境:复用应用的方言适配层与配置,SQLite/非 SQLite 一致。 + +URL 解析优先级: +1. ``sqlalchemy.url``(程序化调用由 ``init_db`` 通过 + ``Config.set_main_option`` 注入;CLI 可配合 ``DATABASE_URL`` 环境变量回退); +2. 应用配置 ``app.config.get_settings().database_url``(经 + ``normalize_database_url`` 归一化,与运行时完全一致)。 + +引擎参数统一取自 ``app.db.dialect.get_dialect(...).engine_kwargs``, +避免迁移连接与应用运行时连接行为不一致(如连接池预检、SQLite connect_args)。 +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from alembic import context +from sqlalchemy import create_engine +from sqlalchemy.engine import Engine, make_url +from sqlmodel import SQLModel + +# alembic CLI 可能从任意目录执行:显式把 backend/ 加入 sys.path,保证 app 包可导入。 +# 迁移目录放在 app 包内(app/db/migrations),wheel/PyInstaller 打包时随 package-data 一起分发。 +# (script_location 本身由 alembic.ini 的 %(here)s 解析为绝对路径。) +# 迁移脚本位于 app/db/migrations/:向上三级即 backend/(app 包所在根目录) +BACKEND_DIR = Path(__file__).resolve().parents[3] +if str(BACKEND_DIR) not in sys.path: + sys.path.insert(0, str(BACKEND_DIR)) + +import app.db.models # noqa: E402,F401 # 注册全部 SQLModel 表/索引/方言 DDL 事件 +from app.config import get_settings # noqa: E402 +from app.db.database_path import normalize_database_url # noqa: E402 +from app.db.dialect import ensure_driver_available, get_dialect # noqa: E402 + +# Alembic 会把 env.py 作为脚本执行并注入全局 context。 +config = context.config + +target_metadata = SQLModel.metadata + + +def _resolve_database_url() -> str: + """优先显式配置的 alembic URL,否则回退应用 database_url。""" + url = (config.get_main_option("sqlalchemy.url") or "").strip() + if url: + return url + return normalize_database_url(get_settings().database_url) + + +def _build_engine(url: str) -> Engine: + parsed = make_url(url) + ensure_driver_available(parsed) + dialect = get_dialect(parsed.get_backend_name()) + return create_engine(url, **dialect.engine_kwargs(url)) + + +def _include_object(object_, name, type_, reflected, compare_to) -> bool: + """autogenerate 比对过滤:models.py 用 after_create DDL 创建的部分唯一索引 + (uq_model_configs_tenant_default)不在 metadata 中,数据库里多出的它不应被 + 误判为 remove_index;该索引由基线 migration 显式创建。""" + if type_ == "index" and name == "uq_model_configs_tenant_default": + return False + return True + + +def run_migrations_offline() -> None: + """离线模式(--sql):只渲染 SQL,不实际连接数据库。""" + context.configure( + url=_resolve_database_url(), + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + compare_type=True, + include_object=_include_object, + ) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """在线模式:按应用同款引擎参数连接后执行迁移。""" + connectable = _build_engine(_resolve_database_url()) + try: + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + compare_type=True, + include_object=_include_object, + ) + with context.begin_transaction(): + context.run_migrations() + finally: + connectable.dispose() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/backend/app/db/migrations/script.py.mako b/backend/app/db/migrations/script.py.mako new file mode 100644 index 000000000..2dee041a4 --- /dev/null +++ b/backend/app/db/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from collections.abc import Sequence + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: str | Sequence[str] | None = ${repr(down_revision)} +branch_labels: str | Sequence[str] | None = ${repr(branch_labels)} +depends_on: str | Sequence[str] | None = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/backend/app/db/migrations/versions/20261106_0001_baseline_schema.py b/backend/app/db/migrations/versions/20261106_0001_baseline_schema.py new file mode 100644 index 000000000..f270cbb78 --- /dev/null +++ b/backend/app/db/migrations/versions/20261106_0001_baseline_schema.py @@ -0,0 +1,2266 @@ +"""baseline schema + +基线版本:与当前 SQLModel.metadata 等价的全量 schema(75 张表 + 索引/唯一约束)。 +非 SQLite 后端首次接入 Alembic 时按此版本 stamp/upgrade;SQLite 运行时仍走 +create_all + 启动期存量迁移,不经过 Alembic。 + +autogenerate 额外手工补齐:models.py 里 uq_model_configs_tenant_default +("每租户至多一条默认模型")是按方言用 after_create DDL 创建的,不在 metadata +中,因此在此显式按方言创建(其它不支持部分索引的方言跳过,由 init_db 的 +启动校验兜底)。 + +Revision ID: 20261106_0001 +Revises: +Create Date: 2026-11-06 17:21:17.945187 + +""" +from collections.abc import Sequence + +import app.db.models +import sqlmodel.sql.sqltypes +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '20261106_0001' +down_revision: str | Sequence[str] | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +_PARTIAL_INDEX_NAME = "uq_model_configs_tenant_default" + + +def _dialect_name() -> str: + """当前迁移连接的方言名;离线 --sql 模式没有真实连接,取 context 的方言。""" + bind = op.get_bind() + if bind is None: + return op.get_context().dialect.name + return bind.dialect.name + + +def _create_partial_default_model_index() -> None: + """复刻 models.py 中按方言创建的"每租户至多一条默认模型"部分唯一索引。""" + dialect_name = _dialect_name() + if dialect_name == "sqlite": + op.execute( + f"CREATE UNIQUE INDEX {_PARTIAL_INDEX_NAME} " + "ON model_configs (tenant_id) WHERE is_default = 1" + ) + elif dialect_name == "postgresql": + op.execute( + f"CREATE UNIQUE INDEX {_PARTIAL_INDEX_NAME} " + "ON model_configs (tenant_id) WHERE is_default" + ) + # mysql/达梦等不支持部分索引:不创建,由启动期 _validate_default_model_invariant 兜底 + + +def _drop_partial_default_model_index() -> None: + if _dialect_name() in ("sqlite", "postgresql"): + op.execute(f"DROP INDEX IF EXISTS {_PARTIAL_INDEX_NAME}") + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('a2a_task_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('run_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sequence', sa.Integer(), nullable=False), + sa.Column('external_event_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('event_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('data_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('run_id', 'sequence', name='uq_a2a_task_event_sequence') + ) + op.create_index(op.f('ix_a2a_task_events_event_type'), 'a2a_task_events', ['event_type'], unique=False) + op.create_index(op.f('ix_a2a_task_events_external_event_id'), 'a2a_task_events', ['external_event_id'], unique=False) + op.create_index(op.f('ix_a2a_task_events_run_id'), 'a2a_task_events', ['run_id'], unique=False) + op.create_index(op.f('ix_a2a_task_events_sequence'), 'a2a_task_events', ['sequence'], unique=False) + op.create_index(op.f('ix_a2a_task_events_tenant_id'), 'a2a_task_events', ['tenant_id'], unique=False) + op.create_table('a2a_task_runs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('direction', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tool_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('invocation_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('endpoint_url', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_card_url', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('protocol_binding', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('protocol_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('remote_task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('context_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('codex_session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('request_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('result_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('artifacts_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('agent_card_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('last_event_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('cancel_requested', sa.Boolean(), nullable=False), + sa.Column('recovery_attempts', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_a2a_task_runs_agent_id'), 'a2a_task_runs', ['agent_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_codex_session_id'), 'a2a_task_runs', ['codex_session_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_context_id'), 'a2a_task_runs', ['context_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_direction'), 'a2a_task_runs', ['direction'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_invocation_id'), 'a2a_task_runs', ['invocation_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_last_event_id'), 'a2a_task_runs', ['last_event_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_remote_task_id'), 'a2a_task_runs', ['remote_task_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_session_id'), 'a2a_task_runs', ['session_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_status'), 'a2a_task_runs', ['status'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_tenant_id'), 'a2a_task_runs', ['tenant_id'], unique=False) + op.create_index(op.f('ix_a2a_task_runs_tool_id'), 'a2a_task_runs', ['tool_id'], unique=False) + op.create_table('agent_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('event_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_agent_events_event_type'), 'agent_events', ['event_type'], unique=False) + op.create_index(op.f('ix_agent_events_session_id'), 'agent_events', ['session_id'], unique=False) + op.create_index(op.f('ix_agent_events_tenant_id'), 'agent_events', ['tenant_id'], unique=False) + op.create_table('agent_knowledge_branches', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('base_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('head_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sync_state', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'agent_id', 'knowledge_base_id', name='uq_agent_knowledge_branch') + ) + op.create_index(op.f('ix_agent_knowledge_branches_agent_id'), 'agent_knowledge_branches', ['agent_id'], unique=False) + op.create_index(op.f('ix_agent_knowledge_branches_knowledge_base_id'), 'agent_knowledge_branches', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_agent_knowledge_branches_status'), 'agent_knowledge_branches', ['status'], unique=False) + op.create_index(op.f('ix_agent_knowledge_branches_sync_state'), 'agent_knowledge_branches', ['sync_state'], unique=False) + op.create_index(op.f('ix_agent_knowledge_branches_tenant_id'), 'agent_knowledge_branches', ['tenant_id'], unique=False) + op.create_table('agent_model_bindings', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('role', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('model_config_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'agent_id', 'role', name='uq_agent_model_binding') + ) + op.create_index(op.f('ix_agent_model_bindings_agent_id'), 'agent_model_bindings', ['agent_id'], unique=False) + op.create_index(op.f('ix_agent_model_bindings_model_config_id'), 'agent_model_bindings', ['model_config_id'], unique=False) + op.create_index(op.f('ix_agent_model_bindings_role'), 'agent_model_bindings', ['role'], unique=False) + op.create_index(op.f('ix_agent_model_bindings_tenant_id'), 'agent_model_bindings', ['tenant_id'], unique=False) + op.create_table('agent_profiles', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('persona_prompt', sa.Text(), nullable=True), + sa.Column('is_overall', sa.Boolean(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('harness_max_actions', sa.Integer(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'name', name='uq_agent_profile_tenant_name') + ) + op.create_index(op.f('ix_agent_profiles_is_overall'), 'agent_profiles', ['is_overall'], unique=False) + op.create_index(op.f('ix_agent_profiles_status'), 'agent_profiles', ['status'], unique=False) + op.create_index(op.f('ix_agent_profiles_tenant_id'), 'agent_profiles', ['tenant_id'], unique=False) + op.create_table('agent_resource_bindings', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'agent_id', 'resource_type', 'resource_id', name='uq_agent_resource') + ) + op.create_index(op.f('ix_agent_resource_bindings_agent_id'), 'agent_resource_bindings', ['agent_id'], unique=False) + op.create_index(op.f('ix_agent_resource_bindings_resource_id'), 'agent_resource_bindings', ['resource_id'], unique=False) + op.create_index(op.f('ix_agent_resource_bindings_resource_type'), 'agent_resource_bindings', ['resource_type'], unique=False) + op.create_index(op.f('ix_agent_resource_bindings_status'), 'agent_resource_bindings', ['status'], unique=False) + op.create_index(op.f('ix_agent_resource_bindings_tenant_id'), 'agent_resource_bindings', ['tenant_id'], unique=False) + op.create_table('agent_skill_branch_versions', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('base_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content_json', app.db.models.PortableJSON(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sync_state', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('change_summary', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'agent_id', 'skill_id', 'version', name='uq_agent_skill_branch_version') + ) + op.create_index(op.f('ix_agent_skill_branch_versions_agent_id'), 'agent_skill_branch_versions', ['agent_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branch_versions_skill_id'), 'agent_skill_branch_versions', ['skill_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branch_versions_source_skill_id'), 'agent_skill_branch_versions', ['source_skill_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branch_versions_status'), 'agent_skill_branch_versions', ['status'], unique=False) + op.create_index(op.f('ix_agent_skill_branch_versions_sync_state'), 'agent_skill_branch_versions', ['sync_state'], unique=False) + op.create_index(op.f('ix_agent_skill_branch_versions_tenant_id'), 'agent_skill_branch_versions', ['tenant_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branch_versions_version'), 'agent_skill_branch_versions', ['version'], unique=False) + op.create_table('agent_skill_branches', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('base_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('head_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content_json', app.db.models.PortableJSON(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sync_state', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'agent_id', 'skill_id', name='uq_agent_skill_branch') + ) + op.create_index(op.f('ix_agent_skill_branches_agent_id'), 'agent_skill_branches', ['agent_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branches_skill_id'), 'agent_skill_branches', ['skill_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branches_source_skill_id'), 'agent_skill_branches', ['source_skill_id'], unique=False) + op.create_index(op.f('ix_agent_skill_branches_status'), 'agent_skill_branches', ['status'], unique=False) + op.create_index(op.f('ix_agent_skill_branches_sync_state'), 'agent_skill_branches', ['sync_state'], unique=False) + op.create_index(op.f('ix_agent_skill_branches_tenant_id'), 'agent_skill_branches', ['tenant_id'], unique=False) + op.create_table('agent_usages', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'user_id', 'agent_id', name='uq_agent_usage_user_agent') + ) + op.create_index(op.f('ix_agent_usages_agent_id'), 'agent_usages', ['agent_id'], unique=False) + op.create_index(op.f('ix_agent_usages_tenant_id'), 'agent_usages', ['tenant_id'], unique=False) + op.create_index(op.f('ix_agent_usages_user_id'), 'agent_usages', ['user_id'], unique=False) + op.create_table('api_audit_logs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('credential_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('request_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('method', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('path', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_type', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('resource_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status_code', sa.Integer(), nullable=False), + sa.Column('duration_ms', sa.Float(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_api_audit_logs_credential_id'), 'api_audit_logs', ['credential_id'], unique=False) + op.create_index(op.f('ix_api_audit_logs_request_id'), 'api_audit_logs', ['request_id'], unique=False) + op.create_index(op.f('ix_api_audit_logs_resource_id'), 'api_audit_logs', ['resource_id'], unique=False) + op.create_index(op.f('ix_api_audit_logs_resource_type'), 'api_audit_logs', ['resource_type'], unique=False) + op.create_index(op.f('ix_api_audit_logs_status_code'), 'api_audit_logs', ['status_code'], unique=False) + op.create_index(op.f('ix_api_audit_logs_tenant_id'), 'api_audit_logs', ['tenant_id'], unique=False) + op.create_table('api_clients', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('scopes_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'name', name='uq_api_client_tenant_name') + ) + op.create_index(op.f('ix_api_clients_created_by_user_id'), 'api_clients', ['created_by_user_id'], unique=False) + op.create_index(op.f('ix_api_clients_status'), 'api_clients', ['status'], unique=False) + op.create_index(op.f('ix_api_clients_tenant_id'), 'api_clients', ['tenant_id'], unique=False) + op.create_table('api_credentials', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('client_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('key_prefix', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('key_digest', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('scopes_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('last_used_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('revoked_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('key_prefix', name='uq_api_credential_prefix') + ) + op.create_index(op.f('ix_api_credentials_agent_id'), 'api_credentials', ['agent_id'], unique=False) + op.create_index(op.f('ix_api_credentials_client_id'), 'api_credentials', ['client_id'], unique=False) + op.create_index(op.f('ix_api_credentials_expires_at'), 'api_credentials', ['expires_at'], unique=False) + op.create_index(op.f('ix_api_credentials_key_prefix'), 'api_credentials', ['key_prefix'], unique=False) + op.create_index(op.f('ix_api_credentials_last_used_at'), 'api_credentials', ['last_used_at'], unique=False) + op.create_index(op.f('ix_api_credentials_status'), 'api_credentials', ['status'], unique=False) + op.create_index(op.f('ix_api_credentials_tenant_id'), 'api_credentials', ['tenant_id'], unique=False) + op.create_table('api_idempotency_records', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('credential_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('method', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('path', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('idempotency_key', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('request_hash', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status_code', sa.Integer(), nullable=False), + sa.Column('response_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('resource_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('expires_at', sa.DateTime(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('credential_id', 'method', 'path', 'idempotency_key', name='uq_api_idempotency_request') + ) + op.create_index(op.f('ix_api_idempotency_records_credential_id'), 'api_idempotency_records', ['credential_id'], unique=False) + op.create_index(op.f('ix_api_idempotency_records_expires_at'), 'api_idempotency_records', ['expires_at'], unique=False) + op.create_index(op.f('ix_api_idempotency_records_idempotency_key'), 'api_idempotency_records', ['idempotency_key'], unique=False) + op.create_index(op.f('ix_api_idempotency_records_resource_id'), 'api_idempotency_records', ['resource_id'], unique=False) + op.create_index(op.f('ix_api_idempotency_records_tenant_id'), 'api_idempotency_records', ['tenant_id'], unique=False) + op.create_table('api_job_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('job_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sequence', sa.Integer(), nullable=False), + sa.Column('event_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('data_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('public', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('job_id', 'sequence', name='uq_api_job_event_sequence') + ) + op.create_index(op.f('ix_api_job_events_event_type'), 'api_job_events', ['event_type'], unique=False) + op.create_index(op.f('ix_api_job_events_job_id'), 'api_job_events', ['job_id'], unique=False) + op.create_index(op.f('ix_api_job_events_sequence'), 'api_job_events', ['sequence'], unique=False) + op.create_index(op.f('ix_api_job_events_tenant_id'), 'api_job_events', ['tenant_id'], unique=False) + op.create_table('api_jobs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('credential_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('stage', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('progress', sa.Float(), nullable=False), + sa.Column('request_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('result_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('cancel_requested', sa.Boolean(), nullable=False), + sa.Column('retryable', sa.Boolean(), nullable=False), + sa.Column('execution_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('execution_generation', sa.Integer(), nullable=False), + sa.Column('lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_api_jobs_agent_id'), 'api_jobs', ['agent_id'], unique=False) + op.create_index(op.f('ix_api_jobs_credential_id'), 'api_jobs', ['credential_id'], unique=False) + op.create_index(op.f('ix_api_jobs_execution_owner'), 'api_jobs', ['execution_owner'], unique=False) + op.create_index(op.f('ix_api_jobs_kind'), 'api_jobs', ['kind'], unique=False) + op.create_index(op.f('ix_api_jobs_lease_expires_at'), 'api_jobs', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_api_jobs_session_id'), 'api_jobs', ['session_id'], unique=False) + op.create_index(op.f('ix_api_jobs_stage'), 'api_jobs', ['stage'], unique=False) + op.create_index(op.f('ix_api_jobs_status'), 'api_jobs', ['status'], unique=False) + op.create_index(op.f('ix_api_jobs_tenant_id'), 'api_jobs', ['tenant_id'], unique=False) + op.create_table('api_sop_drafts', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('base_version', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('draft_version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content_json', app.db.models.PortableJSON(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('warnings_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('validation_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('etag', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_by_credential_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('published_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_api_sop_drafts_agent_id'), 'api_sop_drafts', ['agent_id'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_base_version'), 'api_sop_drafts', ['base_version'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_created_by_credential_id'), 'api_sop_drafts', ['created_by_credential_id'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_draft_version'), 'api_sop_drafts', ['draft_version'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_etag'), 'api_sop_drafts', ['etag'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_skill_id'), 'api_sop_drafts', ['skill_id'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_source'), 'api_sop_drafts', ['source'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_status'), 'api_sop_drafts', ['status'], unique=False) + op.create_index(op.f('ix_api_sop_drafts_tenant_id'), 'api_sop_drafts', ['tenant_id'], unique=False) + op.create_table('channel_bind_codes', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('code', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('expires_at', sa.DateTime(), nullable=False), + sa.Column('used_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'code', name='uq_channel_bind_code_tenant_code'), + sa.UniqueConstraint('tenant_id', 'user_id', name='uq_channel_bind_code_tenant_user') + ) + op.create_index(op.f('ix_channel_bind_codes_code'), 'channel_bind_codes', ['code'], unique=False) + op.create_index(op.f('ix_channel_bind_codes_tenant_id'), 'channel_bind_codes', ['tenant_id'], unique=False) + op.create_index(op.f('ix_channel_bind_codes_user_id'), 'channel_bind_codes', ['user_id'], unique=False) + op.create_table('channel_binding_agents', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('is_default', sa.Boolean(), nullable=False), + sa.Column('sort_order', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('binding_id', 'agent_id', name='uq_channel_binding_agent') + ) + op.create_index(op.f('ix_channel_binding_agents_agent_id'), 'channel_binding_agents', ['agent_id'], unique=False) + op.create_index(op.f('ix_channel_binding_agents_binding_id'), 'channel_binding_agents', ['binding_id'], unique=False) + op.create_index(op.f('ix_channel_binding_agents_tenant_id'), 'channel_binding_agents', ['tenant_id'], unique=False) + op.create_table('channel_binding_managers', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('granted_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('granted_at', sa.DateTime(), nullable=False), + sa.Column('revoked_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('binding_id', 'user_id', name='uq_channel_binding_manager') + ) + op.create_index(op.f('ix_channel_binding_managers_binding_id'), 'channel_binding_managers', ['binding_id'], unique=False) + op.create_index(op.f('ix_channel_binding_managers_tenant_id'), 'channel_binding_managers', ['tenant_id'], unique=False) + op.create_index('ix_channel_binding_managers_tenant_user', 'channel_binding_managers', ['tenant_id', 'user_id'], unique=False) + op.create_index(op.f('ix_channel_binding_managers_user_id'), 'channel_binding_managers', ['user_id'], unique=False) + op.create_table('channel_bindings', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('channel', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('credentials_enc', sa.Text(), nullable=True), + sa.Column('config_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('external_account_key', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('identity_scope_key', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('provider_tenant_key', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('config_revision', sa.Integer(), server_default='0', nullable=False), + sa.Column('connected', sa.Boolean(), nullable=False), + sa.Column('last_connected_at', sa.DateTime(), nullable=True), + sa.Column('created_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_channel_bindings_agent_id'), 'channel_bindings', ['agent_id'], unique=False) + op.create_index(op.f('ix_channel_bindings_channel'), 'channel_bindings', ['channel'], unique=False) + op.create_index(op.f('ix_channel_bindings_created_by_user_id'), 'channel_bindings', ['created_by_user_id'], unique=False) + op.create_index(op.f('ix_channel_bindings_external_account_key'), 'channel_bindings', ['external_account_key'], unique=True) + op.create_index(op.f('ix_channel_bindings_identity_scope_key'), 'channel_bindings', ['identity_scope_key'], unique=False) + op.create_index(op.f('ix_channel_bindings_provider_tenant_key'), 'channel_bindings', ['provider_tenant_key'], unique=False) + op.create_index(op.f('ix_channel_bindings_status'), 'channel_bindings', ['status'], unique=False) + op.create_index(op.f('ix_channel_bindings_team_id'), 'channel_bindings', ['team_id'], unique=False) + op.create_index(op.f('ix_channel_bindings_tenant_id'), 'channel_bindings', ['tenant_id'], unique=False) + op.create_table('channel_conv_states', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('external_conv_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('current_agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('routing_revision', sa.Integer(), server_default='0', nullable=False), + sa.Column('manual_pin_until', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('binding_id', 'external_conv_id', name='uq_channel_conv_state') + ) + op.create_index(op.f('ix_channel_conv_states_binding_id'), 'channel_conv_states', ['binding_id'], unique=False) + op.create_index(op.f('ix_channel_conv_states_tenant_id'), 'channel_conv_states', ['tenant_id'], unique=False) + op.create_table('channel_deliveries', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('message_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('target_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('text', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('attempts', sa.Integer(), nullable=False), + sa.Column('next_attempt_at', sa.DateTime(), nullable=True), + sa.Column('sending_since', sa.DateTime(), nullable=True), + sa.Column('delivery_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('delivery_generation', sa.Integer(), server_default='0', nullable=False), + sa.Column('last_error', sa.Text(), nullable=True), + sa.Column('idempotency_key', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('first_attempt_at', sa.DateTime(), nullable=True), + sa.Column('delivered_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_channel_deliveries_binding_id'), 'channel_deliveries', ['binding_id'], unique=False) + op.create_index(op.f('ix_channel_deliveries_delivery_owner'), 'channel_deliveries', ['delivery_owner'], unique=False) + op.create_index(op.f('ix_channel_deliveries_idempotency_key'), 'channel_deliveries', ['idempotency_key'], unique=True) + op.create_index(op.f('ix_channel_deliveries_kind'), 'channel_deliveries', ['kind'], unique=False) + op.create_index(op.f('ix_channel_deliveries_message_id'), 'channel_deliveries', ['message_id'], unique=False) + op.create_index(op.f('ix_channel_deliveries_next_attempt_at'), 'channel_deliveries', ['next_attempt_at'], unique=False) + op.create_index(op.f('ix_channel_deliveries_session_id'), 'channel_deliveries', ['session_id'], unique=False) + op.create_index(op.f('ix_channel_deliveries_status'), 'channel_deliveries', ['status'], unique=False) + op.create_index(op.f('ix_channel_deliveries_tenant_id'), 'channel_deliveries', ['tenant_id'], unique=False) + op.create_table('channel_identities', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('channel', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('external_account_scope', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('external_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('staffdeck_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('display_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'channel', 'external_account_scope', 'external_user_id', name='uq_channel_identity_scope_external') + ) + op.create_index(op.f('ix_channel_identities_channel'), 'channel_identities', ['channel'], unique=False) + op.create_index(op.f('ix_channel_identities_external_account_scope'), 'channel_identities', ['external_account_scope'], unique=False) + op.create_index(op.f('ix_channel_identities_staffdeck_user_id'), 'channel_identities', ['staffdeck_user_id'], unique=False) + op.create_index(op.f('ix_channel_identities_tenant_id'), 'channel_identities', ['tenant_id'], unique=False) + op.create_table('channel_inbound_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('channel', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('event_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('config_revision', sa.Integer(), server_default='0', nullable=False), + sa.Column('target_json', app.db.models.PortableJSON(), server_default='{}', nullable=False), + sa.Column('reaction_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('processor_run_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('processor_lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('processed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('binding_id', 'event_id', name='uq_channel_inbound_event_binding') + ) + op.create_index(op.f('ix_channel_inbound_events_binding_id'), 'channel_inbound_events', ['binding_id'], unique=False) + op.create_index('ix_channel_inbound_events_binding_status_created', 'channel_inbound_events', ['binding_id', 'status', 'created_at'], unique=False) + op.create_index(op.f('ix_channel_inbound_events_channel'), 'channel_inbound_events', ['channel'], unique=False) + op.create_index(op.f('ix_channel_inbound_events_processor_lease_expires_at'), 'channel_inbound_events', ['processor_lease_expires_at'], unique=False) + op.create_index(op.f('ix_channel_inbound_events_processor_run_id'), 'channel_inbound_events', ['processor_run_id'], unique=False) + op.create_index(op.f('ix_channel_inbound_events_reaction_id'), 'channel_inbound_events', ['reaction_id'], unique=False) + op.create_index(op.f('ix_channel_inbound_events_status'), 'channel_inbound_events', ['status'], unique=False) + op.create_index(op.f('ix_channel_inbound_events_tenant_id'), 'channel_inbound_events', ['tenant_id'], unique=False) + op.create_table('distribution_install_records', + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('package_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('tenant_id') + ) + op.create_table('evolution_proposals', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_key', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('resource_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('base_version', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('trigger_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('risk_level', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('hypothesis', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('rationale', sa.Text(), nullable=True), + sa.Column('expected_outcome', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_feedback_ids_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('evidence_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('candidate_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('diff_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('evaluation_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('published_snapshot_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('created_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('reviewed_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('reviewed_at', sa.DateTime(), nullable=True), + sa.Column('published_at', sa.DateTime(), nullable=True), + sa.Column('rolled_back_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_evolution_proposals_agent_id'), 'evolution_proposals', ['agent_id'], unique=False) + op.create_index(op.f('ix_evolution_proposals_base_version'), 'evolution_proposals', ['base_version'], unique=False) + op.create_index(op.f('ix_evolution_proposals_created_by_user_id'), 'evolution_proposals', ['created_by_user_id'], unique=False) + op.create_index(op.f('ix_evolution_proposals_resource_id'), 'evolution_proposals', ['resource_id'], unique=False) + op.create_index(op.f('ix_evolution_proposals_resource_key'), 'evolution_proposals', ['resource_key'], unique=False) + op.create_index(op.f('ix_evolution_proposals_resource_type'), 'evolution_proposals', ['resource_type'], unique=False) + op.create_index(op.f('ix_evolution_proposals_reviewed_by_user_id'), 'evolution_proposals', ['reviewed_by_user_id'], unique=False) + op.create_index(op.f('ix_evolution_proposals_risk_level'), 'evolution_proposals', ['risk_level'], unique=False) + op.create_index(op.f('ix_evolution_proposals_status'), 'evolution_proposals', ['status'], unique=False) + op.create_index(op.f('ix_evolution_proposals_tenant_id'), 'evolution_proposals', ['tenant_id'], unique=False) + op.create_index(op.f('ix_evolution_proposals_trigger_type'), 'evolution_proposals', ['trigger_type'], unique=False) + op.create_table('external_business_task_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('event_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('event_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('data_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('task_id', 'event_id', name='uq_external_business_task_event') + ) + op.create_index(op.f('ix_external_business_task_events_event_id'), 'external_business_task_events', ['event_id'], unique=False) + op.create_index(op.f('ix_external_business_task_events_event_type'), 'external_business_task_events', ['event_type'], unique=False) + op.create_index(op.f('ix_external_business_task_events_task_id'), 'external_business_task_events', ['task_id'], unique=False) + op.create_index(op.f('ix_external_business_task_events_tenant_id'), 'external_business_task_events', ['tenant_id'], unique=False) + op.create_table('external_business_tasks', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('task_frame_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('resume_step_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('invocation_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('tool_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('external_task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('idempotency_key', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('request_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('result_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('callback_token_hash', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status_url', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status_config_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('poll_interval_seconds', sa.Float(), nullable=False), + sa.Column('next_poll_at', sa.DateTime(), nullable=True), + sa.Column('poll_attempts', sa.Integer(), nullable=False), + sa.Column('lease_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('expires_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('accepted_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'user_id', 'tool_id', 'external_task_id', name='uq_external_business_task') + ) + op.create_index(op.f('ix_external_business_tasks_agent_id'), 'external_business_tasks', ['agent_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_expires_at'), 'external_business_tasks', ['expires_at'], unique=False) + op.create_index(op.f('ix_external_business_tasks_external_task_id'), 'external_business_tasks', ['external_task_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_idempotency_key'), 'external_business_tasks', ['idempotency_key'], unique=True) + op.create_index(op.f('ix_external_business_tasks_invocation_id'), 'external_business_tasks', ['invocation_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_lease_expires_at'), 'external_business_tasks', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_external_business_tasks_lease_owner'), 'external_business_tasks', ['lease_owner'], unique=False) + op.create_index(op.f('ix_external_business_tasks_next_poll_at'), 'external_business_tasks', ['next_poll_at'], unique=False) + op.create_index(op.f('ix_external_business_tasks_session_id'), 'external_business_tasks', ['session_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_status'), 'external_business_tasks', ['status'], unique=False) + op.create_index(op.f('ix_external_business_tasks_task_frame_id'), 'external_business_tasks', ['task_frame_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_tenant_id'), 'external_business_tasks', ['tenant_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_tool_id'), 'external_business_tasks', ['tool_id'], unique=False) + op.create_index(op.f('ix_external_business_tasks_user_id'), 'external_business_tasks', ['user_id'], unique=False) + op.create_table('external_session_bindings', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('credential_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('external_session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('external_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('credential_id', 'external_session_id', name='uq_external_session_credential_id') + ) + op.create_index(op.f('ix_external_session_bindings_agent_id'), 'external_session_bindings', ['agent_id'], unique=False) + op.create_index(op.f('ix_external_session_bindings_credential_id'), 'external_session_bindings', ['credential_id'], unique=False) + op.create_index(op.f('ix_external_session_bindings_external_session_id'), 'external_session_bindings', ['external_session_id'], unique=False) + op.create_index(op.f('ix_external_session_bindings_external_user_id'), 'external_session_bindings', ['external_user_id'], unique=False) + op.create_index(op.f('ix_external_session_bindings_session_id'), 'external_session_bindings', ['session_id'], unique=False) + op.create_index(op.f('ix_external_session_bindings_tenant_id'), 'external_session_bindings', ['tenant_id'], unique=False) + op.create_table('general_skills', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('slug', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('homepage', sa.Text(), nullable=True), + sa.Column('skill_markdown', sa.Text(), nullable=True), + sa.Column('skill_files_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('capability_scope', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('permissions_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('runtime_config_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'slug', name='uq_general_skill_tenant_slug') + ) + op.create_index(op.f('ix_general_skills_capability_scope'), 'general_skills', ['capability_scope'], unique=False) + op.create_index(op.f('ix_general_skills_slug'), 'general_skills', ['slug'], unique=False) + op.create_index(op.f('ix_general_skills_status'), 'general_skills', ['status'], unique=False) + op.create_index(op.f('ix_general_skills_tenant_id'), 'general_skills', ['tenant_id'], unique=False) + op.create_table('harness_agent_loops', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('loop_key', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('owner_task_frame_record_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('workspace_scope_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('checkpoint_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('last_run_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('state_version', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('session_id', 'loop_key', name='uq_harness_agent_loop_session_key') + ) + op.create_index(op.f('ix_harness_agent_loops_kind'), 'harness_agent_loops', ['kind'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_last_run_id'), 'harness_agent_loops', ['last_run_id'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_loop_key'), 'harness_agent_loops', ['loop_key'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_owner_task_frame_record_id'), 'harness_agent_loops', ['owner_task_frame_record_id'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_session_id'), 'harness_agent_loops', ['session_id'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_skill_id'), 'harness_agent_loops', ['skill_id'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_status'), 'harness_agent_loops', ['status'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_tenant_id'), 'harness_agent_loops', ['tenant_id'], unique=False) + op.create_index(op.f('ix_harness_agent_loops_workspace_scope_id'), 'harness_agent_loops', ['workspace_scope_id'], unique=False) + op.create_table('harness_invocations', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('run_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('call_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tool_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('request_digest', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('logical_action_key', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('replayed_from_invocation_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('arguments_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('result_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('response_cache_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('approval_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=False), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('run_id', 'call_id', name='uq_harness_invocation_run_call') + ) + op.create_index(op.f('ix_harness_invocations_call_id'), 'harness_invocations', ['call_id'], unique=False) + op.create_index(op.f('ix_harness_invocations_logical_action_key'), 'harness_invocations', ['logical_action_key'], unique=True) + op.create_index(op.f('ix_harness_invocations_replayed_from_invocation_id'), 'harness_invocations', ['replayed_from_invocation_id'], unique=False) + op.create_index(op.f('ix_harness_invocations_request_digest'), 'harness_invocations', ['request_digest'], unique=False) + op.create_index(op.f('ix_harness_invocations_run_id'), 'harness_invocations', ['run_id'], unique=False) + op.create_index(op.f('ix_harness_invocations_session_id'), 'harness_invocations', ['session_id'], unique=False) + op.create_index(op.f('ix_harness_invocations_status'), 'harness_invocations', ['status'], unique=False) + op.create_index(op.f('ix_harness_invocations_task_id'), 'harness_invocations', ['task_id'], unique=False) + op.create_index(op.f('ix_harness_invocations_tenant_id'), 'harness_invocations', ['tenant_id'], unique=False) + op.create_index(op.f('ix_harness_invocations_tool_name'), 'harness_invocations', ['tool_name'], unique=False) + op.create_table('harness_runs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('task_frame_record_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_loop_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_turn_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False), + sa.Column('lease_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('action_count', sa.Integer(), nullable=False), + sa.Column('task_requirement_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('capability_snapshot_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('result_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=False), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_harness_runs_agent_loop_id'), 'harness_runs', ['agent_loop_id'], unique=False) + op.create_index(op.f('ix_harness_runs_lease_expires_at'), 'harness_runs', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_harness_runs_lease_owner'), 'harness_runs', ['lease_owner'], unique=False) + op.create_index(op.f('ix_harness_runs_session_id'), 'harness_runs', ['session_id'], unique=False) + op.create_index(op.f('ix_harness_runs_source_turn_id'), 'harness_runs', ['source_turn_id'], unique=False) + op.create_index(op.f('ix_harness_runs_status'), 'harness_runs', ['status'], unique=False) + op.create_index(op.f('ix_harness_runs_task_frame_record_id'), 'harness_runs', ['task_frame_record_id'], unique=False) + op.create_index(op.f('ix_harness_runs_task_id'), 'harness_runs', ['task_id'], unique=False) + op.create_index(op.f('ix_harness_runs_tenant_id'), 'harness_runs', ['tenant_id'], unique=False) + op.create_table('harness_session_leases', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('lease_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('lease_expires_at', sa.DateTime(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'session_id', name='uq_harness_session_execution_lease') + ) + op.create_index(op.f('ix_harness_session_leases_lease_expires_at'), 'harness_session_leases', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_harness_session_leases_lease_owner'), 'harness_session_leases', ['lease_owner'], unique=False) + op.create_index(op.f('ix_harness_session_leases_session_id'), 'harness_session_leases', ['session_id'], unique=False) + op.create_index(op.f('ix_harness_session_leases_tenant_id'), 'harness_session_leases', ['tenant_id'], unique=False) + op.create_table('harness_task_frames', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_turn_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_loop_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('decision', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sequence', sa.Integer(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('step_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('user_intent', sa.Text(), nullable=True), + sa.Column('requirements_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('slots_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('depends_on_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('task_requirement_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('result_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('state_version', sa.Integer(), nullable=False), + sa.Column('attempt_no', sa.Integer(), nullable=False), + sa.Column('lease_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('session_id', 'task_id', name='uq_harness_task_frame_session_task') + ) + op.create_index(op.f('ix_harness_task_frames_agent_loop_id'), 'harness_task_frames', ['agent_loop_id'], unique=False) + op.create_index(op.f('ix_harness_task_frames_decision'), 'harness_task_frames', ['decision'], unique=False) + op.create_index(op.f('ix_harness_task_frames_kind'), 'harness_task_frames', ['kind'], unique=False) + op.create_index(op.f('ix_harness_task_frames_lease_expires_at'), 'harness_task_frames', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_harness_task_frames_lease_owner'), 'harness_task_frames', ['lease_owner'], unique=False) + op.create_index(op.f('ix_harness_task_frames_session_id'), 'harness_task_frames', ['session_id'], unique=False) + op.create_index(op.f('ix_harness_task_frames_skill_id'), 'harness_task_frames', ['skill_id'], unique=False) + op.create_index(op.f('ix_harness_task_frames_source_turn_id'), 'harness_task_frames', ['source_turn_id'], unique=False) + op.create_index(op.f('ix_harness_task_frames_status'), 'harness_task_frames', ['status'], unique=False) + op.create_index(op.f('ix_harness_task_frames_step_id'), 'harness_task_frames', ['step_id'], unique=False) + op.create_index(op.f('ix_harness_task_frames_task_id'), 'harness_task_frames', ['task_id'], unique=False) + op.create_index(op.f('ix_harness_task_frames_tenant_id'), 'harness_task_frames', ['tenant_id'], unique=False) + op.create_table('harness_turns', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('client_turn_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('request_digest', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('lease_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('lease_expires_at', sa.DateTime(), nullable=False), + sa.Column('user_message_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('response_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('started_at', sa.DateTime(), nullable=False), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'session_id', 'client_turn_id', name='uq_harness_turn_client_receipt') + ) + op.create_index(op.f('ix_harness_turns_client_turn_id'), 'harness_turns', ['client_turn_id'], unique=False) + op.create_index(op.f('ix_harness_turns_lease_expires_at'), 'harness_turns', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_harness_turns_lease_owner'), 'harness_turns', ['lease_owner'], unique=False) + op.create_index(op.f('ix_harness_turns_request_digest'), 'harness_turns', ['request_digest'], unique=False) + op.create_index(op.f('ix_harness_turns_session_id'), 'harness_turns', ['session_id'], unique=False) + op.create_index(op.f('ix_harness_turns_status'), 'harness_turns', ['status'], unique=False) + op.create_index(op.f('ix_harness_turns_tenant_id'), 'harness_turns', ['tenant_id'], unique=False) + op.create_index(op.f('ix_harness_turns_user_message_id'), 'harness_turns', ['user_message_id'], unique=False) + op.create_table('human_handoff_requests', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('requester_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('assignee_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('trigger_skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('trigger_step_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('context_summary', sa.Text(), nullable=True), + sa.Column('pending_question', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('human_reply', sa.Text(), nullable=True), + sa.Column('resume_payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('answered_at', sa.DateTime(), nullable=True), + sa.Column('notify_message_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_human_handoff_requests_agent_id'), 'human_handoff_requests', ['agent_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_assignee_user_id'), 'human_handoff_requests', ['assignee_user_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_notify_message_id'), 'human_handoff_requests', ['notify_message_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_requester_user_id'), 'human_handoff_requests', ['requester_user_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_session_id'), 'human_handoff_requests', ['session_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_status'), 'human_handoff_requests', ['status'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_tenant_id'), 'human_handoff_requests', ['tenant_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_trigger_skill_id'), 'human_handoff_requests', ['trigger_skill_id'], unique=False) + op.create_index(op.f('ix_human_handoff_requests_trigger_step_id'), 'human_handoff_requests', ['trigger_step_id'], unique=False) + op.create_table('knowledge_base_versions', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('capability_scope', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'knowledge_base_id', 'version', name='uq_knowledge_base_version') + ) + op.create_index(op.f('ix_knowledge_base_versions_capability_scope'), 'knowledge_base_versions', ['capability_scope'], unique=False) + op.create_index(op.f('ix_knowledge_base_versions_knowledge_base_id'), 'knowledge_base_versions', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_base_versions_status'), 'knowledge_base_versions', ['status'], unique=False) + op.create_index(op.f('ix_knowledge_base_versions_tenant_id'), 'knowledge_base_versions', ['tenant_id'], unique=False) + op.create_index(op.f('ix_knowledge_base_versions_version'), 'knowledge_base_versions', ['version'], unique=False) + op.create_table('knowledge_bases', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('capability_scope', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'name', name='uq_knowledge_base_tenant_name') + ) + op.create_index(op.f('ix_knowledge_bases_capability_scope'), 'knowledge_bases', ['capability_scope'], unique=False) + op.create_index(op.f('ix_knowledge_bases_status'), 'knowledge_bases', ['status'], unique=False) + op.create_index(op.f('ix_knowledge_bases_tenant_id'), 'knowledge_bases', ['tenant_id'], unique=False) + op.create_table('knowledge_buckets', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_version_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('document_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('bucket_key', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('summary', sa.Text(), nullable=True), + sa.Column('token_estimate', sa.Integer(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_knowledge_buckets_bucket_key'), 'knowledge_buckets', ['bucket_key'], unique=False) + op.create_index(op.f('ix_knowledge_buckets_document_id'), 'knowledge_buckets', ['document_id'], unique=False) + op.create_index(op.f('ix_knowledge_buckets_knowledge_base_id'), 'knowledge_buckets', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_buckets_knowledge_base_version_id'), 'knowledge_buckets', ['knowledge_base_version_id'], unique=False) + op.create_index(op.f('ix_knowledge_buckets_tenant_id'), 'knowledge_buckets', ['tenant_id'], unique=False) + op.create_table('knowledge_chunks', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_version_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('document_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('bucket_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('chunk_index', sa.Integer(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('summary', sa.Text(), nullable=True), + sa.Column('source_ref', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_knowledge_chunks_bucket_id'), 'knowledge_chunks', ['bucket_id'], unique=False) + op.create_index(op.f('ix_knowledge_chunks_chunk_index'), 'knowledge_chunks', ['chunk_index'], unique=False) + op.create_index(op.f('ix_knowledge_chunks_document_id'), 'knowledge_chunks', ['document_id'], unique=False) + op.create_index(op.f('ix_knowledge_chunks_knowledge_base_id'), 'knowledge_chunks', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_chunks_knowledge_base_version_id'), 'knowledge_chunks', ['knowledge_base_version_id'], unique=False) + op.create_index(op.f('ix_knowledge_chunks_tenant_id'), 'knowledge_chunks', ['tenant_id'], unique=False) + op.create_table('knowledge_concepts', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_version_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('document_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('concept_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('concept_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('content_md', sa.Text(), nullable=True), + sa.Column('frontmatter_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('links_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('citations_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('source_refs_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'knowledge_base_version_id', 'concept_id', name='uq_knowledge_concept_version_path') + ) + op.create_index(op.f('ix_knowledge_concepts_concept_id'), 'knowledge_concepts', ['concept_id'], unique=False) + op.create_index(op.f('ix_knowledge_concepts_concept_type'), 'knowledge_concepts', ['concept_type'], unique=False) + op.create_index(op.f('ix_knowledge_concepts_document_id'), 'knowledge_concepts', ['document_id'], unique=False) + op.create_index(op.f('ix_knowledge_concepts_knowledge_base_id'), 'knowledge_concepts', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_concepts_knowledge_base_version_id'), 'knowledge_concepts', ['knowledge_base_version_id'], unique=False) + op.create_index(op.f('ix_knowledge_concepts_status'), 'knowledge_concepts', ['status'], unique=False) + op.create_index(op.f('ix_knowledge_concepts_tenant_id'), 'knowledge_concepts', ['tenant_id'], unique=False) + op.create_table('knowledge_discovery_suggestions', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_version_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('document_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('bucket_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('suggestion_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('source_refs_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('reason', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_knowledge_discovery_suggestions_bucket_id'), 'knowledge_discovery_suggestions', ['bucket_id'], unique=False) + op.create_index(op.f('ix_knowledge_discovery_suggestions_document_id'), 'knowledge_discovery_suggestions', ['document_id'], unique=False) + op.create_index(op.f('ix_knowledge_discovery_suggestions_knowledge_base_id'), 'knowledge_discovery_suggestions', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_discovery_suggestions_knowledge_base_version_id'), 'knowledge_discovery_suggestions', ['knowledge_base_version_id'], unique=False) + op.create_index(op.f('ix_knowledge_discovery_suggestions_status'), 'knowledge_discovery_suggestions', ['status'], unique=False) + op.create_index(op.f('ix_knowledge_discovery_suggestions_suggestion_type'), 'knowledge_discovery_suggestions', ['suggestion_type'], unique=False) + op.create_index(op.f('ix_knowledge_discovery_suggestions_tenant_id'), 'knowledge_discovery_suggestions', ['tenant_id'], unique=False) + op.create_table('knowledge_documents', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_version_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('filename', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('file_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('bucket_count', sa.Integer(), nullable=False), + sa.Column('chunk_count', sa.Integer(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_knowledge_documents_file_type'), 'knowledge_documents', ['file_type'], unique=False) + op.create_index(op.f('ix_knowledge_documents_knowledge_base_id'), 'knowledge_documents', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_documents_knowledge_base_version_id'), 'knowledge_documents', ['knowledge_base_version_id'], unique=False) + op.create_index(op.f('ix_knowledge_documents_status'), 'knowledge_documents', ['status'], unique=False) + op.create_index(op.f('ix_knowledge_documents_tenant_id'), 'knowledge_documents', ['tenant_id'], unique=False) + op.create_table('knowledge_ingest_jobs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('knowledge_base_version_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('document_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('filename', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('stage', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('progress', sa.Float(), nullable=False), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_knowledge_ingest_jobs_document_id'), 'knowledge_ingest_jobs', ['document_id'], unique=False) + op.create_index(op.f('ix_knowledge_ingest_jobs_knowledge_base_id'), 'knowledge_ingest_jobs', ['knowledge_base_id'], unique=False) + op.create_index(op.f('ix_knowledge_ingest_jobs_knowledge_base_version_id'), 'knowledge_ingest_jobs', ['knowledge_base_version_id'], unique=False) + op.create_index(op.f('ix_knowledge_ingest_jobs_status'), 'knowledge_ingest_jobs', ['status'], unique=False) + op.create_index(op.f('ix_knowledge_ingest_jobs_tenant_id'), 'knowledge_ingest_jobs', ['tenant_id'], unique=False) + op.create_table('mcp_servers', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('display_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('bucket', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('transport', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('url', sa.Text(), nullable=True), + sa.Column('headers_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('command', sa.Text(), nullable=True), + sa.Column('args_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('env_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('cwd', sa.Text(), nullable=True), + sa.Column('apps_mode', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('negotiated_capabilities_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('discovered_tools_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('last_synced_at', sa.DateTime(), nullable=True), + sa.Column('capability_scope', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'name', name='uq_mcp_server_tenant_name') + ) + op.create_index(op.f('ix_mcp_servers_apps_mode'), 'mcp_servers', ['apps_mode'], unique=False) + op.create_index(op.f('ix_mcp_servers_bucket'), 'mcp_servers', ['bucket'], unique=False) + op.create_index(op.f('ix_mcp_servers_capability_scope'), 'mcp_servers', ['capability_scope'], unique=False) + op.create_index(op.f('ix_mcp_servers_name'), 'mcp_servers', ['name'], unique=False) + op.create_index(op.f('ix_mcp_servers_tenant_id'), 'mcp_servers', ['tenant_id'], unique=False) + op.create_index(op.f('ix_mcp_servers_transport'), 'mcp_servers', ['transport'], unique=False) + op.create_table('memories', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('importance', sa.Float(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_memories_kind'), 'memories', ['kind'], unique=False) + op.create_index(op.f('ix_memories_session_id'), 'memories', ['session_id'], unique=False) + op.create_index(op.f('ix_memories_tenant_id'), 'memories', ['tenant_id'], unique=False) + op.create_index(op.f('ix_memories_user_id'), 'memories', ['user_id'], unique=False) + op.create_index(op.f('ix_memories_username'), 'memories', ['username'], unique=False) + op.create_table('message_feedback', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('message_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('rating', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('analysis_status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('analysis_bucket', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('analysis_reason', sa.Text(), nullable=True), + sa.Column('analysis_summary', sa.Text(), nullable=True), + sa.Column('analysis_confidence', sa.Float(), nullable=True), + sa.Column('analysis_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('analyzed_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'message_id', 'user_id', name='uq_feedback_message_user') + ) + op.create_index(op.f('ix_message_feedback_analysis_bucket'), 'message_feedback', ['analysis_bucket'], unique=False) + op.create_index(op.f('ix_message_feedback_analysis_status'), 'message_feedback', ['analysis_status'], unique=False) + op.create_index(op.f('ix_message_feedback_message_id'), 'message_feedback', ['message_id'], unique=False) + op.create_index(op.f('ix_message_feedback_rating'), 'message_feedback', ['rating'], unique=False) + op.create_index(op.f('ix_message_feedback_session_id'), 'message_feedback', ['session_id'], unique=False) + op.create_index(op.f('ix_message_feedback_tenant_id'), 'message_feedback', ['tenant_id'], unique=False) + op.create_index(op.f('ix_message_feedback_user_id'), 'message_feedback', ['user_id'], unique=False) + op.create_table('messages', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('role', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_messages_session_id'), 'messages', ['session_id'], unique=False) + op.create_index(op.f('ix_messages_tenant_id'), 'messages', ['tenant_id'], unique=False) + op.create_table('mock_orders', + sa.Column('order_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('product_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('sku_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('quantity', sa.Integer(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payment_status', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('order_status', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('signed_days', sa.Integer(), nullable=False), + sa.Column('refundable', sa.Boolean(), nullable=False), + sa.Column('total_amount', sa.Float(), nullable=False), + sa.Column('currency', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('order_id') + ) + op.create_index(op.f('ix_mock_orders_product_id'), 'mock_orders', ['product_id'], unique=False) + op.create_index(op.f('ix_mock_orders_status'), 'mock_orders', ['status'], unique=False) + op.create_index(op.f('ix_mock_orders_user_id'), 'mock_orders', ['user_id'], unique=False) + op.create_table('model_configs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('provider', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('api_protocol', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('base_url', sa.Text(), nullable=True), + sa.Column('api_key_encrypted', sa.Text(), nullable=True), + sa.Column('model', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('temperature', sa.Float(), nullable=False), + sa.Column('max_output_tokens', sa.Integer(), nullable=False), + sa.Column('extra_body_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('protocol_options_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('legacy_unmapped_options_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('trust_status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('verified_at', sa.DateTime(), nullable=True), + sa.Column('verified_fingerprint', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('verification_attempt_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('verification_started_at', sa.DateTime(), nullable=True), + sa.Column('verification_attempt_status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('verification_attempt_error_code', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('config_revision', sa.Integer(), nullable=False), + sa.Column('security_revision', sa.Integer(), nullable=False), + sa.Column('key_revision', sa.Integer(), nullable=False), + sa.Column('is_default', sa.Boolean(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_model_configs_api_protocol'), 'model_configs', ['api_protocol'], unique=False) + op.create_index(op.f('ix_model_configs_tenant_id'), 'model_configs', ['tenant_id'], unique=False) + op.create_index(op.f('ix_model_configs_trust_status'), 'model_configs', ['trust_status'], unique=False) + op.create_index(op.f('ix_model_configs_verification_attempt_status'), 'model_configs', ['verification_attempt_status'], unique=False) + op.create_table('persona_configs', + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('system_prompt', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('tenant_id') + ) + op.create_table('scheduled_task_runs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('scheduled_task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('scheduled_for', sa.DateTime(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('finished_at', sa.DateTime(), nullable=True), + sa.Column('result_summary', sa.Text(), nullable=True), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('trace_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('scheduled_task_id', 'scheduled_for', name='uq_scheduled_task_run_due_time') + ) + op.create_index(op.f('ix_scheduled_task_runs_agent_id'), 'scheduled_task_runs', ['agent_id'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_finished_at'), 'scheduled_task_runs', ['finished_at'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_scheduled_for'), 'scheduled_task_runs', ['scheduled_for'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_scheduled_task_id'), 'scheduled_task_runs', ['scheduled_task_id'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_session_id'), 'scheduled_task_runs', ['session_id'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_started_at'), 'scheduled_task_runs', ['started_at'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_status'), 'scheduled_task_runs', ['status'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_tenant_id'), 'scheduled_task_runs', ['tenant_id'], unique=False) + op.create_index(op.f('ix_scheduled_task_runs_user_id'), 'scheduled_task_runs', ['user_id'], unique=False) + op.create_table('scheduled_tasks', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('prompt', sa.Text(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('schedule_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('schedule_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('timezone', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('rrule', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('concurrency_policy', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('misfire_policy', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('max_runs', sa.Integer(), nullable=True), + sa.Column('end_at', sa.DateTime(), nullable=True), + sa.Column('next_run_at', sa.DateTime(), nullable=True), + sa.Column('last_run_at', sa.DateTime(), nullable=True), + sa.Column('last_status', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('run_count', sa.Integer(), nullable=False), + sa.Column('lease_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('lease_until', sa.DateTime(), nullable=True), + sa.Column('source_session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('metadata_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_scheduled_tasks_agent_id'), 'scheduled_tasks', ['agent_id'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_concurrency_policy'), 'scheduled_tasks', ['concurrency_policy'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_created_by_user_id'), 'scheduled_tasks', ['created_by_user_id'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_end_at'), 'scheduled_tasks', ['end_at'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_last_run_at'), 'scheduled_tasks', ['last_run_at'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_last_status'), 'scheduled_tasks', ['last_status'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_lease_owner'), 'scheduled_tasks', ['lease_owner'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_lease_until'), 'scheduled_tasks', ['lease_until'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_misfire_policy'), 'scheduled_tasks', ['misfire_policy'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_next_run_at'), 'scheduled_tasks', ['next_run_at'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_schedule_type'), 'scheduled_tasks', ['schedule_type'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_source_session_id'), 'scheduled_tasks', ['source_session_id'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_status'), 'scheduled_tasks', ['status'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_tenant_id'), 'scheduled_tasks', ['tenant_id'], unique=False) + op.create_index(op.f('ix_scheduled_tasks_timezone'), 'scheduled_tasks', ['timezone'], unique=False) + op.create_table('sessions', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('active_skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('active_step_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('slots_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('skill_stack_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('pending_tasks_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('resume_after_answer_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('awaiting_input_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('knowledge_context_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('context_state_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('summary', sa.Text(), nullable=True), + sa.Column('last_agent_question', sa.Text(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('channel', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('external_conv_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('channel_target_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('channel_binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('channel_account_key', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_sessions_agent_id'), 'sessions', ['agent_id'], unique=False) + op.create_index(op.f('ix_sessions_channel_account_key'), 'sessions', ['channel_account_key'], unique=False) + op.create_index(op.f('ix_sessions_team_id'), 'sessions', ['team_id'], unique=False) + op.create_index(op.f('ix_sessions_tenant_id'), 'sessions', ['tenant_id'], unique=False) + op.create_index(op.f('ix_sessions_user_id'), 'sessions', ['user_id'], unique=False) + op.create_index('uq_sessions_agent_channel_extconv', 'sessions', ['agent_id', 'channel', 'channel_binding_id', 'external_conv_id'], unique=True) + op.create_table('skill_feedback', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_version', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('step_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('message_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('rating', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'message_id', 'user_id', name='uq_skill_feedback_message_user') + ) + op.create_index(op.f('ix_skill_feedback_message_id'), 'skill_feedback', ['message_id'], unique=False) + op.create_index(op.f('ix_skill_feedback_rating'), 'skill_feedback', ['rating'], unique=False) + op.create_index(op.f('ix_skill_feedback_session_id'), 'skill_feedback', ['session_id'], unique=False) + op.create_index(op.f('ix_skill_feedback_skill_id'), 'skill_feedback', ['skill_id'], unique=False) + op.create_index(op.f('ix_skill_feedback_skill_version'), 'skill_feedback', ['skill_version'], unique=False) + op.create_index(op.f('ix_skill_feedback_step_id'), 'skill_feedback', ['step_id'], unique=False) + op.create_index(op.f('ix_skill_feedback_tenant_id'), 'skill_feedback', ['tenant_id'], unique=False) + op.create_index(op.f('ix_skill_feedback_user_id'), 'skill_feedback', ['user_id'], unique=False) + op.create_table('skill_versions', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('business_domain', sa.Text(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('content_json', app.db.models.PortableJSON(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'skill_id', 'version', name='uq_skill_version') + ) + op.create_index(op.f('ix_skill_versions_skill_id'), 'skill_versions', ['skill_id'], unique=False) + op.create_index(op.f('ix_skill_versions_status'), 'skill_versions', ['status'], unique=False) + op.create_index(op.f('ix_skill_versions_tenant_id'), 'skill_versions', ['tenant_id'], unique=False) + op.create_index(op.f('ix_skill_versions_version'), 'skill_versions', ['version'], unique=False) + op.create_table('skills', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('skill_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('version', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('business_domain', sa.Text(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('content_json', app.db.models.PortableJSON(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'skill_id', name='uq_skill_tenant_skill_id') + ) + op.create_index(op.f('ix_skills_skill_id'), 'skills', ['skill_id'], unique=False) + op.create_index(op.f('ix_skills_status'), 'skills', ['status'], unique=False) + op.create_index(op.f('ix_skills_tenant_id'), 'skills', ['tenant_id'], unique=False) + op.create_table('team_blackboard_entries', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('tags_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('source_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('source_task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('citation_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('pinned', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_team_blackboard_entries_source_agent_id'), 'team_blackboard_entries', ['source_agent_id'], unique=False) + op.create_index(op.f('ix_team_blackboard_entries_source_task_id'), 'team_blackboard_entries', ['source_task_id'], unique=False) + op.create_index(op.f('ix_team_blackboard_entries_source_type'), 'team_blackboard_entries', ['source_type'], unique=False) + op.create_index(op.f('ix_team_blackboard_entries_status'), 'team_blackboard_entries', ['status'], unique=False) + op.create_index(op.f('ix_team_blackboard_entries_team_id'), 'team_blackboard_entries', ['team_id'], unique=False) + op.create_index(op.f('ix_team_blackboard_entries_tenant_id'), 'team_blackboard_entries', ['tenant_id'], unique=False) + op.create_table('team_members', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('role', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('team_id', 'agent_id', name='uq_team_member_agent') + ) + op.create_index(op.f('ix_team_members_agent_id'), 'team_members', ['agent_id'], unique=False) + op.create_index(op.f('ix_team_members_role'), 'team_members', ['role'], unique=False) + op.create_index(op.f('ix_team_members_team_id'), 'team_members', ['team_id'], unique=False) + op.create_table('team_runs', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tl_session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source_turn_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('synthesis_session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('final_message_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tl_session_id', 'source_turn_id', name='uq_team_run_tl_session_source_turn') + ) + op.create_index(op.f('ix_team_runs_created_by_user_id'), 'team_runs', ['created_by_user_id'], unique=False) + op.create_index(op.f('ix_team_runs_final_message_id'), 'team_runs', ['final_message_id'], unique=False) + op.create_index(op.f('ix_team_runs_source_turn_id'), 'team_runs', ['source_turn_id'], unique=False) + op.create_index(op.f('ix_team_runs_status'), 'team_runs', ['status'], unique=False) + op.create_index(op.f('ix_team_runs_synthesis_session_id'), 'team_runs', ['synthesis_session_id'], unique=False) + op.create_index(op.f('ix_team_runs_team_id'), 'team_runs', ['team_id'], unique=False) + op.create_index(op.f('ix_team_runs_tenant_id'), 'team_runs', ['tenant_id'], unique=False) + op.create_index(op.f('ix_team_runs_tl_session_id'), 'team_runs', ['tl_session_id'], unique=False) + op.create_table('team_task_bids', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('round', sa.Integer(), nullable=False), + sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('content', sa.Text(), nullable=True), + sa.Column('score', sa.Float(), nullable=True), + sa.Column('score_rationale', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('task_id', 'agent_id', 'round', 'kind', name='uq_team_task_bid_round') + ) + op.create_index(op.f('ix_team_task_bids_agent_id'), 'team_task_bids', ['agent_id'], unique=False) + op.create_index(op.f('ix_team_task_bids_kind'), 'team_task_bids', ['kind'], unique=False) + op.create_index(op.f('ix_team_task_bids_task_id'), 'team_task_bids', ['task_id'], unique=False) + op.create_index(op.f('ix_team_task_bids_team_id'), 'team_task_bids', ['team_id'], unique=False) + op.create_index(op.f('ix_team_task_bids_tenant_id'), 'team_task_bids', ['tenant_id'], unique=False) + op.create_table('team_task_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('actor_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('actor_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('event_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_team_task_events_actor_id'), 'team_task_events', ['actor_id'], unique=False) + op.create_index(op.f('ix_team_task_events_actor_type'), 'team_task_events', ['actor_type'], unique=False) + op.create_index(op.f('ix_team_task_events_event_type'), 'team_task_events', ['event_type'], unique=False) + op.create_index(op.f('ix_team_task_events_task_id'), 'team_task_events', ['task_id'], unique=False) + op.create_index(op.f('ix_team_task_events_team_id'), 'team_task_events', ['team_id'], unique=False) + op.create_table('team_tasks', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_run_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('source_turn_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('parent_task_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('title', sa.Text(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('priority', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_by_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('created_by_tl', sa.Boolean(), nullable=False), + sa.Column('assignee_agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('session_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('depends_on_task_ids_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('activation_condition_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('report_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('review_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_team_tasks_assignee_agent_id'), 'team_tasks', ['assignee_agent_id'], unique=False) + op.create_index(op.f('ix_team_tasks_created_by_user_id'), 'team_tasks', ['created_by_user_id'], unique=False) + op.create_index(op.f('ix_team_tasks_parent_task_id'), 'team_tasks', ['parent_task_id'], unique=False) + op.create_index(op.f('ix_team_tasks_priority'), 'team_tasks', ['priority'], unique=False) + op.create_index(op.f('ix_team_tasks_session_id'), 'team_tasks', ['session_id'], unique=False) + op.create_index(op.f('ix_team_tasks_source_turn_id'), 'team_tasks', ['source_turn_id'], unique=False) + op.create_index(op.f('ix_team_tasks_status'), 'team_tasks', ['status'], unique=False) + op.create_index(op.f('ix_team_tasks_team_id'), 'team_tasks', ['team_id'], unique=False) + op.create_index(op.f('ix_team_tasks_team_run_id'), 'team_tasks', ['team_run_id'], unique=False) + op.create_index(op.f('ix_team_tasks_tenant_id'), 'team_tasks', ['tenant_id'], unique=False) + op.create_table('team_wake_events', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('target_agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('trigger_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_team_wake_events_status'), 'team_wake_events', ['status'], unique=False) + op.create_index(op.f('ix_team_wake_events_target_agent_id'), 'team_wake_events', ['target_agent_id'], unique=False) + op.create_index(op.f('ix_team_wake_events_team_id'), 'team_wake_events', ['team_id'], unique=False) + op.create_index(op.f('ix_team_wake_events_tenant_id'), 'team_wake_events', ['tenant_id'], unique=False) + op.create_index(op.f('ix_team_wake_events_trigger_type'), 'team_wake_events', ['trigger_type'], unique=False) + op.create_table('teams', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('owner_user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('config_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'name', name='uq_team_tenant_name') + ) + op.create_index(op.f('ix_teams_owner_user_id'), 'teams', ['owner_user_id'], unique=False) + op.create_index(op.f('ix_teams_status'), 'teams', ['status'], unique=False) + op.create_index(op.f('ix_teams_tenant_id'), 'teams', ['tenant_id'], unique=False) + op.create_table('tenants', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('tools', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('display_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('bucket', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tool_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('method', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('url', sa.Text(), nullable=True), + sa.Column('headers_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('auth_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('config_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('input_schema', app.db.models.PortableJSON(), nullable=True), + sa.Column('output_schema', app.db.models.PortableJSON(), nullable=True), + sa.Column('allowed_skills_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('mcp_server_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('capability_scope', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('capability_scope_inherited', sa.Boolean(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'name', name='uq_tool_tenant_name') + ) + op.create_index(op.f('ix_tools_bucket'), 'tools', ['bucket'], unique=False) + op.create_index(op.f('ix_tools_capability_scope'), 'tools', ['capability_scope'], unique=False) + op.create_index(op.f('ix_tools_mcp_server_id'), 'tools', ['mcp_server_id'], unique=False) + op.create_index(op.f('ix_tools_name'), 'tools', ['name'], unique=False) + op.create_index(op.f('ix_tools_tenant_id'), 'tools', ['tenant_id'], unique=False) + op.create_index(op.f('ix_tools_tool_type'), 'tools', ['tool_type'], unique=False) + op.create_table('ui_configs', + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('show_thinking_trace', sa.Boolean(), nullable=False), + sa.Column('show_skill_trace', sa.Boolean(), nullable=False), + sa.Column('show_tool_trace', sa.Boolean(), nullable=False), + sa.Column('reflection_max_rounds', sa.Integer(), nullable=False), + sa.Column('agent_loop_max_actions', sa.Integer(), nullable=False), + sa.Column('context_token_budget', sa.Integer(), nullable=False), + sa.Column('context_compaction_trigger_ratio', sa.Float(), nullable=False), + sa.Column('context_recent_round_limit', sa.Integer(), nullable=False), + sa.Column('context_long_summary_token_budget', sa.Integer(), nullable=False), + sa.Column('context_medium_summary_token_budget', sa.Integer(), nullable=False), + sa.Column('context_allowed_roles', app.db.models.PortableJSON(), nullable=True), + sa.Column('context_long_summary_prefix', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('context_medium_summary_prefix', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sandbox_enabled', sa.Boolean(), nullable=False), + sa.Column('sandbox_network_mode', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sandbox_allowed_domains', app.db.models.PortableJSON(), nullable=True), + sa.Column('harness_storage_path', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('tenant_id') + ) + op.create_table('user_avatars', + sa.Column('user_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('data_url', sa.Text(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('user_id') + ) + op.create_table('users', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('display_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('role', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('source', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('password_hash', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('tenant_id', 'username', name='uq_user_tenant_username') + ) + op.create_index(op.f('ix_users_role'), 'users', ['role'], unique=False) + op.create_index(op.f('ix_users_source'), 'users', ['source'], unique=False) + op.create_index(op.f('ix_users_tenant_id'), 'users', ['tenant_id'], unique=False) + op.create_index('ix_users_tenant_id_display_name', 'users', ['tenant_id', 'display_name'], unique=False) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=False) + op.create_table('webhook_deliveries', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('endpoint_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('event_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('event_type', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('payload_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('delivery_owner', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('lease_expires_at', sa.DateTime(), nullable=True), + sa.Column('attempt_count', sa.Integer(), nullable=False), + sa.Column('next_attempt_at', sa.DateTime(), nullable=True), + sa.Column('last_status_code', sa.Integer(), nullable=True), + sa.Column('last_error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('delivered_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('endpoint_id', 'event_id', name='uq_webhook_delivery_event') + ) + op.create_index(op.f('ix_webhook_deliveries_delivery_owner'), 'webhook_deliveries', ['delivery_owner'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_endpoint_id'), 'webhook_deliveries', ['endpoint_id'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_event_id'), 'webhook_deliveries', ['event_id'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_event_type'), 'webhook_deliveries', ['event_type'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_lease_expires_at'), 'webhook_deliveries', ['lease_expires_at'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_next_attempt_at'), 'webhook_deliveries', ['next_attempt_at'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_status'), 'webhook_deliveries', ['status'], unique=False) + op.create_index(op.f('ix_webhook_deliveries_tenant_id'), 'webhook_deliveries', ['tenant_id'], unique=False) + op.create_table('webhook_endpoints', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('client_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('url', sa.Text(), nullable=True), + sa.Column('secret_encrypted', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('events_json', app.db.models.PortableJSON(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_webhook_endpoints_client_id'), 'webhook_endpoints', ['client_id'], unique=False) + op.create_index(op.f('ix_webhook_endpoints_status'), 'webhook_endpoints', ['status'], unique=False) + op.create_index(op.f('ix_webhook_endpoints_tenant_id'), 'webhook_endpoints', ['tenant_id'], unique=False) + op.create_table('wechat_kf_accounts', + sa.Column('id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('tenant_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('binding_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('open_kfid', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('agent_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('team_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('status', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('sync_cursor', sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column('last_error', sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column('last_sync_at', sa.DateTime(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('binding_id', 'open_kfid', name='uq_wechat_kf_account_binding_kfid'), + sa.UniqueConstraint('tenant_id', 'open_kfid', name='uq_wechat_kf_account_tenant_kfid') + ) + op.create_index(op.f('ix_wechat_kf_accounts_agent_id'), 'wechat_kf_accounts', ['agent_id'], unique=False) + op.create_index(op.f('ix_wechat_kf_accounts_binding_id'), 'wechat_kf_accounts', ['binding_id'], unique=False) + op.create_index(op.f('ix_wechat_kf_accounts_open_kfid'), 'wechat_kf_accounts', ['open_kfid'], unique=False) + op.create_index(op.f('ix_wechat_kf_accounts_status'), 'wechat_kf_accounts', ['status'], unique=False) + op.create_index(op.f('ix_wechat_kf_accounts_team_id'), 'wechat_kf_accounts', ['team_id'], unique=False) + op.create_index(op.f('ix_wechat_kf_accounts_tenant_id'), 'wechat_kf_accounts', ['tenant_id'], unique=False) + _create_partial_default_model_index() + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + _drop_partial_default_model_index() + op.drop_index(op.f('ix_wechat_kf_accounts_tenant_id'), table_name='wechat_kf_accounts') + op.drop_index(op.f('ix_wechat_kf_accounts_team_id'), table_name='wechat_kf_accounts') + op.drop_index(op.f('ix_wechat_kf_accounts_status'), table_name='wechat_kf_accounts') + op.drop_index(op.f('ix_wechat_kf_accounts_open_kfid'), table_name='wechat_kf_accounts') + op.drop_index(op.f('ix_wechat_kf_accounts_binding_id'), table_name='wechat_kf_accounts') + op.drop_index(op.f('ix_wechat_kf_accounts_agent_id'), table_name='wechat_kf_accounts') + op.drop_table('wechat_kf_accounts') + op.drop_index(op.f('ix_webhook_endpoints_tenant_id'), table_name='webhook_endpoints') + op.drop_index(op.f('ix_webhook_endpoints_status'), table_name='webhook_endpoints') + op.drop_index(op.f('ix_webhook_endpoints_client_id'), table_name='webhook_endpoints') + op.drop_table('webhook_endpoints') + op.drop_index(op.f('ix_webhook_deliveries_tenant_id'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_status'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_next_attempt_at'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_lease_expires_at'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_event_type'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_event_id'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_endpoint_id'), table_name='webhook_deliveries') + op.drop_index(op.f('ix_webhook_deliveries_delivery_owner'), table_name='webhook_deliveries') + op.drop_table('webhook_deliveries') + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_index('ix_users_tenant_id_display_name', table_name='users') + op.drop_index(op.f('ix_users_tenant_id'), table_name='users') + op.drop_index(op.f('ix_users_source'), table_name='users') + op.drop_index(op.f('ix_users_role'), table_name='users') + op.drop_table('users') + op.drop_table('user_avatars') + op.drop_table('ui_configs') + op.drop_index(op.f('ix_tools_tool_type'), table_name='tools') + op.drop_index(op.f('ix_tools_tenant_id'), table_name='tools') + op.drop_index(op.f('ix_tools_name'), table_name='tools') + op.drop_index(op.f('ix_tools_mcp_server_id'), table_name='tools') + op.drop_index(op.f('ix_tools_capability_scope'), table_name='tools') + op.drop_index(op.f('ix_tools_bucket'), table_name='tools') + op.drop_table('tools') + op.drop_table('tenants') + op.drop_index(op.f('ix_teams_tenant_id'), table_name='teams') + op.drop_index(op.f('ix_teams_status'), table_name='teams') + op.drop_index(op.f('ix_teams_owner_user_id'), table_name='teams') + op.drop_table('teams') + op.drop_index(op.f('ix_team_wake_events_trigger_type'), table_name='team_wake_events') + op.drop_index(op.f('ix_team_wake_events_tenant_id'), table_name='team_wake_events') + op.drop_index(op.f('ix_team_wake_events_team_id'), table_name='team_wake_events') + op.drop_index(op.f('ix_team_wake_events_target_agent_id'), table_name='team_wake_events') + op.drop_index(op.f('ix_team_wake_events_status'), table_name='team_wake_events') + op.drop_table('team_wake_events') + op.drop_index(op.f('ix_team_tasks_tenant_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_team_run_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_team_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_status'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_source_turn_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_session_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_priority'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_parent_task_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_created_by_user_id'), table_name='team_tasks') + op.drop_index(op.f('ix_team_tasks_assignee_agent_id'), table_name='team_tasks') + op.drop_table('team_tasks') + op.drop_index(op.f('ix_team_task_events_team_id'), table_name='team_task_events') + op.drop_index(op.f('ix_team_task_events_task_id'), table_name='team_task_events') + op.drop_index(op.f('ix_team_task_events_event_type'), table_name='team_task_events') + op.drop_index(op.f('ix_team_task_events_actor_type'), table_name='team_task_events') + op.drop_index(op.f('ix_team_task_events_actor_id'), table_name='team_task_events') + op.drop_table('team_task_events') + op.drop_index(op.f('ix_team_task_bids_tenant_id'), table_name='team_task_bids') + op.drop_index(op.f('ix_team_task_bids_team_id'), table_name='team_task_bids') + op.drop_index(op.f('ix_team_task_bids_task_id'), table_name='team_task_bids') + op.drop_index(op.f('ix_team_task_bids_kind'), table_name='team_task_bids') + op.drop_index(op.f('ix_team_task_bids_agent_id'), table_name='team_task_bids') + op.drop_table('team_task_bids') + op.drop_index(op.f('ix_team_runs_tl_session_id'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_tenant_id'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_team_id'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_synthesis_session_id'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_status'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_source_turn_id'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_final_message_id'), table_name='team_runs') + op.drop_index(op.f('ix_team_runs_created_by_user_id'), table_name='team_runs') + op.drop_table('team_runs') + op.drop_index(op.f('ix_team_members_team_id'), table_name='team_members') + op.drop_index(op.f('ix_team_members_role'), table_name='team_members') + op.drop_index(op.f('ix_team_members_agent_id'), table_name='team_members') + op.drop_table('team_members') + op.drop_index(op.f('ix_team_blackboard_entries_tenant_id'), table_name='team_blackboard_entries') + op.drop_index(op.f('ix_team_blackboard_entries_team_id'), table_name='team_blackboard_entries') + op.drop_index(op.f('ix_team_blackboard_entries_status'), table_name='team_blackboard_entries') + op.drop_index(op.f('ix_team_blackboard_entries_source_type'), table_name='team_blackboard_entries') + op.drop_index(op.f('ix_team_blackboard_entries_source_task_id'), table_name='team_blackboard_entries') + op.drop_index(op.f('ix_team_blackboard_entries_source_agent_id'), table_name='team_blackboard_entries') + op.drop_table('team_blackboard_entries') + op.drop_index(op.f('ix_skills_tenant_id'), table_name='skills') + op.drop_index(op.f('ix_skills_status'), table_name='skills') + op.drop_index(op.f('ix_skills_skill_id'), table_name='skills') + op.drop_table('skills') + op.drop_index(op.f('ix_skill_versions_version'), table_name='skill_versions') + op.drop_index(op.f('ix_skill_versions_tenant_id'), table_name='skill_versions') + op.drop_index(op.f('ix_skill_versions_status'), table_name='skill_versions') + op.drop_index(op.f('ix_skill_versions_skill_id'), table_name='skill_versions') + op.drop_table('skill_versions') + op.drop_index(op.f('ix_skill_feedback_user_id'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_tenant_id'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_step_id'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_skill_version'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_skill_id'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_session_id'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_rating'), table_name='skill_feedback') + op.drop_index(op.f('ix_skill_feedback_message_id'), table_name='skill_feedback') + op.drop_table('skill_feedback') + op.drop_index('uq_sessions_agent_channel_extconv', table_name='sessions') + op.drop_index(op.f('ix_sessions_user_id'), table_name='sessions') + op.drop_index(op.f('ix_sessions_tenant_id'), table_name='sessions') + op.drop_index(op.f('ix_sessions_team_id'), table_name='sessions') + op.drop_index(op.f('ix_sessions_channel_account_key'), table_name='sessions') + op.drop_index(op.f('ix_sessions_agent_id'), table_name='sessions') + op.drop_table('sessions') + op.drop_index(op.f('ix_scheduled_tasks_timezone'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_tenant_id'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_status'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_source_session_id'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_schedule_type'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_next_run_at'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_misfire_policy'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_lease_until'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_lease_owner'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_last_status'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_last_run_at'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_end_at'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_created_by_user_id'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_concurrency_policy'), table_name='scheduled_tasks') + op.drop_index(op.f('ix_scheduled_tasks_agent_id'), table_name='scheduled_tasks') + op.drop_table('scheduled_tasks') + op.drop_index(op.f('ix_scheduled_task_runs_user_id'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_tenant_id'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_status'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_started_at'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_session_id'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_scheduled_task_id'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_scheduled_for'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_finished_at'), table_name='scheduled_task_runs') + op.drop_index(op.f('ix_scheduled_task_runs_agent_id'), table_name='scheduled_task_runs') + op.drop_table('scheduled_task_runs') + op.drop_table('persona_configs') + op.drop_index(op.f('ix_model_configs_verification_attempt_status'), table_name='model_configs') + op.drop_index(op.f('ix_model_configs_trust_status'), table_name='model_configs') + op.drop_index(op.f('ix_model_configs_tenant_id'), table_name='model_configs') + op.drop_index(op.f('ix_model_configs_api_protocol'), table_name='model_configs') + op.drop_table('model_configs') + op.drop_index(op.f('ix_mock_orders_user_id'), table_name='mock_orders') + op.drop_index(op.f('ix_mock_orders_status'), table_name='mock_orders') + op.drop_index(op.f('ix_mock_orders_product_id'), table_name='mock_orders') + op.drop_table('mock_orders') + op.drop_index(op.f('ix_messages_tenant_id'), table_name='messages') + op.drop_index(op.f('ix_messages_session_id'), table_name='messages') + op.drop_table('messages') + op.drop_index(op.f('ix_message_feedback_user_id'), table_name='message_feedback') + op.drop_index(op.f('ix_message_feedback_tenant_id'), table_name='message_feedback') + op.drop_index(op.f('ix_message_feedback_session_id'), table_name='message_feedback') + op.drop_index(op.f('ix_message_feedback_rating'), table_name='message_feedback') + op.drop_index(op.f('ix_message_feedback_message_id'), table_name='message_feedback') + op.drop_index(op.f('ix_message_feedback_analysis_status'), table_name='message_feedback') + op.drop_index(op.f('ix_message_feedback_analysis_bucket'), table_name='message_feedback') + op.drop_table('message_feedback') + op.drop_index(op.f('ix_memories_username'), table_name='memories') + op.drop_index(op.f('ix_memories_user_id'), table_name='memories') + op.drop_index(op.f('ix_memories_tenant_id'), table_name='memories') + op.drop_index(op.f('ix_memories_session_id'), table_name='memories') + op.drop_index(op.f('ix_memories_kind'), table_name='memories') + op.drop_table('memories') + op.drop_index(op.f('ix_mcp_servers_transport'), table_name='mcp_servers') + op.drop_index(op.f('ix_mcp_servers_tenant_id'), table_name='mcp_servers') + op.drop_index(op.f('ix_mcp_servers_name'), table_name='mcp_servers') + op.drop_index(op.f('ix_mcp_servers_capability_scope'), table_name='mcp_servers') + op.drop_index(op.f('ix_mcp_servers_bucket'), table_name='mcp_servers') + op.drop_index(op.f('ix_mcp_servers_apps_mode'), table_name='mcp_servers') + op.drop_table('mcp_servers') + op.drop_index(op.f('ix_knowledge_ingest_jobs_tenant_id'), table_name='knowledge_ingest_jobs') + op.drop_index(op.f('ix_knowledge_ingest_jobs_status'), table_name='knowledge_ingest_jobs') + op.drop_index(op.f('ix_knowledge_ingest_jobs_knowledge_base_version_id'), table_name='knowledge_ingest_jobs') + op.drop_index(op.f('ix_knowledge_ingest_jobs_knowledge_base_id'), table_name='knowledge_ingest_jobs') + op.drop_index(op.f('ix_knowledge_ingest_jobs_document_id'), table_name='knowledge_ingest_jobs') + op.drop_table('knowledge_ingest_jobs') + op.drop_index(op.f('ix_knowledge_documents_tenant_id'), table_name='knowledge_documents') + op.drop_index(op.f('ix_knowledge_documents_status'), table_name='knowledge_documents') + op.drop_index(op.f('ix_knowledge_documents_knowledge_base_version_id'), table_name='knowledge_documents') + op.drop_index(op.f('ix_knowledge_documents_knowledge_base_id'), table_name='knowledge_documents') + op.drop_index(op.f('ix_knowledge_documents_file_type'), table_name='knowledge_documents') + op.drop_table('knowledge_documents') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_tenant_id'), table_name='knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_suggestion_type'), table_name='knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_status'), table_name='knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_knowledge_base_version_id'), table_name='knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_knowledge_base_id'), table_name='knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_document_id'), table_name='knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_discovery_suggestions_bucket_id'), table_name='knowledge_discovery_suggestions') + op.drop_table('knowledge_discovery_suggestions') + op.drop_index(op.f('ix_knowledge_concepts_tenant_id'), table_name='knowledge_concepts') + op.drop_index(op.f('ix_knowledge_concepts_status'), table_name='knowledge_concepts') + op.drop_index(op.f('ix_knowledge_concepts_knowledge_base_version_id'), table_name='knowledge_concepts') + op.drop_index(op.f('ix_knowledge_concepts_knowledge_base_id'), table_name='knowledge_concepts') + op.drop_index(op.f('ix_knowledge_concepts_document_id'), table_name='knowledge_concepts') + op.drop_index(op.f('ix_knowledge_concepts_concept_type'), table_name='knowledge_concepts') + op.drop_index(op.f('ix_knowledge_concepts_concept_id'), table_name='knowledge_concepts') + op.drop_table('knowledge_concepts') + op.drop_index(op.f('ix_knowledge_chunks_tenant_id'), table_name='knowledge_chunks') + op.drop_index(op.f('ix_knowledge_chunks_knowledge_base_version_id'), table_name='knowledge_chunks') + op.drop_index(op.f('ix_knowledge_chunks_knowledge_base_id'), table_name='knowledge_chunks') + op.drop_index(op.f('ix_knowledge_chunks_document_id'), table_name='knowledge_chunks') + op.drop_index(op.f('ix_knowledge_chunks_chunk_index'), table_name='knowledge_chunks') + op.drop_index(op.f('ix_knowledge_chunks_bucket_id'), table_name='knowledge_chunks') + op.drop_table('knowledge_chunks') + op.drop_index(op.f('ix_knowledge_buckets_tenant_id'), table_name='knowledge_buckets') + op.drop_index(op.f('ix_knowledge_buckets_knowledge_base_version_id'), table_name='knowledge_buckets') + op.drop_index(op.f('ix_knowledge_buckets_knowledge_base_id'), table_name='knowledge_buckets') + op.drop_index(op.f('ix_knowledge_buckets_document_id'), table_name='knowledge_buckets') + op.drop_index(op.f('ix_knowledge_buckets_bucket_key'), table_name='knowledge_buckets') + op.drop_table('knowledge_buckets') + op.drop_index(op.f('ix_knowledge_bases_tenant_id'), table_name='knowledge_bases') + op.drop_index(op.f('ix_knowledge_bases_status'), table_name='knowledge_bases') + op.drop_index(op.f('ix_knowledge_bases_capability_scope'), table_name='knowledge_bases') + op.drop_table('knowledge_bases') + op.drop_index(op.f('ix_knowledge_base_versions_version'), table_name='knowledge_base_versions') + op.drop_index(op.f('ix_knowledge_base_versions_tenant_id'), table_name='knowledge_base_versions') + op.drop_index(op.f('ix_knowledge_base_versions_status'), table_name='knowledge_base_versions') + op.drop_index(op.f('ix_knowledge_base_versions_knowledge_base_id'), table_name='knowledge_base_versions') + op.drop_index(op.f('ix_knowledge_base_versions_capability_scope'), table_name='knowledge_base_versions') + op.drop_table('knowledge_base_versions') + op.drop_index(op.f('ix_human_handoff_requests_trigger_step_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_trigger_skill_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_tenant_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_status'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_session_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_requester_user_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_notify_message_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_assignee_user_id'), table_name='human_handoff_requests') + op.drop_index(op.f('ix_human_handoff_requests_agent_id'), table_name='human_handoff_requests') + op.drop_table('human_handoff_requests') + op.drop_index(op.f('ix_harness_turns_user_message_id'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_tenant_id'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_status'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_session_id'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_request_digest'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_lease_owner'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_lease_expires_at'), table_name='harness_turns') + op.drop_index(op.f('ix_harness_turns_client_turn_id'), table_name='harness_turns') + op.drop_table('harness_turns') + op.drop_index(op.f('ix_harness_task_frames_tenant_id'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_task_id'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_step_id'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_status'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_source_turn_id'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_skill_id'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_session_id'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_lease_owner'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_lease_expires_at'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_kind'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_decision'), table_name='harness_task_frames') + op.drop_index(op.f('ix_harness_task_frames_agent_loop_id'), table_name='harness_task_frames') + op.drop_table('harness_task_frames') + op.drop_index(op.f('ix_harness_session_leases_tenant_id'), table_name='harness_session_leases') + op.drop_index(op.f('ix_harness_session_leases_session_id'), table_name='harness_session_leases') + op.drop_index(op.f('ix_harness_session_leases_lease_owner'), table_name='harness_session_leases') + op.drop_index(op.f('ix_harness_session_leases_lease_expires_at'), table_name='harness_session_leases') + op.drop_table('harness_session_leases') + op.drop_index(op.f('ix_harness_runs_tenant_id'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_task_id'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_task_frame_record_id'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_status'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_source_turn_id'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_session_id'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_lease_owner'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_lease_expires_at'), table_name='harness_runs') + op.drop_index(op.f('ix_harness_runs_agent_loop_id'), table_name='harness_runs') + op.drop_table('harness_runs') + op.drop_index(op.f('ix_harness_invocations_tool_name'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_tenant_id'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_task_id'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_status'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_session_id'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_run_id'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_request_digest'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_replayed_from_invocation_id'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_logical_action_key'), table_name='harness_invocations') + op.drop_index(op.f('ix_harness_invocations_call_id'), table_name='harness_invocations') + op.drop_table('harness_invocations') + op.drop_index(op.f('ix_harness_agent_loops_workspace_scope_id'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_tenant_id'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_status'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_skill_id'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_session_id'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_owner_task_frame_record_id'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_loop_key'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_last_run_id'), table_name='harness_agent_loops') + op.drop_index(op.f('ix_harness_agent_loops_kind'), table_name='harness_agent_loops') + op.drop_table('harness_agent_loops') + op.drop_index(op.f('ix_general_skills_tenant_id'), table_name='general_skills') + op.drop_index(op.f('ix_general_skills_status'), table_name='general_skills') + op.drop_index(op.f('ix_general_skills_slug'), table_name='general_skills') + op.drop_index(op.f('ix_general_skills_capability_scope'), table_name='general_skills') + op.drop_table('general_skills') + op.drop_index(op.f('ix_external_session_bindings_tenant_id'), table_name='external_session_bindings') + op.drop_index(op.f('ix_external_session_bindings_session_id'), table_name='external_session_bindings') + op.drop_index(op.f('ix_external_session_bindings_external_user_id'), table_name='external_session_bindings') + op.drop_index(op.f('ix_external_session_bindings_external_session_id'), table_name='external_session_bindings') + op.drop_index(op.f('ix_external_session_bindings_credential_id'), table_name='external_session_bindings') + op.drop_index(op.f('ix_external_session_bindings_agent_id'), table_name='external_session_bindings') + op.drop_table('external_session_bindings') + op.drop_index(op.f('ix_external_business_tasks_user_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_tool_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_tenant_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_task_frame_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_status'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_session_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_next_poll_at'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_lease_owner'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_lease_expires_at'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_invocation_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_idempotency_key'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_external_task_id'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_expires_at'), table_name='external_business_tasks') + op.drop_index(op.f('ix_external_business_tasks_agent_id'), table_name='external_business_tasks') + op.drop_table('external_business_tasks') + op.drop_index(op.f('ix_external_business_task_events_tenant_id'), table_name='external_business_task_events') + op.drop_index(op.f('ix_external_business_task_events_task_id'), table_name='external_business_task_events') + op.drop_index(op.f('ix_external_business_task_events_event_type'), table_name='external_business_task_events') + op.drop_index(op.f('ix_external_business_task_events_event_id'), table_name='external_business_task_events') + op.drop_table('external_business_task_events') + op.drop_index(op.f('ix_evolution_proposals_trigger_type'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_tenant_id'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_status'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_risk_level'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_reviewed_by_user_id'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_resource_type'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_resource_key'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_resource_id'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_created_by_user_id'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_base_version'), table_name='evolution_proposals') + op.drop_index(op.f('ix_evolution_proposals_agent_id'), table_name='evolution_proposals') + op.drop_table('evolution_proposals') + op.drop_table('distribution_install_records') + op.drop_index(op.f('ix_channel_inbound_events_tenant_id'), table_name='channel_inbound_events') + op.drop_index(op.f('ix_channel_inbound_events_status'), table_name='channel_inbound_events') + op.drop_index(op.f('ix_channel_inbound_events_reaction_id'), table_name='channel_inbound_events') + op.drop_index(op.f('ix_channel_inbound_events_processor_run_id'), table_name='channel_inbound_events') + op.drop_index(op.f('ix_channel_inbound_events_processor_lease_expires_at'), table_name='channel_inbound_events') + op.drop_index(op.f('ix_channel_inbound_events_channel'), table_name='channel_inbound_events') + op.drop_index('ix_channel_inbound_events_binding_status_created', table_name='channel_inbound_events') + op.drop_index(op.f('ix_channel_inbound_events_binding_id'), table_name='channel_inbound_events') + op.drop_table('channel_inbound_events') + op.drop_index(op.f('ix_channel_identities_tenant_id'), table_name='channel_identities') + op.drop_index(op.f('ix_channel_identities_staffdeck_user_id'), table_name='channel_identities') + op.drop_index(op.f('ix_channel_identities_external_account_scope'), table_name='channel_identities') + op.drop_index(op.f('ix_channel_identities_channel'), table_name='channel_identities') + op.drop_table('channel_identities') + op.drop_index(op.f('ix_channel_deliveries_tenant_id'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_status'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_session_id'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_next_attempt_at'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_message_id'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_kind'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_idempotency_key'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_delivery_owner'), table_name='channel_deliveries') + op.drop_index(op.f('ix_channel_deliveries_binding_id'), table_name='channel_deliveries') + op.drop_table('channel_deliveries') + op.drop_index(op.f('ix_channel_conv_states_tenant_id'), table_name='channel_conv_states') + op.drop_index(op.f('ix_channel_conv_states_binding_id'), table_name='channel_conv_states') + op.drop_table('channel_conv_states') + op.drop_index(op.f('ix_channel_bindings_tenant_id'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_team_id'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_status'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_provider_tenant_key'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_identity_scope_key'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_external_account_key'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_created_by_user_id'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_channel'), table_name='channel_bindings') + op.drop_index(op.f('ix_channel_bindings_agent_id'), table_name='channel_bindings') + op.drop_table('channel_bindings') + op.drop_index(op.f('ix_channel_binding_managers_user_id'), table_name='channel_binding_managers') + op.drop_index('ix_channel_binding_managers_tenant_user', table_name='channel_binding_managers') + op.drop_index(op.f('ix_channel_binding_managers_tenant_id'), table_name='channel_binding_managers') + op.drop_index(op.f('ix_channel_binding_managers_binding_id'), table_name='channel_binding_managers') + op.drop_table('channel_binding_managers') + op.drop_index(op.f('ix_channel_binding_agents_tenant_id'), table_name='channel_binding_agents') + op.drop_index(op.f('ix_channel_binding_agents_binding_id'), table_name='channel_binding_agents') + op.drop_index(op.f('ix_channel_binding_agents_agent_id'), table_name='channel_binding_agents') + op.drop_table('channel_binding_agents') + op.drop_index(op.f('ix_channel_bind_codes_user_id'), table_name='channel_bind_codes') + op.drop_index(op.f('ix_channel_bind_codes_tenant_id'), table_name='channel_bind_codes') + op.drop_index(op.f('ix_channel_bind_codes_code'), table_name='channel_bind_codes') + op.drop_table('channel_bind_codes') + op.drop_index(op.f('ix_api_sop_drafts_tenant_id'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_status'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_source'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_skill_id'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_etag'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_draft_version'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_created_by_credential_id'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_base_version'), table_name='api_sop_drafts') + op.drop_index(op.f('ix_api_sop_drafts_agent_id'), table_name='api_sop_drafts') + op.drop_table('api_sop_drafts') + op.drop_index(op.f('ix_api_jobs_tenant_id'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_status'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_stage'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_session_id'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_lease_expires_at'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_kind'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_execution_owner'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_credential_id'), table_name='api_jobs') + op.drop_index(op.f('ix_api_jobs_agent_id'), table_name='api_jobs') + op.drop_table('api_jobs') + op.drop_index(op.f('ix_api_job_events_tenant_id'), table_name='api_job_events') + op.drop_index(op.f('ix_api_job_events_sequence'), table_name='api_job_events') + op.drop_index(op.f('ix_api_job_events_job_id'), table_name='api_job_events') + op.drop_index(op.f('ix_api_job_events_event_type'), table_name='api_job_events') + op.drop_table('api_job_events') + op.drop_index(op.f('ix_api_idempotency_records_tenant_id'), table_name='api_idempotency_records') + op.drop_index(op.f('ix_api_idempotency_records_resource_id'), table_name='api_idempotency_records') + op.drop_index(op.f('ix_api_idempotency_records_idempotency_key'), table_name='api_idempotency_records') + op.drop_index(op.f('ix_api_idempotency_records_expires_at'), table_name='api_idempotency_records') + op.drop_index(op.f('ix_api_idempotency_records_credential_id'), table_name='api_idempotency_records') + op.drop_table('api_idempotency_records') + op.drop_index(op.f('ix_api_credentials_tenant_id'), table_name='api_credentials') + op.drop_index(op.f('ix_api_credentials_status'), table_name='api_credentials') + op.drop_index(op.f('ix_api_credentials_last_used_at'), table_name='api_credentials') + op.drop_index(op.f('ix_api_credentials_key_prefix'), table_name='api_credentials') + op.drop_index(op.f('ix_api_credentials_expires_at'), table_name='api_credentials') + op.drop_index(op.f('ix_api_credentials_client_id'), table_name='api_credentials') + op.drop_index(op.f('ix_api_credentials_agent_id'), table_name='api_credentials') + op.drop_table('api_credentials') + op.drop_index(op.f('ix_api_clients_tenant_id'), table_name='api_clients') + op.drop_index(op.f('ix_api_clients_status'), table_name='api_clients') + op.drop_index(op.f('ix_api_clients_created_by_user_id'), table_name='api_clients') + op.drop_table('api_clients') + op.drop_index(op.f('ix_api_audit_logs_tenant_id'), table_name='api_audit_logs') + op.drop_index(op.f('ix_api_audit_logs_status_code'), table_name='api_audit_logs') + op.drop_index(op.f('ix_api_audit_logs_resource_type'), table_name='api_audit_logs') + op.drop_index(op.f('ix_api_audit_logs_resource_id'), table_name='api_audit_logs') + op.drop_index(op.f('ix_api_audit_logs_request_id'), table_name='api_audit_logs') + op.drop_index(op.f('ix_api_audit_logs_credential_id'), table_name='api_audit_logs') + op.drop_table('api_audit_logs') + op.drop_index(op.f('ix_agent_usages_user_id'), table_name='agent_usages') + op.drop_index(op.f('ix_agent_usages_tenant_id'), table_name='agent_usages') + op.drop_index(op.f('ix_agent_usages_agent_id'), table_name='agent_usages') + op.drop_table('agent_usages') + op.drop_index(op.f('ix_agent_skill_branches_tenant_id'), table_name='agent_skill_branches') + op.drop_index(op.f('ix_agent_skill_branches_sync_state'), table_name='agent_skill_branches') + op.drop_index(op.f('ix_agent_skill_branches_status'), table_name='agent_skill_branches') + op.drop_index(op.f('ix_agent_skill_branches_source_skill_id'), table_name='agent_skill_branches') + op.drop_index(op.f('ix_agent_skill_branches_skill_id'), table_name='agent_skill_branches') + op.drop_index(op.f('ix_agent_skill_branches_agent_id'), table_name='agent_skill_branches') + op.drop_table('agent_skill_branches') + op.drop_index(op.f('ix_agent_skill_branch_versions_version'), table_name='agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_skill_branch_versions_tenant_id'), table_name='agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_skill_branch_versions_sync_state'), table_name='agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_skill_branch_versions_status'), table_name='agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_skill_branch_versions_source_skill_id'), table_name='agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_skill_branch_versions_skill_id'), table_name='agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_skill_branch_versions_agent_id'), table_name='agent_skill_branch_versions') + op.drop_table('agent_skill_branch_versions') + op.drop_index(op.f('ix_agent_resource_bindings_tenant_id'), table_name='agent_resource_bindings') + op.drop_index(op.f('ix_agent_resource_bindings_status'), table_name='agent_resource_bindings') + op.drop_index(op.f('ix_agent_resource_bindings_resource_type'), table_name='agent_resource_bindings') + op.drop_index(op.f('ix_agent_resource_bindings_resource_id'), table_name='agent_resource_bindings') + op.drop_index(op.f('ix_agent_resource_bindings_agent_id'), table_name='agent_resource_bindings') + op.drop_table('agent_resource_bindings') + op.drop_index(op.f('ix_agent_profiles_tenant_id'), table_name='agent_profiles') + op.drop_index(op.f('ix_agent_profiles_status'), table_name='agent_profiles') + op.drop_index(op.f('ix_agent_profiles_is_overall'), table_name='agent_profiles') + op.drop_table('agent_profiles') + op.drop_index(op.f('ix_agent_model_bindings_tenant_id'), table_name='agent_model_bindings') + op.drop_index(op.f('ix_agent_model_bindings_role'), table_name='agent_model_bindings') + op.drop_index(op.f('ix_agent_model_bindings_model_config_id'), table_name='agent_model_bindings') + op.drop_index(op.f('ix_agent_model_bindings_agent_id'), table_name='agent_model_bindings') + op.drop_table('agent_model_bindings') + op.drop_index(op.f('ix_agent_knowledge_branches_tenant_id'), table_name='agent_knowledge_branches') + op.drop_index(op.f('ix_agent_knowledge_branches_sync_state'), table_name='agent_knowledge_branches') + op.drop_index(op.f('ix_agent_knowledge_branches_status'), table_name='agent_knowledge_branches') + op.drop_index(op.f('ix_agent_knowledge_branches_knowledge_base_id'), table_name='agent_knowledge_branches') + op.drop_index(op.f('ix_agent_knowledge_branches_agent_id'), table_name='agent_knowledge_branches') + op.drop_table('agent_knowledge_branches') + op.drop_index(op.f('ix_agent_events_tenant_id'), table_name='agent_events') + op.drop_index(op.f('ix_agent_events_session_id'), table_name='agent_events') + op.drop_index(op.f('ix_agent_events_event_type'), table_name='agent_events') + op.drop_table('agent_events') + op.drop_index(op.f('ix_a2a_task_runs_tool_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_tenant_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_status'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_session_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_remote_task_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_last_event_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_invocation_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_direction'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_context_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_codex_session_id'), table_name='a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_runs_agent_id'), table_name='a2a_task_runs') + op.drop_table('a2a_task_runs') + op.drop_index(op.f('ix_a2a_task_events_tenant_id'), table_name='a2a_task_events') + op.drop_index(op.f('ix_a2a_task_events_sequence'), table_name='a2a_task_events') + op.drop_index(op.f('ix_a2a_task_events_run_id'), table_name='a2a_task_events') + op.drop_index(op.f('ix_a2a_task_events_external_event_id'), table_name='a2a_task_events') + op.drop_index(op.f('ix_a2a_task_events_event_type'), table_name='a2a_task_events') + op.drop_table('a2a_task_events') + # ### end Alembic commands ### diff --git a/backend/app/db/models.py b/backend/app/db/models.py index bebaaa794..f3b759ab8 100644 --- a/backend/app/db/models.py +++ b/backend/app/db/models.py @@ -1,10 +1,22 @@ from __future__ import annotations +import json from datetime import UTC, datetime from typing import Any, Optional from uuid import uuid4 -from sqlalchemy import JSON, Column, Index, Integer, UniqueConstraint +from sqlalchemy import ( + JSON, + Column, + DDL, + Index, + Integer, + Text, + TypeDecorator, + UniqueConstraint, + event, +) +from sqlalchemy.dialects.mysql import MEDIUMTEXT from sqlmodel import Field, SQLModel @@ -16,6 +28,33 @@ def new_id(prefix: str) -> str: return f"{prefix}_{uuid4().hex[:16]}" +class PortableJSON(TypeDecorator): + """JSON 列的可移植实现:sqlite/postgresql/mysql 用原生 JSON;Oracle/达梦系 + 无 JSON 类型,降级为 CLOB 存序列化文本(读出自动还原,Python 侧透明)。""" + + impl = JSON + cache_ok = True + + def load_dialect_impl(self, dialect): + if dialect.name in ("oracle", "dm"): + return dialect.type_descriptor(Text()) + return dialect.type_descriptor(JSON()) + + def process_bind_param(self, value, dialect): + if value is not None and dialect.name in ("oracle", "dm"): + return json.dumps(value, ensure_ascii=False) + return value + + def process_result_value(self, value, dialect): + if value is not None and dialect.name in ("oracle", "dm"): + return json.loads(value) + return value + + +# 头像等内联二进制数据:MySQL TEXT 只有 64KB,用 MEDIUMTEXT 容纳 <=2MB 图片 base64 +HugeText = Text().with_variant(MEDIUMTEXT(), "mysql") + + class Tenant(SQLModel, table=True): __tablename__ = "tenants" @@ -61,7 +100,7 @@ class UserAvatar(SQLModel, table=True): __tablename__ = "user_avatars" user_id: str = Field(primary_key=True) - data_url: str + data_url: str = Field(sa_column=Column(HugeText)) updated_at: datetime = Field(default_factory=utc_now) @@ -76,11 +115,11 @@ class APIClient(SQLModel, table=True): id: str = Field(default_factory=lambda: new_id("apiclient"), primary_key=True) tenant_id: str = Field(index=True) name: str - description: Optional[str] = None - scopes_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) + scopes_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) status: str = Field(default="active", index=True) created_by_user_id: Optional[str] = Field(default=None, index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -100,7 +139,7 @@ class APICredential(SQLModel, table=True): name: str key_prefix: str = Field(index=True) key_digest: str - scopes_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) + scopes_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) status: str = Field(default="active", index=True) expires_at: Optional[datetime] = Field(default=None, index=True) last_used_at: Optional[datetime] = Field(default=None, index=True) @@ -120,13 +159,13 @@ class APIIdempotencyRecord(SQLModel, table=True): id: str = Field(default_factory=lambda: new_id("apiidem"), primary_key=True) tenant_id: str = Field(index=True) - credential_id: str = Field(index=True) - method: str - path: str - idempotency_key: str = Field(index=True) + credential_id: str = Field(max_length=64, index=True) + method: str = Field(max_length=16) + path: str = Field(max_length=400) + idempotency_key: str = Field(max_length=200, index=True) request_hash: str status_code: int = 200 - response_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + response_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) resource_id: Optional[str] = Field(default=None, index=True) expires_at: datetime = Field(index=True) created_at: datetime = Field(default_factory=utc_now) @@ -144,9 +183,9 @@ class APIJob(SQLModel, table=True): status: str = Field(default="queued", index=True) stage: str = Field(default="queued", index=True) progress: float = 0.0 - request_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + request_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) cancel_requested: bool = False retryable: bool = False execution_owner: Optional[str] = Field(default=None, index=True) @@ -170,7 +209,7 @@ class APIJobEvent(SQLModel, table=True): job_id: str = Field(index=True) sequence: int = Field(index=True) event_type: str = Field(index=True) - data_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + data_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) public: bool = True created_at: datetime = Field(default_factory=utc_now) @@ -195,11 +234,11 @@ class A2ATaskRun(SQLModel, table=True): context_id: Optional[str] = Field(default=None, index=True) codex_session_id: Optional[str] = Field(default=None, index=True) status: str = Field(default="submitted", index=True) - request_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - artifacts_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - agent_card_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + request_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + artifacts_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + agent_card_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) last_event_id: Optional[str] = Field(default=None, index=True) cancel_requested: bool = False recovery_attempts: int = 0 @@ -221,7 +260,7 @@ class A2ATaskEvent(SQLModel, table=True): sequence: int = Field(index=True) external_event_id: Optional[str] = Field(default=None, index=True) event_type: str = Field(index=True) - data_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + data_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) @@ -240,23 +279,23 @@ class ExternalBusinessTask(SQLModel, table=True): ) id: str = Field(default_factory=lambda: new_id("exttask"), primary_key=True) - tenant_id: str = Field(index=True) - user_id: str = Field(index=True) + tenant_id: str = Field(max_length=64, index=True) + user_id: str = Field(max_length=64, index=True) agent_id: Optional[str] = Field(default=None, index=True) session_id: Optional[str] = Field(default=None, index=True) task_frame_id: Optional[str] = Field(default=None, index=True) resume_step_id: Optional[str] = None invocation_id: Optional[str] = Field(default=None, index=True) - tool_id: str = Field(index=True) - external_task_id: Optional[str] = Field(default=None, index=True) + tool_id: str = Field(max_length=64, index=True) + external_task_id: Optional[str] = Field(max_length=192, default=None, index=True) idempotency_key: Optional[str] = Field(default=None, unique=True, index=True) status: str = Field(default="submitting", index=True) - request_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + request_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) callback_token_hash: str status_url: Optional[str] = None - status_config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + status_config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) poll_interval_seconds: float = 5.0 next_poll_at: Optional[datetime] = Field(default=None, index=True) poll_attempts: int = 0 @@ -280,7 +319,7 @@ class ExternalBusinessTaskEvent(SQLModel, table=True): task_id: str = Field(index=True) event_id: str = Field(index=True) event_type: str = Field(index=True) - data_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + data_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) @@ -291,9 +330,9 @@ class WebhookEndpoint(SQLModel, table=True): tenant_id: str = Field(index=True) client_id: str = Field(index=True) name: str - url: str + url: str = Field(sa_column=Column(Text)) secret_encrypted: str - events_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) + events_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) status: str = Field(default="active", index=True) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -310,14 +349,14 @@ class WebhookDelivery(SQLModel, table=True): endpoint_id: str = Field(index=True) event_id: str = Field(index=True) event_type: str = Field(index=True) - payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) status: str = Field(default="queued", index=True) delivery_owner: Optional[str] = Field(default=None, index=True) lease_expires_at: Optional[datetime] = Field(default=None, index=True) attempt_count: int = 0 next_attempt_at: Optional[datetime] = Field(default=None, index=True) last_status_code: Optional[int] = None - last_error: Optional[str] = None + last_error: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) delivered_at: Optional[datetime] = None updated_at: datetime = Field(default_factory=utc_now) @@ -339,7 +378,7 @@ class ExternalSessionBinding(SQLModel, table=True): external_session_id: str = Field(index=True) external_user_id: Optional[str] = Field(default=None, index=True) session_id: str = Field(index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -353,11 +392,11 @@ class APISOPDraft(SQLModel, table=True): skill_id: str = Field(index=True) base_version: Optional[str] = Field(default=None, index=True) draft_version: str = Field(index=True) - content_json: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False)) + content_json: dict[str, Any] = Field(sa_column=Column(PortableJSON, nullable=False)) status: str = Field(default="draft", index=True) source: str = Field(default="structured", index=True) - warnings_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) - validation_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + warnings_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) + validation_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) etag: str = Field(index=True) created_by_credential_id: Optional[str] = Field(default=None, index=True) created_at: datetime = Field(default_factory=utc_now) @@ -390,9 +429,9 @@ class Skill(SQLModel, table=True): skill_id: str = Field(index=True) version: str = "1.0.0" name: str - business_domain: Optional[str] = None - description: Optional[str] = None - content_json: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False)) + business_domain: Optional[str] = Field(default=None, sa_column=Column(Text)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) + content_json: dict[str, Any] = Field(sa_column=Column(PortableJSON, nullable=False)) status: str = Field(default="draft", index=True) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -407,9 +446,9 @@ class SkillVersion(SQLModel, table=True): skill_id: str = Field(index=True) version: str = Field(index=True) name: str - business_domain: Optional[str] = None - description: Optional[str] = None - content_json: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False)) + business_domain: Optional[str] = Field(default=None, sa_column=Column(Text)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) + content_json: dict[str, Any] = Field(sa_column=Column(PortableJSON, nullable=False)) status: str = Field(default="draft", index=True) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -428,10 +467,10 @@ class AgentSkillBranch(SQLModel, table=True): source_skill_id: str = Field(index=True) base_version: str = "1.0.0" head_version: str = "1.0.0" - content_json: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False)) + content_json: dict[str, Any] = Field(sa_column=Column(PortableJSON, nullable=False)) status: str = Field(default="active", index=True) sync_state: str = Field(default="synced", index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -443,16 +482,16 @@ class AgentSkillBranchVersion(SQLModel, table=True): ) id: str = Field(default_factory=lambda: new_id("agentbranchver"), primary_key=True) - tenant_id: str = Field(index=True) - agent_id: str = Field(index=True) - skill_id: str = Field(index=True) + tenant_id: str = Field(max_length=64, index=True) + agent_id: str = Field(max_length=64, index=True) + skill_id: str = Field(max_length=64, index=True) source_skill_id: str = Field(index=True) - version: str = Field(index=True) + version: str = Field(max_length=32, index=True) base_version: str = "1.0.0" - content_json: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False)) + content_json: dict[str, Any] = Field(sa_column=Column(PortableJSON, nullable=False)) status: str = Field(default="active", index=True) sync_state: str = Field(default="diverged", index=True) - change_summary: Optional[str] = None + change_summary: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -465,15 +504,15 @@ class GeneralSkill(SQLModel, table=True): tenant_id: str = Field(index=True) slug: str = Field(index=True) name: str - description: Optional[str] = None - homepage: Optional[str] = None - skill_markdown: str - skill_files_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) + homepage: Optional[str] = Field(default=None, sa_column=Column(Text)) + skill_markdown: str = Field(sa_column=Column(Text)) + skill_files_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) status: str = Field(default="draft", index=True) capability_scope: str = Field(default="general", index=True) - permissions_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - runtime_config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + permissions_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + runtime_config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -485,10 +524,10 @@ class KnowledgeBase(SQLModel, table=True): id: str = Field(default_factory=lambda: new_id("kb"), primary_key=True) tenant_id: str = Field(index=True) name: str - description: Optional[str] = None + description: Optional[str] = Field(default=None, sa_column=Column(Text)) status: str = Field(default="active", index=True) capability_scope: str = Field(default="general", index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -504,10 +543,10 @@ class KnowledgeBaseVersion(SQLModel, table=True): knowledge_base_id: str = Field(index=True) version: str = Field(default="1.0.0", index=True) name: str - description: Optional[str] = None + description: Optional[str] = Field(default=None, sa_column=Column(Text)) status: str = Field(default="active", index=True) capability_scope: str = Field(default="general", index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -526,7 +565,7 @@ class AgentKnowledgeBranch(SQLModel, table=True): head_version: str = "1.0.0" status: str = Field(default="active", index=True) sync_state: str = Field(default="synced", index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -540,12 +579,12 @@ class KnowledgeDocument(SQLModel, table=True): knowledge_base_version_id: Optional[str] = Field(default=None, index=True) filename: str file_type: str = Field(index=True) - title: Optional[str] = None + title: Optional[str] = Field(default=None, sa_column=Column(Text)) status: str = Field(default="processing", index=True) bucket_count: int = 0 chunk_count: int = 0 - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - error: Optional[str] = None + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + error: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -559,10 +598,10 @@ class KnowledgeBucket(SQLModel, table=True): knowledge_base_version_id: Optional[str] = Field(default=None, index=True) document_id: str = Field(index=True) bucket_key: str = Field(index=True) - title: str - summary: str + title: str = Field(sa_column=Column(Text)) + summary: str = Field(sa_column=Column(Text)) token_estimate: int = 0 - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -577,10 +616,10 @@ class KnowledgeChunk(SQLModel, table=True): document_id: str = Field(index=True) bucket_id: str = Field(index=True) chunk_index: int = Field(index=True) - content: str - summary: Optional[str] = None + content: str = Field(sa_column=Column(Text)) + summary: Optional[str] = Field(default=None, sa_column=Column(Text)) source_ref: Optional[str] = None - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -603,13 +642,13 @@ class KnowledgeConcept(SQLModel, table=True): document_id: Optional[str] = Field(default=None, index=True) concept_id: str = Field(index=True) concept_type: str = Field(index=True) - title: str - description: Optional[str] = None - content_md: str - frontmatter_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - links_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - citations_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - source_refs_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) + title: str = Field(sa_column=Column(Text)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) + content_md: str = Field(sa_column=Column(Text)) + frontmatter_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + links_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + citations_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + source_refs_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) status: str = Field(default="active", index=True) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -625,11 +664,11 @@ class KnowledgeDiscoverySuggestion(SQLModel, table=True): document_id: str = Field(index=True) bucket_id: Optional[str] = Field(default=None, index=True) suggestion_type: str = Field(index=True) - title: str + title: str = Field(sa_column=Column(Text)) status: str = Field(default="pending", index=True) - payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - source_refs_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - reason: Optional[str] = None + payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + source_refs_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + reason: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -646,8 +685,8 @@ class KnowledgeIngestJob(SQLModel, table=True): status: str = Field(default="queued", index=True) stage: str = "queued" progress: float = 0.0 - error: Optional[str] = None - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + error: Optional[str] = Field(default=None, sa_column=Column(Text)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) started_at: Optional[datetime] = None finished_at: Optional[datetime] = None @@ -662,15 +701,15 @@ class ModelConfig(SQLModel, table=True): name: str provider: str = "openai_compatible" api_protocol: str = Field(default="openai_chat_completions", index=True) - base_url: Optional[str] = None - api_key_encrypted: str + base_url: Optional[str] = Field(default=None, sa_column=Column(Text)) + api_key_encrypted: str = Field(sa_column=Column(Text)) model: str temperature: float = 0.2 max_output_tokens: int = 8192 - extra_body_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - protocol_options_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + extra_body_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + protocol_options_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) legacy_unmapped_options_json: dict[str, Any] = Field( - default_factory=dict, sa_column=Column(JSON) + default_factory=dict, sa_column=Column(PortableJSON) ) trust_status: str = Field(default="unverified", index=True) verified_at: Optional[datetime] = None @@ -688,11 +727,33 @@ class ModelConfig(SQLModel, table=True): updated_at: datetime = Field(default_factory=utc_now) +# 每租户至多一条默认模型:部分唯一索引只按方言显式创建(SQLite=1 字面量,PG=布尔)。 +# 不把该索引挂在 metadata 上:sqlite_where/postgresql_where 在其它方言下会被静默 +# 丢弃,退化为全量唯一索引(MySQL/达梦下变成"每租户仅一条模型配置");不支持 +# 部分索引的后端由 init_db 的启动校验兜底(见 database.py)。 +event.listen( + ModelConfig.__table__, + "after_create", + DDL( + "CREATE UNIQUE INDEX uq_model_configs_tenant_default " + "ON model_configs (tenant_id) WHERE is_default = 1" + ).execute_if(dialect="sqlite"), +) +event.listen( + ModelConfig.__table__, + "after_create", + DDL( + "CREATE UNIQUE INDEX uq_model_configs_tenant_default " + "ON model_configs (tenant_id) WHERE is_default" + ).execute_if(dialect="postgresql"), +) + + class PersonaConfig(SQLModel, table=True): __tablename__ = "persona_configs" tenant_id: str = Field(primary_key=True) - system_prompt: str + system_prompt: str = Field(sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -713,14 +774,14 @@ class UIConfig(SQLModel, table=True): context_medium_summary_token_budget: int = 4_000 context_allowed_roles: list[str] = Field( default_factory=lambda: ["user", "assistant"], - sa_column=Column(JSON), + sa_column=Column(PortableJSON), ) context_long_summary_prefix: str = "历史的信息可以被总结为:" context_medium_summary_prefix: str = "近期的历史信息总结为:" sandbox_enabled: bool = False sandbox_network_mode: str = Field(default="all") - sandbox_allowed_domains: list[str] = Field(default_factory=list, sa_column=Column(JSON)) - harness_storage_path: Optional[str] = None + sandbox_allowed_domains: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) + harness_storage_path: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -732,12 +793,12 @@ class AgentProfile(SQLModel, table=True): id: str = Field(default_factory=lambda: new_id("agent"), primary_key=True) tenant_id: str = Field(index=True) name: str - description: Optional[str] = None - persona_prompt: Optional[str] = None + description: Optional[str] = Field(default=None, sa_column=Column(Text)) + persona_prompt: Optional[str] = Field(default=None, sa_column=Column(Text)) is_overall: bool = Field(default=False, index=True) status: str = Field(default="active", index=True) harness_max_actions: int = Field(default=32) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -752,7 +813,7 @@ class AgentUsage(SQLModel, table=True): tenant_id: str = Field(index=True) user_id: str = Field(index=True) agent_id: str = Field(index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -779,12 +840,12 @@ class AgentResourceBinding(SQLModel, table=True): ) id: str = Field(default_factory=lambda: new_id("agentres"), primary_key=True) - tenant_id: str = Field(index=True) - agent_id: str = Field(index=True) - resource_type: str = Field(index=True) - resource_id: str = Field(index=True) + tenant_id: str = Field(max_length=64, index=True) + agent_id: str = Field(max_length=64, index=True) + resource_type: str = Field(max_length=64, index=True) + resource_id: str = Field(max_length=192, index=True) status: str = Field(default="active", index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -797,17 +858,17 @@ class Tool(SQLModel, table=True): tenant_id: str = Field(index=True) name: str = Field(index=True) display_name: Optional[str] = None - description: Optional[str] = None + description: Optional[str] = Field(default=None, sa_column=Column(Text)) bucket: str = Field(default="未分桶", index=True) tool_type: str = Field(default="http", index=True) method: str - url: str - headers_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - auth_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - input_schema: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - output_schema: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - allowed_skills_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) + url: str = Field(sa_column=Column(Text)) + headers_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + auth_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + input_schema: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + output_schema: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + allowed_skills_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) mcp_server_id: Optional[str] = Field(default=None, index=True) capability_scope: str = Field(default="general", index=True) capability_scope_inherited: bool = True @@ -824,26 +885,26 @@ class MCPServer(SQLModel, table=True): tenant_id: str = Field(index=True) name: str = Field(index=True) display_name: Optional[str] = None - description: Optional[str] = None + description: Optional[str] = Field(default=None, sa_column=Column(Text)) bucket: str = Field(default="MCP 工具", index=True) # 连接方式:stdio / streamable_http / sse / builtin transport: str = Field(default="streamable_http", index=True) # streamable_http / sse 使用 - url: Optional[str] = None - headers_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + url: Optional[str] = Field(default=None, sa_column=Column(Text)) + headers_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # stdio 使用 - command: Optional[str] = None - args_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) - env_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - cwd: Optional[str] = None + command: Optional[str] = Field(default=None, sa_column=Column(Text)) + args_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) + env_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + cwd: Optional[str] = Field(default=None, sa_column=Column(Text)) # MCP Apps is opt-in so legacy standard MCP servers retain identical behavior. apps_mode: str = Field(default="disabled", index=True) negotiated_capabilities_json: dict[str, Any] = Field( default_factory=dict, - sa_column=Column(JSON), + sa_column=Column(PortableJSON), ) # 最近一次发现的原始工具定义(预览/审计用) - discovered_tools_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) + discovered_tools_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) last_synced_at: Optional[datetime] = None capability_scope: str = Field(default="general", index=True) enabled: bool = True @@ -866,36 +927,48 @@ class MockOrder(SQLModel, table=True): refundable: bool = True total_amount: float = 0.0 currency: str = "CNY" - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) class ChatSession(SQLModel, table=True): __tablename__ = "sessions" + __table_args__ = ( + # SQLite/PG 唯一索引中 NULL 互不相等,web 会话(channel 为空)不受约束; + # 含 channel_binding_id 以隔离同企业多 Bot(与 SQLite 迁移中的同名索引一致) + Index( + "uq_sessions_agent_channel_extconv", + "agent_id", + "channel", + "channel_binding_id", + "external_conv_id", + unique=True, + ), + ) id: str = Field(primary_key=True) tenant_id: str = Field(index=True) user_id: Optional[str] = Field(default=None, index=True) - agent_id: Optional[str] = Field(default=None, index=True) - title: Optional[str] = None + agent_id: Optional[str] = Field(max_length=64, default=None, index=True) + title: Optional[str] = Field(default=None, sa_column=Column(Text)) active_skill_id: Optional[str] = None active_step_id: Optional[str] = None - slots_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - skill_stack_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - pending_tasks_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - resume_after_answer_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) - awaiting_input_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) - knowledge_context_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - context_state_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - summary: Optional[str] = None - last_agent_question: Optional[str] = None + slots_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + skill_stack_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + pending_tasks_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + resume_after_answer_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(PortableJSON)) + awaiting_input_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(PortableJSON)) + knowledge_context_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + context_state_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + summary: Optional[str] = Field(default=None, sa_column=Column(Text)) + last_agent_question: Optional[str] = Field(default=None, sa_column=Column(Text)) status: str = "active" - channel: Optional[str] = None - external_conv_id: Optional[str] = None - channel_target_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) + channel: Optional[str] = Field(default=None, max_length=32) + external_conv_id: Optional[str] = Field(default=None, max_length=192) + channel_target_json: Optional[dict[str, Any]] = Field(default=None, sa_column=Column(PortableJSON)) # 渠道会话直挂绑定:出站 staging 优先按它直查,不再靠 (agent_id, channel) 反查 - channel_binding_id: Optional[str] = None + channel_binding_id: Optional[str] = Field(default=None, max_length=64) # 渠道外部账号稳定键:绑定删除后仍保留,仅允许同一外部 Bot 精确认领历史会话 channel_account_key: Optional[str] = Field(default=None, index=True) # 团队会话挂接:非空表示该会话属于某团队(TL 对话/任务执行等) @@ -919,9 +992,9 @@ class ChannelBinding(SQLModel, table=True): # pending/active/expired/disabled status: str = Field(default="pending", index=True) # Fernet 加密后的渠道凭证(如微信 bot_token),绝不回传明文 - credentials_enc: Optional[str] = None + credentials_enc: Optional[str] = Field(default=None, sa_column=Column(Text)) # ilink_bot_id、baseurl、get_updates_buf 游标、session_expired、bound_at 等 - config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # provider 侧 Bot 的稳定连接键,全部署唯一;pending 绑定激活前允许为空 external_account_key: Optional[str] = Field(default=None, unique=True, index=True) # 身份作用域稳定键:企微为 corp_id,微信为空字符串 @@ -1057,11 +1130,11 @@ class ChannelIdentity(SQLModel, table=True): ) id: str = Field(default_factory=lambda: new_id("chident"), primary_key=True) - tenant_id: str = Field(index=True) - channel: str = Field(index=True) + tenant_id: str = Field(max_length=64, index=True) + channel: str = Field(max_length=32, index=True) # 渠道账号作用域:wechat 置空(全局 wxid);wecom 取 corp_id/bot_id/binding.id,隔离跨企业身份 - external_account_scope: str = Field(default="", index=True) - external_user_id: str + external_account_scope: str = Field(max_length=64, default="", index=True) + external_user_id: str = Field(max_length=192) staffdeck_user_id: str = Field(index=True) display_name: Optional[str] = None created_at: datetime = Field(default_factory=utc_now) @@ -1085,7 +1158,7 @@ class ChannelInboundEvent(SQLModel, table=True): binding_id: str = Field(index=True) channel: str = Field(index=True) event_id: str - payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # 入站时的绑定配置代次,仅用于 ingress 代际审计;已落库事件不因后续轮换失效 config_revision: int = Field( default=0, @@ -1094,7 +1167,10 @@ class ChannelInboundEvent(SQLModel, table=True): # 每条事件不可变的回复目标;异步处理不得读取会话上的可变 target target_json: dict[str, Any] = Field( default_factory=dict, - sa_column=Column(JSON, nullable=False, server_default="{}"), + # server_default 不用于 JSON 列:MySQL 不允许 JSON 字面量默认值(1101); + # SQLite 存量库由 _migrate_sqlite_skill_schema 的 ALTER ... DEFAULT '{}' 兜底, + # 新库由 default_factory 保证 ORM 写入,故不在 DDL 层声明默认值。 + sa_column=Column(PortableJSON, nullable=False), ) # 收到确认标记的句柄;最终回复送达后据此异步撤回。飞书存远端 reaction_id; # 钉钉 emotion 接口不返回 ID,存本地哨兵值表示"已挂上待撤回"。 @@ -1104,7 +1180,7 @@ class ChannelInboundEvent(SQLModel, table=True): # 创建/接管该事件的进程启动代次;当前代次仍在运行时禁止按墙钟误接管。 processor_run_id: Optional[str] = Field(default=None, index=True) processor_lease_expires_at: Optional[datetime] = Field(default=None, index=True) - error: Optional[str] = None + error: Optional[str] = Field(default=None, sa_column=Column(Text)) processed_at: Optional[datetime] = None created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1119,10 +1195,10 @@ class ChannelDelivery(SQLModel, table=True): session_id: str = Field(index=True) message_id: Optional[str] = Field(default=None, index=True) # 投递目标:to_user_id + context_token - target_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + target_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # reply/error_notice kind: str = Field(default="reply", index=True) - text: str + text: str = Field(sa_column=Column(Text)) # pending/sending/delivered/failed status: str = Field(default="pending", index=True) attempts: int = 0 @@ -1135,7 +1211,7 @@ class ChannelDelivery(SQLModel, table=True): default=0, sa_column=Column(Integer, nullable=False, server_default="0"), ) - last_error: Optional[str] = None + last_error: Optional[str] = Field(default=None, sa_column=Column(Text)) # 回复类投递 = message_id,天然幂等 idempotency_key: str = Field(unique=True, index=True) # 第一次真正尝试远端发送的时间,用于飞书 UUID 一小时去重窗口 @@ -1156,12 +1232,12 @@ class HumanHandoffRequest(SQLModel, table=True): assignee_user_id: Optional[str] = Field(default=None, index=True) trigger_skill_id: Optional[str] = Field(default=None, index=True) trigger_step_id: Optional[str] = Field(default=None, index=True) - context_summary: Optional[str] = None - pending_question: Optional[str] = None + context_summary: Optional[str] = Field(default=None, sa_column=Column(Text)) + pending_question: Optional[str] = Field(default=None, sa_column=Column(Text)) status: str = Field(default="pending", index=True) - human_reply: Optional[str] = None - resume_payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + human_reply: Optional[str] = Field(default=None, sa_column=Column(Text)) + resume_payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) answered_at: Optional[datetime] = None @@ -1177,11 +1253,11 @@ class ScheduledTask(SQLModel, table=True): tenant_id: str = Field(index=True) agent_id: str = Field(index=True) created_by_user_id: str = Field(index=True) - title: str - prompt: str - description: Optional[str] = None + title: str = Field(sa_column=Column(Text)) + prompt: str = Field(sa_column=Column(Text)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) schedule_type: str = Field(default="daily", index=True) - schedule_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + schedule_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) timezone: str = Field(default="Asia/Shanghai", index=True) rrule: Optional[str] = None status: str = Field(default="active", index=True) @@ -1196,7 +1272,7 @@ class ScheduledTask(SQLModel, table=True): lease_owner: Optional[str] = Field(default=None, index=True) lease_until: Optional[datetime] = Field(default=None, index=True) source_session_id: Optional[str] = Field(default=None, index=True) - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1217,9 +1293,9 @@ class ScheduledTaskRun(SQLModel, table=True): status: str = Field(default="queued", index=True) started_at: Optional[datetime] = Field(default=None, index=True) finished_at: Optional[datetime] = Field(default=None, index=True) - result_summary: Optional[str] = None - error: Optional[str] = None - trace_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + result_summary: Optional[str] = Field(default=None, sa_column=Column(Text)) + error: Optional[str] = Field(default=None, sa_column=Column(Text)) + trace_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1243,7 +1319,7 @@ class HarnessAgentLoopRecord(SQLModel, table=True): owner_task_frame_record_id: Optional[str] = Field(default=None, index=True) skill_id: Optional[str] = Field(default=None, index=True) workspace_scope_id: Optional[str] = Field(default=None, index=True) - checkpoint_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + checkpoint_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) last_run_id: Optional[str] = Field(default=None, index=True) state_version: int = 1 created_at: datetime = Field(default_factory=utc_now) @@ -1273,15 +1349,15 @@ class HarnessTaskFrameRecord(SQLModel, table=True): sequence: int = 0 skill_id: Optional[str] = Field(default=None, index=True) step_id: Optional[str] = Field(default=None, index=True) - user_intent: Optional[str] = None - requirements_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) - slots_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - depends_on_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) + user_intent: Optional[str] = Field(default=None, sa_column=Column(Text)) + requirements_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) + slots_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + depends_on_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) task_requirement_json: dict[str, Any] = Field( - default_factory=dict, sa_column=Column(JSON) + default_factory=dict, sa_column=Column(PortableJSON) ) - result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + error_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) state_version: int = 1 attempt_no: int = 0 lease_owner: Optional[str] = Field(default=None, index=True) @@ -1306,12 +1382,12 @@ class HarnessRunRecord(SQLModel, table=True): lease_expires_at: Optional[datetime] = Field(default=None, index=True) action_count: int = 0 task_requirement_json: dict[str, Any] = Field( - default_factory=dict, sa_column=Column(JSON) + default_factory=dict, sa_column=Column(PortableJSON) ) capability_snapshot_json: dict[str, Any] = Field( - default_factory=dict, sa_column=Column(JSON) + default_factory=dict, sa_column=Column(PortableJSON) ) - result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) started_at: datetime = Field(default_factory=utc_now) finished_at: Optional[datetime] = None created_at: datetime = Field(default_factory=utc_now) @@ -1342,11 +1418,11 @@ class HarnessTurnRecord(SQLModel, table=True): user_message_id: Optional[str] = Field(default=None, index=True) response_json: dict[str, Any] = Field( default_factory=dict, - sa_column=Column(JSON), + sa_column=Column(PortableJSON), ) error_json: dict[str, Any] = Field( default_factory=dict, - sa_column=Column(JSON), + sa_column=Column(PortableJSON), ) started_at: datetime = Field(default_factory=utc_now) finished_at: Optional[datetime] = None @@ -1398,13 +1474,13 @@ class HarnessInvocationRecord(SQLModel, table=True): ) replayed_from_invocation_id: Optional[str] = Field(default=None, index=True) status: str = Field(default="started", index=True) - arguments_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + arguments_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + result_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) response_cache_json: dict[str, Any] = Field( default_factory=dict, - sa_column=Column(JSON), + sa_column=Column(PortableJSON), ) - approval_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + approval_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) started_at: datetime = Field(default_factory=utc_now) finished_at: Optional[datetime] = None created_at: datetime = Field(default_factory=utc_now) @@ -1418,8 +1494,8 @@ class Message(SQLModel, table=True): tenant_id: str = Field(index=True) session_id: str = Field(index=True) role: str - content: str - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + content: str = Field(sa_column=Column(Text)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) @@ -1435,10 +1511,10 @@ class MessageFeedback(SQLModel, table=True): rating: str = Field(index=True) analysis_status: str = Field(default="pending", index=True) analysis_bucket: Optional[str] = Field(default=None, index=True) - analysis_reason: Optional[str] = None - analysis_summary: Optional[str] = None + analysis_reason: Optional[str] = Field(default=None, sa_column=Column(Text)) + analysis_summary: Optional[str] = Field(default=None, sa_column=Column(Text)) analysis_confidence: Optional[float] = None - analysis_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + analysis_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) analyzed_at: Optional[datetime] = None created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1476,15 +1552,15 @@ class EvolutionProposal(SQLModel, table=True): trigger_type: str = Field(default="feedback", index=True) risk_level: str = Field(default="medium", index=True) hypothesis: str = "" - rationale: str = "" + rationale: str = Field(default="", sa_column=Column(Text)) expected_outcome: str = "" - source_feedback_ids_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) - evidence_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - candidate_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - diff_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(JSON)) - evaluation_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - published_snapshot_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - error: Optional[str] = None + source_feedback_ids_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) + evidence_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + candidate_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + diff_json: list[dict[str, Any]] = Field(default_factory=list, sa_column=Column(PortableJSON)) + evaluation_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + published_snapshot_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + error: Optional[str] = Field(default=None, sa_column=Column(Text)) created_by_user_id: str = Field(index=True) reviewed_by_user_id: Optional[str] = Field(default=None, index=True) created_at: datetime = Field(default_factory=utc_now) @@ -1501,7 +1577,7 @@ class AgentEvent(SQLModel, table=True): tenant_id: str = Field(index=True) session_id: str = Field(index=True) event_type: str = Field(index=True) - payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) @@ -1514,9 +1590,9 @@ class MemoryRecord(SQLModel, table=True): username: Optional[str] = Field(default=None, index=True) session_id: Optional[str] = Field(default=None, index=True) kind: str = Field(default="conversation", index=True) - content: str + content: str = Field(sa_column=Column(Text)) importance: float = 0.5 - metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + metadata_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1530,10 +1606,10 @@ class Team(SQLModel, table=True): id: str = Field(default_factory=lambda: new_id("team"), primary_key=True) tenant_id: str = Field(index=True) name: str - description: Optional[str] = None + description: Optional[str] = Field(default=None, sa_column=Column(Text)) owner_user_id: str = Field(index=True) # 预留:并发策略/竞标等团队级配置 - config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + config_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) status: str = Field(default="active", index=True) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1573,7 +1649,7 @@ class TeamRun(SQLModel, table=True): status: str = Field(default="planning", index=True) synthesis_session_id: Optional[str] = Field(default=None, index=True) final_message_id: Optional[str] = Field(default=None, index=True) - error: Optional[str] = None + error: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) completed_at: Optional[datetime] = None @@ -1593,18 +1669,18 @@ class TeamTask(SQLModel, table=True): team_run_id: Optional[str] = Field(default=None, index=True) source_turn_id: Optional[str] = Field(default=None, index=True) parent_task_id: Optional[str] = Field(default=None, index=True) - title: str - description: Optional[str] = None + title: str = Field(sa_column=Column(Text)) + description: Optional[str] = Field(default=None, sa_column=Column(Text)) priority: str = Field(default="normal", index=True) status: str = Field(default="pending", index=True) created_by_user_id: Optional[str] = Field(default=None, index=True) created_by_tl: bool = False assignee_agent_id: Optional[str] = Field(default=None, index=True) session_id: Optional[str] = Field(default=None, index=True) - depends_on_task_ids_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) - activation_condition_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - report_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) - review_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + depends_on_task_ids_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) + activation_condition_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + report_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) + review_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # 乐观锁版本号,人改判/验收并发时防覆盖 version: int = 0 created_at: datetime = Field(default_factory=utc_now) @@ -1623,7 +1699,7 @@ class TeamTaskEvent(SQLModel, table=True): actor_type: str = Field(index=True) actor_id: Optional[str] = Field(default=None, index=True) event_type: str = Field(index=True) - payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) created_at: datetime = Field(default_factory=utc_now) @@ -1638,10 +1714,10 @@ class TeamWakeEvent(SQLModel, table=True): target_agent_id: str = Field(index=True) # trigger_type: task_assigned / task_report / task_rework / tl_message 等 trigger_type: str = Field(index=True) - payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + payload_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # status: pending -> claimed -> done / failed status: str = Field(default="pending", index=True) - error: Optional[str] = None + error: Optional[str] = Field(default=None, sa_column=Column(Text)) created_at: datetime = Field(default_factory=utc_now) updated_at: datetime = Field(default_factory=utc_now) @@ -1654,14 +1730,14 @@ class TeamBlackboardEntry(SQLModel, table=True): id: str = Field(default_factory=lambda: new_id("bbentry"), primary_key=True) team_id: str = Field(index=True) tenant_id: str = Field(index=True) - content: str - tags_json: list[str] = Field(default_factory=list, sa_column=Column(JSON)) + content: str = Field(sa_column=Column(Text)) + tags_json: list[str] = Field(default_factory=list, sa_column=Column(PortableJSON)) # source_type: member(TL 裁决的成员建议) / leader / human(人直写) source_type: str = Field(default="human", index=True) source_agent_id: Optional[str] = Field(default=None, index=True) source_task_id: Optional[str] = Field(default=None, index=True) # 引用回链:如 {"task_id": ..., "task_title": ...} - citation_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON)) + citation_json: dict[str, Any] = Field(default_factory=dict, sa_column=Column(PortableJSON)) # status: active / archived status: str = Field(default="active", index=True) pinned: bool = False @@ -1678,14 +1754,14 @@ class TeamTaskBid(SQLModel, table=True): ) id: str = Field(default_factory=lambda: new_id("bid"), primary_key=True) - task_id: str = Field(index=True) + task_id: str = Field(max_length=64, index=True) team_id: str = Field(index=True) tenant_id: str = Field(index=True) - agent_id: str = Field(index=True) + agent_id: str = Field(max_length=64, index=True) round: int = 1 # kind: statement(方案陈述) / rebuttal(反驳) - kind: str = Field(default="statement", index=True) - content: str + kind: str = Field(max_length=32, default="statement", index=True) + content: str = Field(sa_column=Column(Text)) # TL 裁决后回写的分数与理由,未裁决前为 None score: Optional[float] = None score_rationale: Optional[str] = None diff --git a/backend/app/db/opengauss.py b/backend/app/db/opengauss.py new file mode 100644 index 000000000..c7a77c8ff --- /dev/null +++ b/backend/app/db/opengauss.py @@ -0,0 +1,73 @@ +"""openGauss(高斯)SQLAlchemy 方言兼容层. + +openGauss 使用 PostgreSQL 协议,但有两处与上游 PostgreSQL 不同,直接用默认的 +``postgresql+psycopg`` 驱动无法建连/初始化: + +1. ``select version()`` 返回 ``(openGauss 5.0.0 build ) compiled at ...``, + SQLAlchemy 的 PG 方言用正则解析版本失败(无法确定 server_version_info); +2. 服务端返回的 version/设置值在 ``client_encoding`` 未显式指定时可能以 bytes + 返回(SQL_ASCII 初始化库),SQLAlchemy 的版本解析会因此报 + ``cannot use a string pattern on a bytes-like object``。 + +本模块提供一个最小子类:继承 psycopg3 的 PostgreSQL 方言,版本解析失败时回退到 +openGauss 5.x 所基于的 PostgreSQL 9.2 兼容级别(9, 2, 4),并通过 +``opengauss+psycopg://`` URL scheme 注册。其余行为(类型编译、RETURNING、事务) +全部继承 PG 方言;``client_encoding=utf8`` 由 ``app.db.dialect.OpenGaussDialect`` +的 engine_kwargs 注入。 + +用法:``DATABASE_URL="opengauss+psycopg://user:pass@host:5432/postgres"``。 +psycopg 未安装时本模块不做任何注册(SQLite 桌面端无额外依赖),驱动检查由 +``app.db.dialect.ensure_driver_available`` 在启动时给出安装指引。 +""" + +from __future__ import annotations + +import logging + +logger = logging.getLogger(__name__) + +try: # psycopg 为可选依赖([postgres] extra) + from sqlalchemy.dialects.postgresql.psycopg import PGDialect_psycopg as _PGDialectPsycopg +except ImportError: # pragma: no cover - 未安装 psycopg 时走 SQLite/其它后端 + _PGDialectPsycopg = None # type: ignore[assignment] + +# openGauss 5.x 基于 PostgreSQL 9.2 内核,版本解析失败时按该兼容级别工作 +OPENGAUSS_PG_COMPAT_VERSION = (9, 2, 4) + + +if _PGDialectPsycopg is not None: + + class OpenGaussPGDialect(_PGDialectPsycopg): # type: ignore[misc, valid-type] + """openGauss 的 psycopg3 方言:PG 方言 + 版本串/编码兼容。""" + + # SQLAlchemy 2.x 编译缓存需要显式声明;显式继承 PG 方言行为 + supports_statement_cache = True + + def _get_server_version_info(self, connection): + """解析服务端版本;openGauss 的 version 串无法按 PG 正则解析。 + + openGauss 返回形如 ``(openGauss 5.0.0 build ) compiled at ...`` 的 + 字符串(且未设 client_encoding 时可能是 bytes);解析失败时回退到 + PostgreSQL 9.2 兼容级别,保证 PG 方言按 openGauss 支持的语法生成 SQL。 + """ + try: + return super()._get_server_version_info(connection) + except Exception: # noqa: BLE001 - 任何解析失败都回退兼容级别 + logger.debug("openGauss: 无法解析服务端版本,回退 PostgreSQL 9.2 兼容级别") + return OPENGAUSS_PG_COMPAT_VERSION + + from sqlalchemy.dialects import registry as _dialect_registry + + # URL: opengauss+psycopg://user:pass@host:5432/dbname + # + # 注意:这里不用 registry.register(modulepath, objname)——该 API 在引擎创建时 + # 按模块路径重新 import,而 create_engine() 发生在 app.db 包 __init__ 导入 + # 过程中,会触发 "cannot access submodule 'db' of module 'app'" 的循环导入。 + # 直接注册类加载器(PluginLoader.impls 承载可调用对象)即可,与 SQLAlchemy + # 内置方言的注册语义一致且无循环导入。 + _dialect_registry.impls["opengauss.psycopg"] = lambda: OpenGaussPGDialect + + OPENGAUSS_SQLALCHEMY_AVAILABLE = True +else: # pragma: no cover - SQLite 默认安装路径 + OpenGaussPGDialect = None # type: ignore[assignment,misc] + OPENGAUSS_SQLALCHEMY_AVAILABLE = False diff --git a/backend/feishu_connector_worker.py b/backend/feishu_connector_worker.py index 299ccaa27..d659facc0 100644 --- a/backend/feishu_connector_worker.py +++ b/backend/feishu_connector_worker.py @@ -39,18 +39,20 @@ def _user_data_dir() -> Path: return Path.home() / ".local" / "share" / "StaffDeck" -def binding_lock_path(binding_id: str, database_path: Path) -> Path: - database = database_path.expanduser().resolve() - database_fingerprint = hashlib.sha256(str(database).encode("utf-8")).hexdigest()[:16] - binding_fingerprint = hashlib.sha256(binding_id.encode("utf-8")).hexdigest()[:16] - return ( - database.parent - / "connector-locks" - / f"feishu-{database_fingerprint}-{binding_fingerprint}.lock" - ) +def binding_lock_key(binding_id: str) -> str: + """binding 级进程锁的统一 key:方言 advisory lock,锁身份 = 数据库作用域 + key。 + + 同一数据库内同一 binding 互斥;不再取 database_url 指纹(指纹随密码轮换 + 漂移,且跨 HOME/容器互不可见)。 + """ + return f"staffdeck-binding-{binding_id}" class BindingProcessLock: + """用户数据目录文件锁:仅作 spec.database_url 为空(单测直构造 spec)时的兜底。 + + 生产路径一律走 _DialectBindingLock(方言 advisory lock,数据库作用域)。""" + def __init__(self, path: Path): self.path = path self._handle = None @@ -101,14 +103,63 @@ def release(self) -> None: self._handle = None +class _DialectBindingLock: + """binding 级方言 advisory lock:engine 与持锁 session 常驻至 release()。 + + PG 锁随连接存活(专属 AUTOCOMMIT 连接由方言内部常驻,进程退出即释放); + SQLite 为数据库文件旁的文件锁,句柄由方言实现管理。engine 用 NullPool: + 持锁期间不需要连接池复用。engine/session 仅作 bind 来源常驻至 release()。 + """ + + def __init__(self, database_url: str, key: str) -> None: + self._database_url = database_url + self._key = key + self._dialect = None + self._session = None + self._engine = None + + def acquire(self) -> bool: + from sqlalchemy.pool import NullPool + from sqlmodel import Session, create_engine + + from app.db.dialect import get_dialect + + self._engine = create_engine(self._database_url, poolclass=NullPool) + self._session = Session(self._engine) + self._dialect = get_dialect(self._engine.url.get_backend_name()) + if self._dialect.acquire_advisory_lock(self._session, self._key): + return True + self._session.close() + self._session = None + self._engine.dispose() + self._engine = None + return False + + def release(self) -> None: + if self._session is not None: + self._dialect.release_advisory_lock(self._session, self._key) + self._session.close() + self._session = None + if self._engine is not None: + self._engine.dispose() + self._engine = None + + +def _fallback_binding_lock(binding_id: str) -> BindingProcessLock: + """无 database_url 时的兜底文件锁(仅单测直构造 spec 场景)。""" + digest = hashlib.sha256(binding_id.encode("utf-8")).hexdigest()[:16] + path = _user_data_dir() / "connector-locks" / f"feishu-binding-{digest}.lock" + return BindingProcessLock(path) + + @dataclass(frozen=True) class ConnectorChildSpec: binding_id: str config_revision: int child_nonce: str runtime_path: str - binding_lock_path: str - database_path: str = "" + # 完整 SQLAlchemy URL:子进程按它自建引擎(非 SQLite 不传 check_same_thread) + database_url: str = "" watchdog_seconds: float = 2.5 assembly_fingerprint: str = "" @@ -273,7 +324,13 @@ def _load_runtime(path: str) -> Callable[[ConnectorChildSpec, ChildControl, Fram def connector_child_entry(spec: ConnectorChildSpec, connection) -> None: - lock = BindingProcessLock(Path(spec.binding_lock_path)) + # 生产路径:方言 advisory lock(数据库作用域,key 与父进程探测一致); + # spec.database_url 为空(单测直构造 spec)时回退用户数据目录文件锁。 + lock: BindingProcessLock | _DialectBindingLock + if spec.database_url: + lock = _DialectBindingLock(spec.database_url, binding_lock_key(spec.binding_id)) + else: + lock = _fallback_binding_lock(spec.binding_id) if not lock.acquire(): try: connection.send( diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 609810fb5..54514d894 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -4,6 +4,7 @@ version = "0.1.0" description = "FastAPI MVP for an enterprise Skill Agent Loop service" requires-python = ">=3.11" dependencies = [ + "alembic>=1.13", "anthropic>=0.117.0,<0.121.0", # cryptography 49 macOS wheels dynamically link their bundled OpenSSL. PyInstaller # can then select Python's older libssl.3.dylib with the same basename, producing @@ -40,6 +41,17 @@ dev = [ "pytest-asyncio>=0.23.0", "ruff>=0.5.0" ] +# 非 SQLite 驱动按需安装(默认 SQLite 的桌面端不背额外驱动二进制) +postgres = [ + "psycopg[binary]>=3.1" +] +mysql = [ + "pymysql>=1.1" +] +# 达梦:除 dmPython 驱动外还需部署方提供 SQLAlchemy 达梦方言插件(本仓库未预装/未验证) +dm = [ + "dmPython>=2.5" +] packaging = [ "pyinstaller>=6.6.0", "certifi>=2024.2.2", @@ -68,7 +80,12 @@ include = ["app*", "mock_servers*", "staffdeck_harness*", "staffdeck*"] [tool.setuptools.package-data] staffdeck = ["py.typed", "skills/staffdeck-cli/SKILL.md"] -app = ["db/seed_fixtures/*.json"] +app = [ + "db/seed_fixtures/*.json", + "db/migrations/*.py", + "db/migrations/*.mako", + "db/migrations/versions/*.py", +] [tool.ruff] line-length = 100 diff --git a/backend/tests/test_alembic_migrations.py b/backend/tests/test_alembic_migrations.py new file mode 100644 index 000000000..8eed625d7 --- /dev/null +++ b/backend/tests/test_alembic_migrations.py @@ -0,0 +1,236 @@ +"""Alembic 迁移通路回归测试。 + +覆盖:基线 migration 建库(表集合/两个唯一索引/样例数据/幂等/downgrade/离线 SQL), +以及非 SQLite 启动集成 ``_prepare_non_sqlite_schema`` 的三类存量情形 +(全新空库 / 已有表但无版本表 / 已有 alembic_version)。 + +真实 PostgreSQL 验证不进入 CI,只用 tmp SQLite 文件库;PG 手工验证结论见 PR。 +""" + +from __future__ import annotations + +import io +import logging + +import pytest +from sqlalchemy import create_engine, inspect, text +from sqlalchemy.exc import IntegrityError +from sqlmodel import Session, SQLModel, select + +from app.db import database +from app.db.database import _prepare_non_sqlite_schema +from app.db.models import ModelConfig, Tenant + + +def _alembic_config(database_url: str): + return database._alembic_config(database_url) + + +def _head_revision() -> str: + from alembic.script import ScriptDirectory + + head = ScriptDirectory.from_config(_alembic_config("sqlite://")).get_current_head() + assert head is not None + return head + + +def _upgrade_to_head(database_url: str) -> None: + from alembic import command + + command.upgrade(_alembic_config(database_url), "head") + + +def _table_names(engine) -> set[str]: + return set(inspect(engine).get_table_names()) + + +def _indexes_by_name(engine, table_name: str) -> dict[str, dict]: + return {index["name"]: index for index in inspect(engine).get_indexes(table_name)} + + +def _assert_schema_matches_metadata(engine) -> None: + """基线 upgrade 后的表集合必须与当前 SQLModel.metadata 完全一致。""" + expected = set(SQLModel.metadata.tables) | {"alembic_version"} + assert _table_names(engine) == expected + + +def _assert_partial_default_model_index(engine) -> None: + index = _indexes_by_name(engine, "model_configs")["uq_model_configs_tenant_default"] + assert index["column_names"] == ["tenant_id"] + assert index["unique"] == 1 + # SQLite 部分索引带 sqlite_where;PG 为 postgresql_where(见基线 migration) + assert index["dialect_options"] + + +def test_baseline_upgrade_builds_schema_and_indexes(tmp_path) -> None: + db_path = tmp_path / "baseline.db" + database_url = f"sqlite:///{db_path}" + _upgrade_to_head(database_url) + + engine = create_engine(database_url) + try: + _assert_schema_matches_metadata(engine) + _assert_partial_default_model_index(engine) + + session_index = _indexes_by_name(engine, "sessions")[ + "uq_sessions_agent_channel_extconv" + ] + assert session_index["column_names"] == [ + "agent_id", + "channel", + "channel_binding_id", + "external_conv_id", + ] + assert session_index["unique"] == 1 + + with engine.connect() as conn: + version = conn.execute(text("SELECT version_num FROM alembic_version")).scalar() + assert version == _head_revision() + + # 样例数据可插入/查询(ORM 映射与 migration 建出的 schema 一致) + with Session(engine) as session: + session.add(Tenant(id="tenant_a", name="租户 A")) + session.add( + ModelConfig( + tenant_id="tenant_a", + name="默认模型", + api_key_encrypted="secret", + model="demo-model", + is_default=True, + ) + ) + session.commit() + stored = session.exec(select(ModelConfig).where(ModelConfig.tenant_id == "tenant_a")) + assert [row.model for row in stored] == ["demo-model"] + + # 部分唯一索引生效:同租户第二条默认模型被拒绝 + with Session(engine) as session: + session.add( + ModelConfig( + tenant_id="tenant_a", + name="第二个默认", + api_key_encrypted="secret", + model="other-model", + is_default=True, + ) + ) + with pytest.raises(IntegrityError): + session.commit() + + # 非默认模型不受限制 + with Session(engine) as session: + session.add( + ModelConfig( + tenant_id="tenant_a", + name="备用模型", + api_key_encrypted="secret", + model="other-model", + ) + ) + session.commit() + finally: + engine.dispose() + + +def test_baseline_upgrade_is_idempotent_and_downgradable(tmp_path) -> None: + from alembic import command + + database_url = f"sqlite:///{tmp_path / 'roundtrip.db'}" + _upgrade_to_head(database_url) + _upgrade_to_head(database_url) # 重复 upgrade 幂等 + + engine = create_engine(database_url) + try: + assert _table_names(engine) == set(SQLModel.metadata.tables) | {"alembic_version"} + + command.downgrade(_alembic_config(database_url), "base") + assert _table_names(engine) == {"alembic_version"} + + command.upgrade(_alembic_config(database_url), "head") + _assert_schema_matches_metadata(engine) + _assert_partial_default_model_index(engine) + finally: + engine.dispose() + + +def test_env_offline_mode_renders_sql(tmp_path) -> None: + """env.py 的 offline(--sql)通路可用,且基线含方言部分唯一索引。""" + from alembic import command + + config = _alembic_config(f"sqlite:///{tmp_path / 'offline.db'}") + buffer = io.StringIO() + config.output_buffer = buffer + command.upgrade(config, "head", sql=True) + sql = buffer.getvalue() + assert "CREATE TABLE tenants" in sql + assert "CREATE UNIQUE INDEX uq_model_configs_tenant_default" in sql + assert "alembic_version" in sql + + +def test_prepare_non_sqlite_schema_creates_and_stamps_fresh_database(tmp_path) -> None: + engine = create_engine(f"sqlite:///{tmp_path / 'fresh.db'}") + try: + _prepare_non_sqlite_schema(engine) + + _assert_schema_matches_metadata(engine) + # 全新库走 create_all,models.py 的按方言 after_create DDL 同样建出部分索引 + _assert_partial_default_model_index(engine) + with engine.connect() as conn: + version = conn.execute(text("SELECT version_num FROM alembic_version")).scalar() + assert version == _head_revision() + + # 再次调用时已有 alembic_version,走 upgrade head,幂等 + _prepare_non_sqlite_schema(engine) + _assert_schema_matches_metadata(engine) + finally: + engine.dispose() + + +def test_prepare_non_sqlite_schema_stamps_existing_tables_with_warning( + tmp_path, caplog +) -> None: + engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}") + try: + with engine.begin() as conn: + conn.execute( + text( + "CREATE TABLE tenants (" + "id VARCHAR PRIMARY KEY, name VARCHAR NOT NULL, " + "created_at DATETIME, updated_at DATETIME)" + ) + ) + + with caplog.at_level(logging.WARNING, logger="app.db.database"): + _prepare_non_sqlite_schema(engine) + + tables = _table_names(engine) + # 只按基线标记,不 create_all 补建缺失表 + assert "alembic_version" in tables + assert "users" not in tables + assert "tenants" in tables + with engine.connect() as conn: + version = conn.execute(text("SELECT version_num FROM alembic_version")).scalar() + assert version == _head_revision() + assert any( + "缺少 alembic_version" in record.getMessage() for record in caplog.records + ) + finally: + engine.dispose() + + +def test_prepare_non_sqlite_schema_upgrades_versioned_database(tmp_path) -> None: + from alembic import command + + database_url = f"sqlite:///{tmp_path / 'versioned.db'}" + _upgrade_to_head(database_url) + command.downgrade(_alembic_config(database_url), "base") + + engine = create_engine(database_url) + try: + # 重放到 base 后只剩空的 alembic_version;helper 走 upgrade head 重建 schema + assert _table_names(engine) == {"alembic_version"} + _prepare_non_sqlite_schema(engine) + _assert_schema_matches_metadata(engine) + _assert_partial_default_model_index(engine) + finally: + engine.dispose() diff --git a/backend/tests/test_channel_connector_lock.py b/backend/tests/test_channel_connector_lock.py new file mode 100644 index 000000000..987ffd01d --- /dev/null +++ b/backend/tests/test_channel_connector_lock.py @@ -0,0 +1,184 @@ +"""connector 单实例锁:方言分发、SQLite 文件锁行为、PG 持锁会话常驻、占用冲突。""" + +import os +from types import SimpleNamespace + +from sqlalchemy.pool import StaticPool +from sqlmodel import Session, create_engine + +import app.channels as channels +from app.db.dialect import SQLiteDialect + + +def _sqlite_engine(tmp_path, name: str = "connector.db"): + return create_engine( + f"sqlite:///{tmp_path / name}", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + + +def _reset_connector_lock_state() -> None: + channels._connector_lock_pid = None + channels._connector_lock_session = None + + +class _FakeSessionScopedDialect: + """PG 形态的假方言:记录 acquire/release,会话级锁标志位为真。""" + + session_scoped_advisory_lock = True + + def __init__(self, *, acquired: bool = True) -> None: + self.acquired = acquired + self.lock_held = acquired + self.calls: list[tuple[str, str]] = [] + + def acquire_advisory_lock(self, session, key: str) -> bool: + self.calls.append(("acquire", key)) + return self.acquired + + def release_advisory_lock(self, session, key: str) -> None: + self.calls.append(("release", key)) + + def check_advisory_lock(self, session, key: str) -> bool: + self.calls.append(("check", key)) + return self.lock_held + + +def test_connector_lock_sqlite_file_roundtrip(tmp_path, monkeypatch) -> None: + engine = _sqlite_engine(tmp_path) + monkeypatch.setattr("app.db.engine", engine) + _reset_connector_lock_state() + + assert channels._acquire_connector_process_lock() is True + # 重入成功 + assert channels._acquire_connector_process_lock() is True + # 数据目录文件锁已落盘(行为不变,锁文件名带统一 key) + assert (tmp_path / "connector.db.staffdeck-connector.lock").exists() + channels._release_connector_process_lock() + assert channels._connector_lock_pid is None + # 释放后可再获取 + assert channels._acquire_connector_process_lock() is True + channels._release_connector_process_lock() + _reset_connector_lock_state() + + +def test_connector_lock_sqlite_contention_returns_false(tmp_path, monkeypatch) -> None: + engine = _sqlite_engine(tmp_path) + monkeypatch.setattr("app.db.engine", engine) + _reset_connector_lock_state() + + holder = SQLiteDialect() + with Session(engine) as session: + # 另一"进程"(独立方言实例)已持有同一文件锁 + assert holder.acquire_advisory_lock(session, channels._CONNECTOR_LOCK_KEY) is True + assert channels._acquire_connector_process_lock() is False + holder.release_advisory_lock(session, channels._CONNECTOR_LOCK_KEY) + # 释放后可获取 + assert channels._acquire_connector_process_lock() is True + channels._release_connector_process_lock() + _reset_connector_lock_state() + + +def test_connector_lock_pg_resident_session_roundtrip(monkeypatch) -> None: + engine = create_engine("postgresql+psycopg://user:secret@db.internal/staffdeck") + monkeypatch.setattr("app.db.engine", engine) + dialect = _FakeSessionScopedDialect() + monkeypatch.setattr("app.db.dialect.get_dialect", lambda _name: dialect) + _reset_connector_lock_state() + + assert channels._acquire_connector_process_lock() is True + assert dialect.calls == [("acquire", channels._CONNECTOR_LOCK_KEY)] + # PG advisory lock 随连接存活:持锁会话常驻模块级 + assert channels._connector_lock_session is not None + channels._release_connector_process_lock() + assert ("release", channels._CONNECTOR_LOCK_KEY) in dialect.calls + assert channels._connector_lock_session is None + _reset_connector_lock_state() + + +def test_connector_lock_pg_contention_closes_session(monkeypatch) -> None: + engine = create_engine("postgresql+psycopg://user:secret@db.internal/staffdeck") + monkeypatch.setattr("app.db.engine", engine) + dialect = _FakeSessionScopedDialect(acquired=False) + monkeypatch.setattr("app.db.dialect.get_dialect", lambda _name: dialect) + _reset_connector_lock_state() + + assert channels._acquire_connector_process_lock() is False + assert channels._connector_lock_session is None + assert channels._connector_lock_pid is None + _reset_connector_lock_state() + + +# ---------- 会话级锁存活校验与断连降级 ---------- + + +def test_connector_lock_healthy_without_session_is_true() -> None: + """文件锁路径无常驻会话:无静默失效模式,健康检查恒 True。""" + _reset_connector_lock_state() + assert channels._connector_lock_healthy() is True + + +def test_connector_lock_healthy_delegates_to_dialect(monkeypatch) -> None: + engine = create_engine("postgresql+psycopg://user:secret@db.internal/staffdeck") + monkeypatch.setattr("app.db.engine", engine) + dialect = _FakeSessionScopedDialect() + monkeypatch.setattr("app.db.dialect.get_dialect", lambda _name: dialect) + _reset_connector_lock_state() + + channels._connector_lock_session = object() + dialect.lock_held = True + assert channels._connector_lock_healthy() is True + dialect.lock_held = False + assert channels._connector_lock_healthy() is False + _reset_connector_lock_state() + + +def test_connector_lock_watchdog_degrades_on_lock_loss(monkeypatch) -> None: + """锁静默失效:看门狗调用 stop_channel_services 主动降级后退出。""" + _reset_connector_lock_state() + monkeypatch.setattr(channels, "_CONNECTOR_LOCK_CHECK_SECONDS", 0) + channels._connector_lock_pid = os.getpid() + channels._connector_lock_session = object() + monkeypatch.setattr(channels, "_connector_lock_healthy", lambda: False) + calls: list[str] = [] + monkeypatch.setattr( + channels, "stop_channel_services", lambda: calls.append("stop") or True + ) + + channels._connector_lock_watchdog() + assert calls == ["stop"] + _reset_connector_lock_state() + + +def test_connector_lock_watchdog_exits_after_normal_release(monkeypatch) -> None: + """正常释放锁后看门狗自行退出,不触发降级。""" + _reset_connector_lock_state() + monkeypatch.setattr(channels, "_CONNECTOR_LOCK_CHECK_SECONDS", 0) + # pid=None:锁未持有,看门狗第一轮即返回 + calls: list[str] = [] + monkeypatch.setattr( + channels, "stop_channel_services", lambda: calls.append("stop") or True + ) + channels._connector_lock_watchdog() + assert calls == [] + + +def test_release_tolerates_dead_lock_session(monkeypatch) -> None: + """释放路径容错:会话已随断连死亡(release 抛错)时状态仍被清理,不再抛出。""" + engine = create_engine("postgresql+psycopg://user:secret@db.internal/staffdeck") + monkeypatch.setattr("app.db.engine", engine) + + class _DeadReleaseDialect(_FakeSessionScopedDialect): + def release_advisory_lock(self, session, key: str) -> None: + raise RuntimeError("connection is closed") + + dialect = _DeadReleaseDialect() + monkeypatch.setattr("app.db.dialect.get_dialect", lambda _name: dialect) + _reset_connector_lock_state() + channels._connector_lock_pid = os.getpid() + channels._connector_lock_session = SimpleNamespace(close=lambda: None) + + channels._release_connector_process_lock() # 不应抛出 + assert channels._connector_lock_pid is None + assert channels._connector_lock_session is None diff --git a/backend/tests/test_channel_session.py b/backend/tests/test_channel_session.py index d659971bb..6f421996d 100644 --- a/backend/tests/test_channel_session.py +++ b/backend/tests/test_channel_session.py @@ -1,27 +1,20 @@ import pytest from sqlalchemy.exc import IntegrityError from sqlalchemy.pool import StaticPool -from sqlmodel import Session, SQLModel, create_engine, text +from sqlmodel import Session, SQLModel, create_engine from app.channels.service_session import find_or_create_channel_session from app.db.models import ChannelBinding, ChatSession, Tenant, User -def _test_engine(with_unique_index: bool = False): +def _test_engine(): + # 唯一索引 uq_sessions_agent_channel_extconv 已由 models.py 并入 create_all engine = create_engine( "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, ) SQLModel.metadata.create_all(engine) - if with_unique_index: - with engine.begin() as conn: - conn.execute( - text( - "CREATE UNIQUE INDEX uq_sessions_agent_channel_extconv " - "ON sessions(agent_id, channel, channel_binding_id, external_conv_id)" - ) - ) return engine @@ -62,7 +55,7 @@ def test_create_then_reuse_channel_session() -> None: def test_user_mismatch_archives_legacy_session_and_starts_clean() -> None: - engine = _test_engine(with_unique_index=True) + engine = _test_engine() with Session(engine) as db: binding, old_user = _seed(db) new_user = User( @@ -136,7 +129,7 @@ def test_channel_target_json_roundtrip() -> None: def test_unique_index_rejects_duplicate_anchor() -> None: - engine = _test_engine(with_unique_index=True) + engine = _test_engine() with Session(engine) as db: binding, user = _seed(db) first = find_or_create_channel_session(db, binding, user, "agent_1", "wechat_p2p_wxid_1", "hi") @@ -160,7 +153,7 @@ def test_unique_index_rejects_duplicate_anchor() -> None: def test_web_sessions_coexist_under_unique_index() -> None: - engine = _test_engine(with_unique_index=True) + engine = _test_engine() with Session(engine) as db: _seed(db) # channel 为 NULL 的 web 会话在唯一索引下互不相等,可重复存在 diff --git a/backend/tests/test_channel_wechat.py b/backend/tests/test_channel_wechat.py index 3aa836e5b..a562db3e1 100644 --- a/backend/tests/test_channel_wechat.py +++ b/backend/tests/test_channel_wechat.py @@ -1065,3 +1065,107 @@ def handler(request: httpx.Request) -> httpx.Response: random_ids = [payload["msg"]["client_id"] for payload in sent] assert len(set(random_ids)) == 3 assert all(not cid.startswith("staffdeck:msg_1") for cid in random_ids) + + +# ---------- _patch_runtime_config 读-改-写 + revision CAS ---------- + + +def test_patch_runtime_config_revision_cas_and_expected_values() -> None: + from app.channels.adapters.wechat import _patch_runtime_config + + engine = _test_engine() + with Session(engine) as db: + db.add(Tenant(id="tenant_demo", name="Demo")) + binding = ChannelBinding( + tenant_id="tenant_demo", + agent_id="agent_1", + channel="wechat", + status="active", + config_json={"get_updates_buf": "old", "typing_ticket": "t1"}, + ) + db.add(binding) + db.commit() + db.refresh(binding) + binding_id = binding.id + revision = binding.config_revision + + # stale expected_revision:CAS 拒绝且不落库 + assert ( + _patch_runtime_config( + engine, + binding_id, + set_values={"get_updates_buf": "new"}, + expected_revision=revision + 1, + ) + is False + ) + # JSON 键 CAS 不符:拒绝 + assert ( + _patch_runtime_config( + engine, + binding_id, + remove_keys=("typing_ticket",), + expected_values={"typing_ticket": "other"}, + ) + is False + ) + with Session(engine) as db: + row = db.get(ChannelBinding, binding_id) + assert row.config_json["get_updates_buf"] == "old" + assert row.config_json["typing_ticket"] == "t1" + + # revision 与 expected_values 均匹配:set/remove/列值一并原子落库 + assert ( + _patch_runtime_config( + engine, + binding_id, + set_values={"get_updates_buf": "new"}, + remove_keys=("typing_ticket",), + expected_revision=revision, + expected_values={"typing_ticket": "t1"}, + binding_values={"connected": True}, + ) + is True + ) + with Session(engine) as db: + row = db.get(ChannelBinding, binding_id) + assert row.config_json == {"get_updates_buf": "new"} + assert row.connected is True + + +def test_patch_runtime_config_require_active_and_field_whitelist() -> None: + from app.channels.adapters.wechat import _patch_runtime_config + + engine = _test_engine() + with Session(engine) as db: + db.add(Tenant(id="tenant_demo", name="Demo")) + binding = ChannelBinding( + tenant_id="tenant_demo", + agent_id="agent_1", + channel="wechat", + status="expired", + config_json={}, + ) + db.add(binding) + db.commit() + db.refresh(binding) + binding_id = binding.id + + # 非 active:require_active 拒绝 + assert ( + _patch_runtime_config( + engine, binding_id, set_values={"get_updates_buf": "x"}, require_active=True + ) + is False + ) + # 白名单外列:拒绝 + try: + _patch_runtime_config(engine, binding_id, binding_values={"tenant_id": "evil"}) + except ValueError as error: + assert "unsupported binding runtime field" in str(error) + else: + raise AssertionError("白名单外字段必须拒绝") + # 不存在的 binding:False + assert _patch_runtime_config(engine, "chan_missing", set_values={"a": 1}) is False + + diff --git a/backend/tests/test_db_adapters.py b/backend/tests/test_db_adapters.py new file mode 100644 index 000000000..230b2c6f2 --- /dev/null +++ b/backend/tests/test_db_adapters.py @@ -0,0 +1,309 @@ +"""MySQL/达梦适配器单测:注册表、能力位、引擎参数、日分桶、命名锁、驱动提示。 + +全部用例不依赖真实驱动/数据库:命名锁用桩 Engine/Connection/Session(与 +test_db_dialect.py 的 PG 用例同构),驱动缺失用 sys.modules 注入 None 模拟 +ImportError,日分桶用 SQLAlchemy 方言离线编译。 +""" + +import os +import sys +import types +from types import SimpleNamespace + +import pytest +from sqlalchemy import Column, DateTime +from sqlalchemy.dialects import mysql as mysql_dialect +from sqlalchemy.dialects import sqlite as sqlite_dialect +from sqlalchemy.engine import make_url + +import app.db.dialect as dialect_module +from app.db.dialect import ( + DatabaseDialect, + DMDialect, + MySQLDialect, + ensure_driver_available, + get_dialect, +) + +_COLUMN = Column("created_at", DateTime) + + +# ---------- 注册表与能力位 ---------- + + +def test_mysql_dialect_registered_with_expected_capabilities() -> None: + dialect = get_dialect("mysql") + assert isinstance(dialect, MySQLDialect) + assert isinstance(dialect, DatabaseDialect) + assert dialect.name == "mysql" + # 无部分唯一索引:默认模型索引不创建,由 init_db 启动校验兜底 + assert dialect.supports_partial_index is False + # 命名锁属于连接:业务层须常驻专属连接(见 PostgresDialect 同语义) + assert dialect.session_scoped_advisory_lock is True + + +def test_dm_dialect_registered_with_expected_capabilities() -> None: + dialect = get_dialect("dm") + assert isinstance(dialect, DMDialect) + assert isinstance(dialect, DatabaseDialect) + assert dialect.name == "dm" + assert dialect.supports_partial_index is False + # 无已验证原生锁:走 BaseDialect 文件锁(非 SQLite 文件库响亮拒绝) + assert dialect.session_scoped_advisory_lock is False + + +def test_mysql_engine_kwargs_pool_hardening_and_utf8mb4() -> None: + kwargs = MySQLDialect().engine_kwargs("mysql+pymysql://u:p@h/db") + assert kwargs["pool_pre_ping"] is True + assert kwargs["pool_recycle"] == 1800 + assert kwargs["pool_size"] == 10 + assert kwargs["max_overflow"] == 20 + assert kwargs["connect_args"] == {"charset": "utf8mb4"} + + +def test_dm_engine_kwargs_defer_to_deployment() -> None: + """达梦方言插件/驱动为部署方安装物:不内置未经验证的项目参数。""" + assert DMDialect().engine_kwargs("dm+dmPython://u:p@h:5236/STAFFDECK") == {} + + +# ---------- 日分桶(离线编译) ---------- + + +def test_mysql_day_bucket_compiles_to_date_cast() -> None: + compiled = str( + MySQLDialect() + .day_bucket(_COLUMN) + .compile(dialect=mysql_dialect.dialect(), compile_kwargs={"literal_binds": True}) + ) + # 服务器时区自然日:标准 SQL CAST(... AS DATE),无 sqlite 的 localtime 修饰 + assert compiled == "CAST(created_at AS DATE)" + + +def test_dm_day_bucket_compiles_to_date_cast() -> None: + compiled = str( + DMDialect() + .day_bucket(_COLUMN) + .compile(dialect=sqlite_dialect.dialect(), compile_kwargs={"literal_binds": True}) + ) + assert compiled == "CAST(created_at AS DATE)" + + +# ---------- MySQL 命名锁(桩连接,不依赖真实 MySQL) ---------- + + +class _StubConn: + """专属连接桩:记录 SQL/参数、AUTOCOMMIT 设置与关闭状态。""" + + def __init__(self, scalar=1) -> None: + self._scalar = scalar + self.calls: list[tuple[str, dict | None]] = [] + self.isolation: str | None = None + self.closed = False + + def execution_options(self, **kwargs): + self.isolation = kwargs.get("isolation_level") + return self + + def execute(self, statement, params=None): + self.calls.append((str(statement), params)) + return SimpleNamespace(scalar=lambda: self._scalar) + + def close(self) -> None: + self.closed = True + + +class _StubEngine: + """connect() 按需产出新 _StubConn 的引擎桩;scalar 可调模拟 GET_LOCK 返回。""" + + def __init__(self) -> None: + self.conns: list[_StubConn] = [] + self.scalar = 1 + + def connect(self): + conn = _StubConn(self.scalar) + self.conns.append(conn) + return conn + + +class _StubSession: + """最小会话桩:仅作 bind 来源(锁实现不得 commit/rollback 它)。""" + + def __init__(self, bind) -> None: + self._bind = bind + + def get_bind(self): + return self._bind + + +def test_mysql_advisory_lock_uses_named_lock_on_dedicated_connection() -> None: + """acquire/check/release 全程使用同一条专属 Connection,不归池。""" + dialect = MySQLDialect() + engine = _StubEngine() + session = _StubSession(engine) + + assert dialect.acquire_advisory_lock(session, "staffdeck-connector") is True + assert len(engine.conns) == 1 + conn = engine.conns[0] + assert conn.isolation == "AUTOCOMMIT" + assert conn.calls[0] == ("SELECT GET_LOCK(:key, 0)", {"key": "staffdeck-connector"}) + assert conn.closed is False + + # check 在同一连接上比对 IS_USED_LOCK 与 CONNECTION_ID(),不再从池里取新连接 + assert dialect.check_advisory_lock(session, "staffdeck-connector") is True + assert len(engine.conns) == 1 + check_sql, check_params = conn.calls[1] + assert "IS_USED_LOCK(:key) = CONNECTION_ID()" in check_sql + assert check_params == {"key": "staffdeck-connector"} + + dialect.release_advisory_lock(session, "staffdeck-connector") + assert conn.calls[2][0] == "SELECT RELEASE_LOCK(:key)" + assert conn.closed is True + + # 释放后重新取锁:新连接 + assert dialect.acquire_advisory_lock(session, "staffdeck-connector") is True + assert len(engine.conns) == 2 + dialect.release_advisory_lock(session, "staffdeck-connector") + + +def test_mysql_advisory_lock_resolves_engine_from_session_bind() -> None: + """session.get_bind() 返回 Connection 形态时取其 .engine(与 PG 同 seam)。""" + engine = _StubEngine() + session = _StubSession(SimpleNamespace(engine=engine)) + assert MySQLDialect().acquire_advisory_lock(session, "k") is True + assert len(engine.conns) == 1 + + +@pytest.mark.parametrize("locked_value", [0, None]) +def test_mysql_advisory_lock_contention_or_error_closes_connection(locked_value) -> None: + """GET_LOCK 返回 0=被占用 / NULL=错误:都不算持锁,专属连接立即关闭。""" + dialect = MySQLDialect() + engine = _StubEngine() + engine.scalar = locked_value + session = _StubSession(engine) + + assert dialect.acquire_advisory_lock(session, "connector") is False + assert engine.conns[0].closed is True + assert dialect.check_advisory_lock(session, "connector") is False + + +def test_mysql_advisory_lock_check_failure_treated_as_lost(monkeypatch) -> None: + """连接被服务端掐断后 check 查询抛错:必须判失效(不能静默当健康)。""" + dialect = MySQLDialect() + engine = _StubEngine() + session = _StubSession(engine) + assert dialect.acquire_advisory_lock(session, "connector") is True + conn = engine.conns[0] + + def _broken_execute(statement, params=None): + raise RuntimeError("MySQL server has gone away") + + monkeypatch.setattr(conn, "execute", _broken_execute) + assert dialect.check_advisory_lock(session, "connector") is False + + +def test_mysql_advisory_lock_reentrant_and_fork_guard(monkeypatch) -> None: + """同进程重入不新建连接;fork 子进程继承连接不作数且不被操作/关闭。""" + parent = MySQLDialect() + engine = _StubEngine() + session = _StubSession(engine) + assert parent.acquire_advisory_lock(session, "k") is True + assert parent.acquire_advisory_lock(session, "k") is True + assert len(engine.conns) == 1 + parent_conn = engine.conns[0] + parent_calls = len(parent_conn.calls) + + # 模拟另一"进程"(独立方言实例 + 另一进程号):继承状态不作数 + child = MySQLDialect() + child._mysql_lock_conns = dict(parent._mysql_lock_conns) # fork 继承的是内存副本 + real_pid = os.getpid() + monkeypatch.setattr(os, "getpid", lambda: real_pid + 100000) + assert child.check_advisory_lock(session, "k") is False + # 子进程不得在父进程的共享连接上执行任何语句(INVALID:关闭会连带释放父锁) + assert len(parent_conn.calls) == parent_calls + assert parent_conn.closed is False + assert child.acquire_advisory_lock(session, "k") is True + assert len(engine.conns) == 2 + child.release_advisory_lock(session, "k") + # 子进程只释放自己的新连接,继承的父连接保持原状 + assert engine.conns[1].closed is True + assert parent_conn.closed is False + monkeypatch.undo() + # 父进程锁不受子进程动作影响 + assert parent.check_advisory_lock(session, "k") is True + parent.release_advisory_lock(session, "k") + assert parent_conn.closed is True + + +def test_mysql_advisory_lock_rejects_overlong_lock_name() -> None: + """MySQL 命名锁名上限 64 字符:边界内可用,超长响亮拒绝且不碰数据库。""" + assert MySQLDialect.MAX_LOCK_NAME_LENGTH == 64 + engine = _StubEngine() + session = _StubSession(engine) + dialect = MySQLDialect() + assert dialect.acquire_advisory_lock(session, "k" * 64) is True + dialect.release_advisory_lock(session, "k" * 64) + + engine.conns.clear() + with pytest.raises(ValueError, match="64 个字符"): + dialect.acquire_advisory_lock(session, "k" * 65) + assert engine.conns == [] + + +# ---------- 达梦:无原生锁 → 文件锁响亮拒绝 ---------- + + +def test_dm_file_lock_refuses_non_sqlite_database() -> None: + """达梦 url.database 是库名而非文件路径:不得当路径在 CWD 生成静默错锁。""" + dialect = get_dialect("dm") + session = SimpleNamespace( + get_bind=lambda: SimpleNamespace( + url=make_url("dm+dmPython://u:p@dm.internal:5236/STAFFDECK") + ) + ) + assert dialect.acquire_advisory_lock(session, "staffdeck-connector") is False + assert dialect._lock_handles == {} + assert dialect.check_advisory_lock(session, "staffdeck-connector") is False + + +# ---------- 可选驱动提示 ---------- + + +def test_optional_driver_specs_cover_mysql_and_dm() -> None: + assert dialect_module._OPTIONAL_DRIVERS["mysql"] == ( + "pymysql", + 'pip install "skill-agent-loop-backend[mysql]"', + ) + assert dialect_module._OPTIONAL_DRIVERS["dm"] == ( + "dmPython", + 'pip install "skill-agent-loop-backend[dm]"', + ) + + +@pytest.mark.parametrize( + ("backend", "module_name", "url"), + [ + ("mysql", "pymysql", "mysql+pymysql://u:p@db.internal/staffdeck"), + ("dm", "dmPython", "dm+dmPython://u:p@dm.internal:5236/STAFFDECK"), + ], +) +def test_ensure_driver_available_missing_driver_has_install_hint( + monkeypatch, backend: str, module_name: str, url: str +) -> None: + # sys.modules 中置 None 使 __import__ 抛 ImportError(与真实缺驱动同路径) + monkeypatch.setitem(sys.modules, module_name, None) + with pytest.raises(RuntimeError) as excinfo: + ensure_driver_available(make_url(url)) + message = str(excinfo.value) + assert backend in message + assert "需要可选驱动" in message + assert f"skill-agent-loop-backend[{backend}]" in message + # 保留原始 ImportError 作为 cause,便于排障 + assert isinstance(excinfo.value.__cause__, ImportError) + + +def test_ensure_driver_available_passes_when_driver_present(monkeypatch) -> None: + monkeypatch.setitem(sys.modules, "pymysql", types.ModuleType("pymysql")) + assert ensure_driver_available(make_url("mysql+pymysql://u:p@h/db")) is None + # 未登记可选驱动的后端(sqlite/未注册)直接放行 + assert ensure_driver_available(make_url("sqlite:///x.db")) is None + assert ensure_driver_available(make_url("mssql+pyodbc://u:p@h/db")) is None diff --git a/backend/tests/test_db_dialect.py b/backend/tests/test_db_dialect.py new file mode 100644 index 000000000..fae7a187e --- /dev/null +++ b/backend/tests/test_db_dialect.py @@ -0,0 +1,507 @@ +"""方言提供者单测:注册表、engine_kwargs、日分桶表达式形态、JSON 读改写、锁。""" + +import os +from types import SimpleNamespace + +from sqlalchemy import Column, DateTime +from sqlalchemy.dialects import postgresql, sqlite +from sqlalchemy.pool import StaticPool +from sqlmodel import Session, SQLModel, create_engine, select +from sqlalchemy import text as sa_text + +from app.db.dialect import ( + GenericDialect, + PostgresDialect, + SQLiteDialect, + get_dialect, + register_dialect, +) +import app.db.dialect as dialect_module + +import pytest + +_COLUMN = Column("created_at", DateTime) + + +@pytest.fixture(autouse=True) +def _restore_dialect_registry(): + """用例可能注册新方言或缓存 Generic 实例:每个用例后还原注册表,防跨测试污染。""" + snapshot = dict(dialect_module._DIALECTS) + yield + dialect_module._DIALECTS.clear() + dialect_module._DIALECTS.update(snapshot) + + +def test_registry_returns_expected_dialects() -> None: + assert get_dialect("sqlite").name == "sqlite" + assert get_dialect("sqlite").supports_partial_index is True + assert get_dialect("postgresql").name == "postgresql" + assert get_dialect("postgresql").supports_partial_index is True + # MySQL/达梦已注册专属适配器(能力位与锁语义见 test_db_adapters.py) + assert get_dialect("mysql").name == "mysql" + assert get_dialect("dm").name == "dm" + # 未注册后端回退 GenericDialect(名按 backend 名,能力保守) + fallback = get_dialect("mssql") + assert isinstance(fallback, GenericDialect) + assert fallback.name == "mssql" + assert fallback.supports_partial_index is False + + +def test_register_dialect_override() -> None: + custom = GenericDialect("dm") + register_dialect("dm", custom) + assert get_dialect("dm") is custom + + +def test_engine_kwargs_sqlite_matches_legacy_behavior() -> None: + kwargs = get_dialect("sqlite").engine_kwargs("sqlite:///x.db") + assert kwargs == {"connect_args": {"check_same_thread": False, "timeout": 30}} + # PG 连接池加固:pre_ping 防陈旧连接、recycle 防 idle 掐断、池容随 binding 增长 + pg_kwargs = get_dialect("postgresql").engine_kwargs("postgresql+psycopg://h/db") + assert pg_kwargs["pool_pre_ping"] is True + + +def test_day_bucket_sqlite_keeps_localtime_date() -> None: + compiled = str( + SQLiteDialect() + .day_bucket(_COLUMN) + .compile(dialect=sqlite.dialect(), compile_kwargs={"literal_binds": True}) + ) + assert "date(" in compiled and "localtime" in compiled + + +def test_day_bucket_postgres_casts_with_configured_timezone(monkeypatch) -> None: + monkeypatch.setattr( + "app.db.dialect.get_settings", lambda: SimpleNamespace(app_timezone="Asia/Shanghai") + ) + compiled = str( + PostgresDialect() + .day_bucket(_COLUMN) + .compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}) + ) + assert "timezone('Asia/Shanghai'" in compiled + assert compiled.startswith("CAST(") and compiled.endswith("AS DATE)") + + +def test_day_bucket_postgres_falls_back_to_local_offset(monkeypatch) -> None: + monkeypatch.setattr( + "app.db.dialect.get_settings", lambda: SimpleNamespace(app_timezone="") + ) + compiled = str( + PostgresDialect() + .day_bucket(_COLUMN) + .compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}) + ) + assert "make_interval" in compiled + assert compiled.startswith("CAST(") and compiled.endswith("AS DATE)") + + +def test_day_bucket_generic_is_standard_cast() -> None: + compiled = str( + GenericDialect("dm") + .day_bucket(_COLUMN) + .compile(dialect=sqlite.dialect(), compile_kwargs={"literal_binds": True}) + ) + assert compiled.startswith("CAST(") and " AS DATE)" in compiled + + +def test_json_config_helpers_read_modify_write() -> None: + dialect = SQLiteDialect() + assert dialect.json_config_get(None, "k") is None + config = dialect.json_config_set({"a": 1}, "b", {"x": True}) + assert config == {"a": 1, "b": {"x": True}} + # 不改动入参原 dict + assert dialect.json_config_get(config, "a") == 1 + removed = dialect.json_config_remove(config, "a") + assert removed == {"b": {"x": True}} + assert dialect.json_config_remove(config, "missing") == config + + +def test_sqlite_file_advisory_lock_excludes_other_holder(tmp_path) -> None: + engine = create_engine( + f"sqlite:///{tmp_path / 'lock.db'}", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + first, second = SQLiteDialect(), SQLiteDialect() + with Session(engine) as session: + assert first.acquire_advisory_lock(session, "connector") is True + # 同一持有者重入成功 + assert first.acquire_advisory_lock(session, "connector") is True + # 另一持有者抢同一把文件锁失败 + assert second.acquire_advisory_lock(session, "connector") is False + first.release_advisory_lock(session, "connector") + # 释放后可被他人获取 + assert second.acquire_advisory_lock(session, "connector") is True + second.release_advisory_lock(session, "connector") + + +class _StubConn: + """PG 专属连接桩:记录 SQL、AUTOCOMMIT 设置与关闭状态。""" + + def __init__(self, scalar=1, *, first_row=(1,)) -> None: + self._scalar = scalar + self._first_row = first_row + self.calls: list[tuple[str, dict]] = [] + self.isolation: str | None = None + self.closed = False + + def execution_options(self, **kwargs): + self.isolation = kwargs.get("isolation_level") + return self + + def execute(self, statement, params=None): + self.calls.append((str(statement), params)) + return SimpleNamespace( + scalar=lambda: self._scalar, + first=lambda: self._first_row, + ) + + def close(self) -> None: + self.closed = True + + +class _StubEngine: + """connect() 按需产出新 _StubConn 的引擎桩。""" + + def __init__(self) -> None: + self.conns: list[_StubConn] = [] + self.scalar = 1 + self.first_row = (1,) + + def connect(self): + conn = _StubConn(self.scalar, first_row=self.first_row) + self.conns.append(conn) + return conn + + +class _StubSession: + """最小会话桩:仅作 bind 来源(锁实现不得 commit/rollback 它)。""" + + def __init__(self, engine: _StubEngine) -> None: + self._engine = engine + + def get_bind(self): + return self._engine + + +def test_postgres_advisory_lock_uses_dedicated_autocommit_connection() -> None: + """acquire/check/release 全程使用同一条专属 AUTOCOMMIT Connection,不归池。""" + dialect = PostgresDialect() + engine = _StubEngine() + session = _StubSession(engine) + + assert dialect.acquire_advisory_lock(session, "connector") is True + assert len(engine.conns) == 1 + conn = engine.conns[0] + assert conn.isolation == "AUTOCOMMIT" + assert "pg_try_advisory_lock(hashtext(:key), 0)" in conn.calls[0][0] + assert conn.closed is False + + # check 在同一连接上查 pg_locks(pid 稳定),不再从池里取新连接 + assert dialect.check_advisory_lock(session, "connector") is True + assert len(engine.conns) == 1 + sql = conn.calls[1][0] + assert "pg_locks" in sql and "locktype = 'advisory'" in sql + assert "pg_backend_pid()" in sql + + dialect.release_advisory_lock(session, "connector") + assert "pg_advisory_unlock(hashtext(:key), 0)" in conn.calls[2][0] + assert conn.closed is True + + # 释放后再取:新连接 + assert dialect.acquire_advisory_lock(session, "connector") is True + assert len(engine.conns) == 2 + dialect.release_advisory_lock(session, "connector") + + +def test_postgres_advisory_lock_contention_closes_connection() -> None: + """抢锁失败:专属连接立即关闭,不驻留;check 判 False。""" + dialect = PostgresDialect() + engine = _StubEngine() + engine.scalar = 0 + session = _StubSession(engine) + + assert dialect.acquire_advisory_lock(session, "connector") is False + assert engine.conns[0].closed is True + assert dialect.check_advisory_lock(session, "connector") is False + + +def test_postgres_advisory_lock_reentrant_and_fork_guard(monkeypatch) -> None: + """同进程重入不新建连接;fork 子进程视角下继承连接不作数,按新身份真实抢锁。""" + parent = PostgresDialect() + engine = _StubEngine() + session = _StubSession(engine) + assert parent.acquire_advisory_lock(session, "k") is True + assert parent.acquire_advisory_lock(session, "k") is True + assert len(engine.conns) == 1 + + # 模拟另一"进程"(独立方言实例 + 另一进程号):继承状态不作数 + child = PostgresDialect() + child._pg_lock_conns = dict(parent._pg_lock_conns) # fork 继承的是内存副本 + real_pid = os.getpid() + monkeypatch.setattr(os, "getpid", lambda: real_pid + 100000) + assert child.check_advisory_lock(session, "k") is False + assert child.acquire_advisory_lock(session, "k") is True + assert len(engine.conns) == 2 + child.release_advisory_lock(session, "k") + monkeypatch.undo() + # 父进程锁不受子进程动作影响 + assert parent.check_advisory_lock(session, "k") is True + parent.release_advisory_lock(session, "k") + + +def test_postgres_engine_kwargs_pool_hardening() -> None: + kwargs = PostgresDialect().engine_kwargs("postgresql+psycopg://u:p@h/db") + assert kwargs["pool_pre_ping"] is True + assert kwargs["pool_recycle"] > 0 + assert kwargs["pool_size"] >= 10 + + +def test_generic_file_lock_refuses_non_sqlite_backend() -> None: + """MySQL/达梦等:url.database 是库名而非文件路径,文件锁必须响亮拒绝。""" + from sqlalchemy.engine import make_url + + dialect = GenericDialect("mysql") + session = SimpleNamespace( + get_bind=lambda: SimpleNamespace(url=make_url("mysql+pymysql://u:p@db.internal/staffdeck")) + ) + assert dialect.acquire_advisory_lock(session, "staffdeck-connector") is False + + +def test_base_check_advisory_lock_tracks_file_handle(tmp_path) -> None: + """文件锁无静默失效:check 只核实本进程仍持有打开的句柄。""" + engine = create_engine( + f"sqlite:///{tmp_path / 'check.db'}", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + dialect = SQLiteDialect() + with Session(engine) as session: + assert dialect.check_advisory_lock(session, "k") is False + assert dialect.acquire_advisory_lock(session, "k") is True + assert dialect.check_advisory_lock(session, "k") is True + dialect.release_advisory_lock(session, "k") + assert dialect.check_advisory_lock(session, "k") is False + + +def test_default_model_partial_index_not_in_table_metadata() -> None: + """部分唯一索引不进 metadata:其它方言 create_all 不会静默退化为全量唯一索引。""" + import app.db.models as models # noqa: F401 + + index_names = {index.name for index in models.ModelConfig.__table__.indexes} + assert "uq_model_configs_tenant_default" not in index_names + + +def test_for_update_compile_dialect_behavior() -> None: + """FOR UPDATE:PG 真实加锁,SQLite 省略(编译期即验证,不依赖真实连接)。""" + from sqlalchemy.dialects import postgresql as pg_dialect + from sqlalchemy.dialects import sqlite as sqlite_dialect + + from app.db.models import ChannelBinding + + stmt = select(ChannelBinding).where(ChannelBinding.id == "b1").with_for_update() + assert "FOR UPDATE" in str(stmt.compile(dialect=pg_dialect.dialect())) + assert "FOR UPDATE" not in str(stmt.compile(dialect=sqlite_dialect.dialect())) + + +def test_create_all_contains_channel_session_unique_index() -> None: + import app.db.models # noqa: F401 - 注册全部表模型 + + engine = create_engine( + "sqlite://", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + SQLModel.metadata.create_all(engine) + with engine.connect() as conn: + session_indexes = { + row[1] for row in conn.execute(sa_text("PRAGMA index_list('sessions')")) + } + assert "uq_sessions_agent_channel_extconv" in session_indexes + index_sql = conn.execute( + sa_text( + "SELECT sql FROM sqlite_master " + "WHERE type='index' AND name='uq_model_configs_tenant_default'" + ) + ).scalar_one() + # 部分唯一索引:仅默认模型一行受约束 + assert "WHERE is_default = 1" in index_sql + + +def test_sqlite_file_lock_fork_child_does_not_inherit(tmp_path, monkeypatch) -> None: + """fork 防护:继承句柄不作数(重抢并登记新进程号);父进程仍持锁时真实抢锁失败。""" + engine = create_engine( + f"sqlite:///{tmp_path / 'fork.db'}", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + dialect = SQLiteDialect() + sibling = SQLiteDialect() # 模拟父进程仍存活持有的同一把锁 + real_pid = os.getpid() + with Session(engine) as session: + assert dialect.acquire_advisory_lock(session, "k") is True + # 进入"子进程"视角(getpid 被 mock 成另一个进程号):继承句柄被关闭并按 + # 本进程身份重抢(同进程内等价:旧锁已随句柄关闭释放),锁登记到新进程号 + monkeypatch.setattr(os, "getpid", lambda: real_pid + 100000) + assert dialect.acquire_advisory_lock(session, "k") is True + assert dialect._lock_handles["k"][0] == real_pid + 100000 + dialect.release_advisory_lock(session, "k") + # 父进程仍持锁(sibling 句柄打开):子进程身份真实抢锁失败 + assert sibling.acquire_advisory_lock(session, "k") is True + assert dialect.acquire_advisory_lock(session, "k") is False + sibling.release_advisory_lock(session, "k") + # 父释放后可得 + assert dialect.acquire_advisory_lock(session, "k") is True + dialect.release_advisory_lock(session, "k") + + +def _seed_duplicate_default_models(engine) -> None: + from app.db.models import ModelConfig + + # sqlite 上索引已由按方言 DDL 创建,先删掉再插入(模拟无部分索引后端的数据形态) + with engine.begin() as conn: + conn.execute(sa_text("DROP INDEX uq_model_configs_tenant_default")) + with Session(engine) as db: + for name in ("m1", "m2"): + db.add( + ModelConfig( + tenant_id="t1", + name=name, + model="gpt-x", + api_key_encrypted="enc", + is_default=True, + ) + ) + db.commit() + + +def test_validate_default_model_invariant_rejects_duplicates(monkeypatch, tmp_path) -> None: + """无部分索引后端:启动校验发现同租户多条默认模型时响亮拒绝,清理后放行。""" + import app.db.database as database + import app.db.models # noqa: F401 - 注册全部表模型 + from app.db.models import ModelConfig + + engine = create_engine( + f"sqlite:///{tmp_path / 'dup.db'}", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + SQLModel.metadata.create_all(engine) + _seed_duplicate_default_models(engine) + + monkeypatch.setattr(database, "engine", engine) + monkeypatch.setattr(database, "_dialect", SimpleNamespace(supports_partial_index=False)) + with pytest.raises(RuntimeError, match="多条默认模型"): + database._validate_default_model_invariant() + + # 清理到每租户一条后校验通过 + with Session(engine) as db: + row = db.exec(select(ModelConfig).where(ModelConfig.name == "m2")).one() + row.is_default = False + db.add(row) + db.commit() + database._validate_default_model_invariant() + + +def test_validate_default_model_invariant_skipped_when_partial_index_supported( + monkeypatch, tmp_path +) -> None: + """支持部分索引的后端:约束由 DB 唯一索引保证,启动校验直接跳过。""" + import app.db.database as database + import app.db.models # noqa: F401 + + engine = create_engine( + f"sqlite:///{tmp_path / 'skip.db'}", + connect_args={"check_same_thread": False}, + poolclass=StaticPool, + ) + SQLModel.metadata.create_all(engine) + _seed_duplicate_default_models(engine) # 即使存在脏数据形态也不查库 + + monkeypatch.setattr(database, "engine", engine) + monkeypatch.setattr(database, "_dialect", SimpleNamespace(supports_partial_index=True)) + database._validate_default_model_invariant() + + +# ---------- MySQL/Oracle 可移植性:全表 DDL 编译扫描 + 类型策略 ---------- + + +def test_all_tables_compile_on_mysql_and_oracle() -> None: + """42 张表在 mysql/oracle 方言下 DDL 全部可编译(JSON 列经 PortableJSON 降级)。""" + from sqlalchemy.dialects import mysql as mysql_dialect + from sqlalchemy.dialects import oracle as oracle_dialect + from sqlalchemy.schema import CreateTable + + import app.db.models # noqa: F401 - 注册全部表模型 + + tables = SQLModel.metadata.sorted_tables + assert len(tables) >= 40 + for table in tables: + assert str(CreateTable(table).compile(dialect=mysql_dialect.dialect())) + assert str(CreateTable(table).compile(dialect=oracle_dialect.dialect())) + + +def test_mysql_long_text_columns_are_not_varchar255() -> None: + """MySQL 对无长度 str 列默认 VARCHAR(255):长文本列必须显式 Text(抽验关键列)。""" + from sqlalchemy.dialects import mysql as mysql_dialect + + from app.db.models import ( + AgentProfile, + ChannelBinding, + ChannelDelivery, + KnowledgeChunk, + MemoryRecord, + Message, + ModelConfig, + PersonaConfig, + Tool, + UserAvatar, + ) + + dialect = mysql_dialect.dialect() + long_columns = [ + (Message, "content"), + (KnowledgeChunk, "content"), + (PersonaConfig, "system_prompt"), + (AgentProfile, "persona_prompt"), + (ChannelDelivery, "text"), + (ChannelBinding, "credentials_enc"), + (MemoryRecord, "content"), + (ModelConfig, "api_key_encrypted"), + (Tool, "url"), + (Tool, "description"), + # 头像 base64 ~2.8MB:MySQL 须 MEDIUMTEXT(超 TEXT 64KB 上限) + (UserAvatar, "data_url"), + ] + for table, column in long_columns: + compiled = str(table.__table__.c[column].type.compile(dialect=dialect)) + assert "TEXT" in compiled.upper(), (table.__tablename__, column, compiled) + assert "VARCHAR(255)" not in compiled.upper(), (table.__tablename__, column, compiled) + + +def test_portable_json_roundtrip_and_oracle_fallback() -> None: + """PortableJSON:pg/sqlite/mysql 走原生 JSON;oracle/dm 序列化进 CLOB 并还原。""" + from sqlalchemy.dialects import oracle as oracle_dialect + from sqlalchemy.dialects import postgresql as pg_dialect + + from app.db.models import PortableJSON + + portable = PortableJSON() + oracle = oracle_dialect.dialect() + pg = pg_dialect.dialect() + + value = {"key": ["a", 1], "中文": True} + # oracle:序列化为文本,读出还原 + bound = portable.process_bind_param(value, oracle) + assert isinstance(bound, str) + assert portable.process_result_value(bound, oracle) == value + # pg:原样透传(由原生 JSON 类型处理) + assert portable.process_bind_param(value, pg) is value + assert portable.process_result_value(value, pg) is value + # None 两方言都透传 + assert portable.process_bind_param(None, oracle) is None + assert portable.process_result_value(None, oracle) is None + # oracle 下 DDL 类型为 CLOB,pg 下为 JSON + assert "CLOB" in str(portable.compile(dialect=oracle)).upper() + assert "JSON" in str(portable.compile(dialect=pg)).upper() diff --git a/backend/tests/test_feishu_manager.py b/backend/tests/test_feishu_manager.py index 9b80a0060..a1589c7df 100644 --- a/backend/tests/test_feishu_manager.py +++ b/backend/tests/test_feishu_manager.py @@ -11,7 +11,7 @@ class FakeSupervisor: def __init__(self, **kwargs): - self.database_path = kwargs["database_path"] + self.database_url = kwargs["database_url"] self.started = [] self.stopped = [] self.states = {} @@ -62,6 +62,8 @@ def test_manager_reconciles_pause_resume_revision_and_shutdown(tmp_path) -> None channel="feishu", status="active", config_revision=4, + credentials_enc="enc", + config_json={"app_id": "cli_test", "bot_open_id": "ou_test"}, ) ) db.commit() @@ -113,6 +115,8 @@ def test_manager_keeps_tracking_binding_when_stop_times_out(tmp_path) -> None: channel="feishu", status="active", config_revision=1, + credentials_enc="enc", + config_json={"app_id": "cli_test", "bot_open_id": "ou_test"}, ) ) db.commit() @@ -154,6 +158,8 @@ def test_manager_writes_disconnected_truth_and_accepts_backoff_as_stopped(tmp_pa channel="feishu", status="active", config_revision=1, + credentials_enc="enc", + config_json={"app_id": "cli_test", "bot_open_id": "ou_test"}, ) ) db.commit() @@ -193,6 +199,8 @@ def test_pause_starts_stop_without_consuming_wait_deadline(tmp_path) -> None: channel="feishu", status="active", config_revision=1, + credentials_enc="enc", + config_json={"app_id": "cli_test", "bot_open_id": "ou_test"}, ) ) db.commit() @@ -302,3 +310,29 @@ def test_feishu_adapter_is_registered() -> None: channels._ensure_adapters_registered() assert get_channel_adapter("feishu").__class__.__name__ == "FeishuAdapter" + + +# ---------- 数据库 URL 透传(P2 方言化) ---------- + + +def test_manager_accepts_non_sqlite_database_url() -> None: + """非 SQLite 不再报"仅支持文件 SQLite":完整 URL(密码不遮蔽)透传给子进程。""" + engine = create_engine("postgresql+psycopg://user:secret@db.internal:5432/staffdeck") + manager = FeishuProcessManager(db_engine=engine, reconcile_seconds=60) + assert ( + manager._database_url + == "postgresql+psycopg://user:secret@db.internal:5432/staffdeck" + ) + + +def test_manager_rejects_memory_sqlite() -> None: + """内存 SQLite 子进程无法共享,仍然拒绝(与方言无关的物理限制)。""" + from sqlalchemy.pool import StaticPool + + engine = create_engine("sqlite://", poolclass=StaticPool) + try: + FeishuProcessManager(db_engine=engine) + except RuntimeError as error: + assert "内存数据库" in str(error) + else: + raise AssertionError("内存 SQLite 必须拒绝(子进程无法共享)") diff --git a/backend/tests/test_feishu_process_spike.py b/backend/tests/test_feishu_process_spike.py index eac344d6e..db39463d6 100644 --- a/backend/tests/test_feishu_process_spike.py +++ b/backend/tests/test_feishu_process_spike.py @@ -24,7 +24,8 @@ from lark_channel.ws.pb.pbbp2_pb2 import Frame from app.channels.feishu_process import ConnectorState, FeishuProcessSupervisor -from feishu_connector_worker import BindingProcessLock, binding_lock_path +from app.db.dialect import get_dialect +from feishu_connector_worker import BindingProcessLock, binding_lock_key SDK_RUNTIME = "feishu_connector_worker:run_sdk_contract_runtime" IDLE_RUNTIME = "feishu_connector_worker:run_idle_contract_runtime" @@ -32,6 +33,23 @@ UNSTOPPABLE_RUNTIME = "feishu_connector_worker:run_unstoppable_contract_runtime" +def _binding_lock_free(database: Path, binding_id: str) -> bool: + """方言探测 binding 锁是否空闲(与父进程同语义:短会话 try-acquire + release)。""" + from sqlmodel import Session, create_engine + + engine = create_engine(f"sqlite:///{database}") + try: + dialect = get_dialect(engine.url.get_backend_name()) + key = binding_lock_key(binding_id) + with Session(engine) as session: + if not dialect.acquire_advisory_lock(session, key): + return False + dialect.release_advisory_lock(session, key) + return True + finally: + engine.dispose() + + class _LocalFeishuServer: def __init__(self) -> None: self.loop = asyncio.new_event_loop() @@ -851,9 +869,7 @@ def test_child_owned_lock_is_released_after_parent_pipe_closes(tmp_path: Path, m time.sleep(0.01) record.process.join(timeout=1.0) assert not record.process.is_alive() - lock = BindingProcessLock(binding_lock_path("binding-orphan", database)) - assert lock.acquire() - lock.release() + assert _binding_lock_free(database, "binding-orphan") assert supervisor.stop(timeout=2.0) @@ -1170,10 +1186,7 @@ def test_replace_binding_stops_old_generation_before_revision_commit( commit_observations: list[tuple[int | None, bool]] = [] def commit_revision() -> bool: - lock = BindingProcessLock(Path(old.spec.binding_lock_path)) - lock_free = lock.acquire() - if lock_free: - lock.release() + lock_free = _binding_lock_free(tmp_path / "replace.db", "binding-replace") commit_observations.append((old.exit_code, lock_free)) return True @@ -1303,12 +1316,12 @@ def test_stop_does_not_mark_closed_until_binding_locks_are_free( original_lock_check = supervisor._binding_lock_is_free checks = 0 - def first_check_blocked(path: Path) -> bool: + def first_check_blocked(binding_id: str) -> bool: nonlocal checks checks += 1 if checks == 1: return False - return original_lock_check(path) + return original_lock_check(binding_id) monkeypatch.setattr(supervisor, "_binding_lock_is_free", first_check_blocked) assert not supervisor.stop(timeout=2.0) diff --git a/backend/tests/test_model_configs_api.py b/backend/tests/test_model_configs_api.py index 8d3324e79..b455c8d3f 100644 --- a/backend/tests/test_model_configs_api.py +++ b/backend/tests/test_model_configs_api.py @@ -421,7 +421,7 @@ def test_switching_default_clears_existing_row_before_setting_new(tmp_path) -> N with _db(tmp_path) as db: db.exec( text( - "CREATE UNIQUE INDEX uq_model_configs_tenant_default " + "CREATE UNIQUE INDEX IF NOT EXISTS uq_model_configs_tenant_default " "ON model_configs(tenant_id) WHERE is_default = 1" ) ) @@ -657,13 +657,7 @@ def test_concurrent_initial_verification_activates_only_one_default(tmp_path, mo connect_args={"check_same_thread": False, "timeout": 30}, ) SQLModel.metadata.create_all(engine) - with engine.begin() as conn: - conn.execute( - text( - "CREATE UNIQUE INDEX uq_model_configs_tenant_default " - "ON model_configs(tenant_id) WHERE is_default = 1" - ) - ) + # 部分唯一索引 uq_model_configs_tenant_default 已由 models.py 按方言 DDL 创建 with Session(engine) as db: db.add(Tenant(id="tenant_a", name="Tenant A")) for model_id in ("model_a", "model_b"): diff --git a/backend/tests/test_opengauss_dialect.py b/backend/tests/test_opengauss_dialect.py new file mode 100644 index 000000000..c1bdd4f53 --- /dev/null +++ b/backend/tests/test_opengauss_dialect.py @@ -0,0 +1,95 @@ +"""openGauss(高斯)SQLAlchemy 方言兼容层回归测试. + +覆盖:URL scheme 注册、版本串解析回退(openGauss 的 version() 不是 PG 格式)、 +client_encoding=utf8 注入、应用方言层能力位,以及对上游 PG 版本串不产生回归。 +""" + +from __future__ import annotations + +from sqlalchemy import make_url +from sqlalchemy.dialects import registry +from sqlalchemy.dialects.postgresql.psycopg import PGDialect_psycopg + +from app.db import opengauss +from app.db.dialect import OpenGaussDialect, ensure_driver_available, get_dialect + + +class _FakeResult: + def __init__(self, value): + self._value = value + + def scalar(self): + return self._value + + +class _FakeConnection: + """最小连接桩:只提供 _get_server_version_info 用到的 exec_driver_sql。""" + + def __init__(self, version_string): + self._version_string = version_string + + def exec_driver_sql(self, statement): + return _FakeResult(self._version_string) + + +def test_opengauss_sqlalchemy_dialect_registered() -> None: + cls = registry.load("opengauss.psycopg") + assert cls is opengauss.OpenGaussPGDialect + assert issubclass(cls, PGDialect_psycopg) + + +def test_version_parse_falls_back_for_opengauss_string() -> None: + dialect = opengauss.OpenGaussPGDialect() + # openGauss 5.0 的真实返回格式(带 "(" 前缀,PG 方言正则无法解析) + version = "(openGauss 5.0.0 build ) compiled at 2023-04-18 10:27:05 commit 0 last mr" + assert dialect._get_server_version_info(_FakeConnection(version)) == (9, 2, 4) + + +def test_version_parse_keeps_postgresql_strings() -> None: + dialect = opengauss.OpenGaussPGDialect() + pg_version = "PostgreSQL 16.3 (Debian 16.3-1.pgdg120+1) on aarch64-unknown-linux-gnu" + parsed = dialect._get_server_version_info(_FakeConnection(pg_version)) + assert parsed[0] == 16 + + +def test_app_dialect_layer_entry() -> None: + dialect = get_dialect("opengauss") + assert isinstance(dialect, OpenGaussDialect) + assert dialect.name == "opengauss" + assert dialect.supports_partial_index is True + assert dialect.session_scoped_advisory_lock is True + kwargs = dialect.engine_kwargs("opengauss+psycopg://user:secret@db.internal/postgres") + assert kwargs["connect_args"] == {"client_encoding": "utf8"} + assert kwargs["pool_pre_ping"] is True + + +def test_ensure_driver_available_accepts_opengauss_url() -> None: + # psycopg 为 [postgres] 可选依赖;开发/CI 装 dev extra 时可能缺失,缺失则跳过 + try: + import psycopg # noqa: F401 + except ImportError: # pragma: no cover + import pytest + + pytest.skip("psycopg not installed ([postgres] extra)") + ensure_driver_available(make_url("opengauss+psycopg://user:secret@db.internal/postgres")) + + +def test_ensure_driver_available_message_for_missing_driver(monkeypatch) -> None: + from app.db import dialect as dialect_module + + monkeypatch.setitem( + dialect_module._OPTIONAL_DRIVERS, + "opengauss", + ("skilldeck_missing_driver_for_test", 'pip install "skill-agent-loop-backend[postgres]"'), + ) + try: + ensure_driver_available(make_url("opengauss+psycopg://user:secret@db.internal/postgres")) + except RuntimeError as exc: + assert "postgres" in str(exc) + else: # pragma: no cover + raise AssertionError("missing driver must raise RuntimeError") + + +def test_opengauss_dialect_declares_statement_cache() -> None: + # SQLAlchemy 2.x 编译缓存需要方言显式声明,避免告警 + assert getattr(opengauss.OpenGaussPGDialect, "supports_statement_cache", False) is True diff --git a/backend/uv.lock b/backend/uv.lock index 4f39af45a..4cda70756 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14'", @@ -148,6 +148,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, ] +[[package]] +name = "alembic" +version = "1.20.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mako" }, + { name = "sqlalchemy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/93/1c/00909e0fbebad2121d916fdcab044cae988146680e9ee4387ba25fef8747/alembic-1.20.1.tar.gz", hash = "sha256:83490def1f723413db5096591f7609ac52544805be93849170088ed04f5a2e0b", size = 2103576, upload-time = "2026-10-22T03:24:35.93Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/3c/8740f5b4e1bd57333e4f84265b9b6363da4f7cf70f5622dd1e2fde7a0bd5/alembic-1.20.1-py3-none-any.whl", hash = "sha256:9970712cfb81ea26c8658d378aaa5b8f6ff9146e5bb111d70497c164016cf598", size = 270355, upload-time = "2026-10-22T03:24:37.667Z" }, +] + [[package]] name = "altgraph" version = "0.17.5" @@ -591,6 +605,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, ] +[[package]] +name = "dmpython" +version = "2.6.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/34/5095feb96a0ab197e82e1c395efc0574e91bba8572830aeeda3e4ceb9079/dmpython-2.6.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3b70c55a8773e3c461ffd3cdc55c5eff44c4cff3a978e10f52f439c734c4dd19", size = 11480453, upload-time = "2026-10-19T01:19:28.439Z" }, + { url = "https://files.pythonhosted.org/packages/5f/17/80392580af4d8d5a9c61d0b6e85ba37a7f7059013ae3933a0f762e928752/dmpython-2.6.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03c21ea904193e932e522003d1f0868fa2d27ad452177c209b483958f42855d0", size = 11683144, upload-time = "2026-10-19T01:20:17.451Z" }, + { url = "https://files.pythonhosted.org/packages/40/7e/4f07a3e29cbe01c6c509a74a80f718753e1038dfb00788f7b99e3beb0851/dmpython-2.6.1-cp311-cp311-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:4e7a6f1a99b637c23662728e9ff60e0384e2bbfda4aecbe44ec9815de1df4742", size = 11687132, upload-time = "2026-10-19T01:20:56.949Z" }, + { url = "https://files.pythonhosted.org/packages/67/19/6ce8d1f39bb849094f9f0f3184c7e4012f7686d2fa5acd8cd3bba4136233/dmpython-2.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:2363b00f5df3fa5c1f07bca14eae5ba3dc4127e2b3bed1197cd61e1f5cc4fdb4", size = 9224345, upload-time = "2026-10-19T01:21:23.238Z" }, + { url = "https://files.pythonhosted.org/packages/84/c9/b69f60dc452ef546ff8e73d655a8f8989ce36872a7860320f5cf0892a7f3/dmpython-2.6.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:4a0bceb097c437c92942b10b96c9202f1ecbbeeb7d47e3641869da73521bb51c", size = 11203824, upload-time = "2026-10-19T01:19:44.75Z" }, + { url = "https://files.pythonhosted.org/packages/fb/ff/3118daa18879a63ce4acaf36fd1e5789cd2a63eaca1d19e2744b8bf521eb/dmpython-2.6.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:13d93ea66a1d9a739599e3054f98de9abd1311476cb59d195658293b22c3ed03", size = 11343703, upload-time = "2026-10-19T01:22:03.404Z" }, + { url = "https://files.pythonhosted.org/packages/da/7d/846436e3590301da67394a46817f7ee4e5df0b59ca0e932c74ffa32a8524/dmpython-2.6.1-cp312-cp312-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98e060572b5847ddc713b55c0497b76cf4d75ae2126d98f174c4f19bd2458469", size = 11350855, upload-time = "2026-10-19T01:22:27.512Z" }, + { url = "https://files.pythonhosted.org/packages/88/aa/509a6594b1e4064920eb84fcdd92c1cae1c3faf3c501a6efcb72fe560bd7/dmpython-2.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:5c270dd51fb16c6e0c6a927018c207584ca6c15c9ac16461b71c795edb72291e", size = 9158537, upload-time = "2026-10-19T01:23:07.389Z" }, + { url = "https://files.pythonhosted.org/packages/45/56/12de6c191321fde76d40f47604fafb1d559238c996b05d6f09c18405c5d7/dmpython-2.6.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:96958af6d4c7365b12235ac33b841d05cc61e2eb1047bed823e6a8ad0b17d515", size = 11203150, upload-time = "2026-10-19T01:20:02.685Z" }, + { url = "https://files.pythonhosted.org/packages/73/c2/e184900605b805a61e59da75f31caeff7fb72ec4a0b06d54c2333cadd7d2/dmpython-2.6.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:45d7883ce2262ec27138f64a5e66e877b4330963e83b8d5440325b67c91eaf52", size = 11337431, upload-time = "2026-10-19T01:23:47.647Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b9/8a00142ac1b15348d1e17c0ab8a71914316e4f5245fe5e8f1dd61818dd64/dmpython-2.6.1-cp313-cp313-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:a8538ea58c679acbb1da1e003b063c434115465f7c9fbeadda919615d42a0369", size = 11338927, upload-time = "2026-10-19T01:24:29.474Z" }, + { url = "https://files.pythonhosted.org/packages/26/6c/8c49602bad4e444262b6675b2ebecca3e7b2a2132a776e0a389a43fa046b/dmpython-2.6.1-cp313-cp313-win_amd64.whl", hash = "sha256:4e8a78c8507279019342f582b18b3fa007cfec554e0056d0681c5a87b6a1f40b", size = 9158507, upload-time = "2026-10-19T01:24:46.407Z" }, + { url = "https://files.pythonhosted.org/packages/1c/b5/2289fb7d72d808e13b1fadf5afe0c661ffc2709d23ac54ade7b65d4a7210/dmpython-2.6.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d6e11e8fde6f12b4c1558fc4be77831bc6516a3789a6c4dba53f1bf8e0fc7952", size = 11204903, upload-time = "2026-10-19T01:20:25.688Z" }, + { url = "https://files.pythonhosted.org/packages/34/bf/44b6687478dc46e2d4f25aa19e094cd490aa0b9baa35a6d23e9ade4d9f47/dmpython-2.6.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:14153a9678c9227b00753a82e0f304be4497aeea2426a189e137a9aeebc03a9f", size = 11338461, upload-time = "2026-10-19T01:25:31.132Z" }, + { url = "https://files.pythonhosted.org/packages/df/6b/7a8e06d3501ce0775c156374075bae525a27c13cd98bde6d0df52108b845/dmpython-2.6.1-cp314-cp314-win_amd64.whl", hash = "sha256:8d7822e0b27bd0ec0f4fc3a1a2d6f4866b5884aadd0671b010dd5a0d9c1686aa", size = 9158442, upload-time = "2026-10-19T01:26:15.651Z" }, +] + [[package]] name = "docstring-parser" version = "0.18.0" @@ -825,8 +861,8 @@ name = "httpcore2" version = "2.13.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, - { name = "truststore", marker = "python_full_version < '3.12' or python_full_version >= '3.14' or sys_platform != 'emscripten'" }, + { name = "h11" }, + { name = "truststore" }, ] sdist = { url = "https://files.pythonhosted.org/packages/15/8c/e925b1c92018abb3a1863ce1549d76d2381e334d21d65d4ac8f65dabd78a/httpcore2-2.13.0.tar.gz", hash = "sha256:2adc8be4fb285fbcd6d894298db3b52c177e74b6674eda3a76bd36be3292a3db", size = 67740, upload-time = "2026-09-14T14:18:04.717Z" } wheels = [ @@ -1235,6 +1271,146 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" }, ] +[[package]] +name = "mako" +version = "1.4.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5a/09/e07c4b5579a79f4b16f8d4f29f6c54514ac787c4ad506b8c4f28a0e6b0bf/mako-1.4.3.tar.gz", hash = "sha256:cd6537fe88d5fec315c55c2f8529bc4ce7a9a352ad7db3eeaa6a66e2dd4ec37a", size = 412799, upload-time = "2026-09-22T20:54:31.509Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/a0/053d6af3e8f871e0073b4a36732d9e65be77a72e5434c31b94f6af78a6bb/mako-1.4.3-py3-none-any.whl", hash = "sha256:723296007c870bfd6b3f0c3230dba7198096e5269297ebf5e4eff9e7ffa39d4f", size = 80164, upload-time = "2026-09-22T20:54:33.128Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/81/09/4c59d56b8461ae8eb0d8ba34bb25b7e618547044679d58a82ef9b2479fc1/markupsafe-3.0.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6", size = 11658, upload-time = "2026-10-02T23:04:51.876Z" }, + { url = "https://files.pythonhosted.org/packages/a2/f0/d6613774d86fbf6d145751d43c59875e47a6f9f17daee0aef173bd36d90e/markupsafe-3.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f", size = 12050, upload-time = "2026-10-02T23:04:52.931Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f2/8f18e0b806eb13c1f8d07d917a720831ead54253a6dec011fbc78098a6f8/markupsafe-3.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b", size = 24363, upload-time = "2026-10-02T23:04:53.895Z" }, + { url = "https://files.pythonhosted.org/packages/60/ce/fa07dbe8a5675558fa36dea033e19995bc783de2dec5f540ccb9030b06aa/markupsafe-3.0.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df", size = 28525, upload-time = "2026-10-02T23:04:54.905Z" }, + { url = "https://files.pythonhosted.org/packages/85/40/be87c01f3868ec217f8a2015089d71c22c8c5a75324822e5ed1cdd87210d/markupsafe-3.0.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c", size = 24733, upload-time = "2026-10-02T23:04:56.229Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985, upload-time = "2026-10-02T23:04:57.521Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fc/e91352bb08c6a59da3ef0909d457bf95a5f5908fbf151b30a06d9dbcfbb4/markupsafe-3.0.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77", size = 22001, upload-time = "2026-10-02T23:04:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/5d/f8/bffee5e7d2a3deb59748a797650a48af7e672025cf641a79344a771ad106/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c", size = 23793, upload-time = "2026-10-02T23:04:59.686Z" }, + { url = "https://files.pythonhosted.org/packages/ed/59/b853d6628ecb4d658e1d637224846d5e9bb4adf4f8df97f3be9f29dce2ec/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749", size = 22640, upload-time = "2026-10-02T23:05:00.768Z" }, + { url = "https://files.pythonhosted.org/packages/09/b2/1506df394f0f075797c418d0301498f49e43be194e3ffcb49e6fe6ccf022/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed", size = 24074, upload-time = "2026-10-02T23:05:01.813Z" }, + { url = "https://files.pythonhosted.org/packages/c7/81/5ed69cda630ac69ef60d06c09ba5a7f84ff66a2e28cf986fd5614ab3c6e6/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786", size = 21563, upload-time = "2026-10-02T23:05:03.239Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048, upload-time = "2026-10-02T23:05:04.479Z" }, + { url = "https://files.pythonhosted.org/packages/c8/52/7632a53360671a9b750cdbabaf9cdd89f18b42248b8e4cb42c0b0296e459/markupsafe-3.0.4-cp312-cp312-win32.whl", hash = "sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237", size = 14108, upload-time = "2026-10-02T23:05:05.513Z" }, + { url = "https://files.pythonhosted.org/packages/3f/bf/62495e180b7000aaf30000fff849e933f74264638057176cf46852500adc/markupsafe-3.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7", size = 14303, upload-time = "2026-10-02T23:05:06.538Z" }, + { url = "https://files.pythonhosted.org/packages/c5/8e/4c24208776a65878d656996945aacfbfe010d3720d1a98fc0eb8491fc03b/markupsafe-3.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9", size = 14174, upload-time = "2026-10-02T23:05:07.617Z" }, + { url = "https://files.pythonhosted.org/packages/6d/18/4bc5ba32499e87bb2b0ef5b3a9bb9c00a131fa961ddf0be548cb550f548b/markupsafe-3.0.4-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1", size = 12786, upload-time = "2026-10-02T23:05:08.709Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6f/17f0c099bf25f3e31e63cc19244d9f6af861a9a4ab778c203997903cfdd0/markupsafe-3.0.4-cp313-cp313-android_24_x86_64.whl", hash = "sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1", size = 12510, upload-time = "2026-10-02T23:05:09.93Z" }, + { url = "https://files.pythonhosted.org/packages/11/af/1a141081b905036ee904ec4bd945e1f70b4e1b32d33c4e59e8cf1d58b247/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96", size = 11583, upload-time = "2026-10-02T23:05:10.884Z" }, + { url = "https://files.pythonhosted.org/packages/e7/0a/a89385ae590232622a03e091805cff12f24fabe6c11e0e8bae096cece81c/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148", size = 11801, upload-time = "2026-10-02T23:05:11.913Z" }, + { url = "https://files.pythonhosted.org/packages/ed/85/ea548dc013962eb73653124bc595635fbf9e0fa41d1f181a967ccb784dfb/markupsafe-3.0.4-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e", size = 11443, upload-time = "2026-10-02T23:05:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/cc/72/15f2e5ec9cf2eb00d5cdfe968d94e4156a7bd7303832c3f3b2c403a36839/markupsafe-3.0.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248", size = 11665, upload-time = "2026-10-02T23:05:13.829Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e0/4030bea613677e333c8a2c901fd405055f657f9d06acba5b7357984b6ef7/markupsafe-3.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72", size = 12061, upload-time = "2026-10-02T23:05:14.807Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a5/28b76a7449eb702966b88bef599e2360b411fbb3afeee8fe560939be06ec/markupsafe-3.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2", size = 24395, upload-time = "2026-10-02T23:05:15.909Z" }, + { url = "https://files.pythonhosted.org/packages/07/6c/21232811afc3a063b5e934b1ae2efda52f46154ec382f585149c020e61fe/markupsafe-3.0.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85", size = 27183, upload-time = "2026-10-02T23:05:16.976Z" }, + { url = "https://files.pythonhosted.org/packages/14/38/6ccdfa5b59049cb36fb80cbc80aee9cf1fc9bb77d1335ad435f2070b08cf/markupsafe-3.0.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde", size = 24772, upload-time = "2026-10-02T23:05:18.209Z" }, + { url = "https://files.pythonhosted.org/packages/63/e0/cec6865dfe88cb48fedd4b20aed6af5158e41092adcbf3e028bcc6ec2108/markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6", size = 23017, upload-time = "2026-10-02T23:05:19.286Z" }, + { url = "https://files.pythonhosted.org/packages/ee/76/6ed4940bb7648a9aac457c14f870cfdd5105f139a0fb1f29cd61fafa47d1/markupsafe-3.0.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f", size = 22036, upload-time = "2026-10-02T23:05:20.352Z" }, + { url = "https://files.pythonhosted.org/packages/a1/4f/ed476226d4fe46a09090a36025bf319296810028df55eb12f1253b540f3a/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39", size = 23786, upload-time = "2026-10-02T23:05:21.576Z" }, + { url = "https://files.pythonhosted.org/packages/9a/35/66ff30450e35ef5fba9ebc930c9411747e537fd9447b65e44f5007e2b84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee", size = 22672, upload-time = "2026-10-02T23:05:22.922Z" }, + { url = "https://files.pythonhosted.org/packages/32/0b/72f45ce4b4efcbca4b80cf1b06703eff0be8d37e82abb78f66c85a7ead1e/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2", size = 24107, upload-time = "2026-10-02T23:05:24.175Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/71776e5fdcba04614b384cc102e8a4198208579d896fd1394cb7cb9aa900/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46", size = 21615, upload-time = "2026-10-02T23:05:25.215Z" }, + { url = "https://files.pythonhosted.org/packages/ab/5f/801ce02a02e7aee0f784b1ec7843026178f6adeb9c93ac67eb1992a9a84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17", size = 23076, upload-time = "2026-10-02T23:05:26.423Z" }, + { url = "https://files.pythonhosted.org/packages/4a/85/c43776625428f3bb4a61e8633940400e3efe6409e3c6f5bff26de5e45618/markupsafe-3.0.4-cp313-cp313-win32.whl", hash = "sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0", size = 14118, upload-time = "2026-10-02T23:05:27.716Z" }, + { url = "https://files.pythonhosted.org/packages/6f/36/163da64de88a13db79214ef75fa041be7fa13bdb42261cf5b7484de14bfb/markupsafe-3.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5", size = 14313, upload-time = "2026-10-02T23:05:28.749Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a8/9b662783ffaa1149221432a923cee562f78b9cbbb8baa3df9b3753e63e1e/markupsafe-3.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc", size = 14189, upload-time = "2026-10-02T23:05:29.917Z" }, + { url = "https://files.pythonhosted.org/packages/5c/c3/a944f3b0df22bd129e96915b9f4e98d2eeca6516687d7618304a966c3c74/markupsafe-3.0.4-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed", size = 12787, upload-time = "2026-10-02T23:05:30.971Z" }, + { url = "https://files.pythonhosted.org/packages/d4/d6/a44863f69d88b6c7e27889108f70d47aed259edf89d5df3c5fca1eac87d6/markupsafe-3.0.4-cp314-cp314-android_24_x86_64.whl", hash = "sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59", size = 12525, upload-time = "2026-10-02T23:05:32.263Z" }, + { url = "https://files.pythonhosted.org/packages/17/8f/168ba80e532dd6a93f96f8f706f1ad41d7990b6e1aeedc1cc0d211a33497/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453", size = 11589, upload-time = "2026-10-02T23:05:33.251Z" }, + { url = "https://files.pythonhosted.org/packages/32/b3/aa2c95a574d3af39403a469b295886eb9b6d448da568cbebb5a2cbfdc2e5/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b", size = 11801, upload-time = "2026-10-02T23:05:34.315Z" }, + { url = "https://files.pythonhosted.org/packages/60/d0/34b810107d83840e768bf485de795893ebbae35b26ab061b487adfa0a692/markupsafe-3.0.4-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6", size = 11447, upload-time = "2026-10-02T23:05:35.302Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ab/2f8488f0f817a39fca068d2b17daf446bf5cdb3eae28c3720af534d873b4/markupsafe-3.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634", size = 11722, upload-time = "2026-10-02T23:05:36.363Z" }, + { url = "https://files.pythonhosted.org/packages/ad/40/e2d117b048d47282ade906fbfd92814cbee5647afc13fda88a3406039372/markupsafe-3.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f", size = 12061, upload-time = "2026-10-02T23:05:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a8/73a81135e85ba66217f5af7facb03bbb386807e1a729ab64532e4c802652/markupsafe-3.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9", size = 24434, upload-time = "2026-10-02T23:05:38.407Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ca/fa9216dd01efee2dfdacafe7df32b4d0170fbac694b0c258a193d6e53999/markupsafe-3.0.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f", size = 27183, upload-time = "2026-10-02T23:05:39.581Z" }, + { url = "https://files.pythonhosted.org/packages/fa/4e/a469509e538d37af51103b17b073126973f2b1cbf197ff32c7ddf025cfe5/markupsafe-3.0.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c", size = 24813, upload-time = "2026-10-02T23:05:40.671Z" }, + { url = "https://files.pythonhosted.org/packages/8f/db/d7282caf7ab03af44d5d6fdbaa019b35c7d7f1c90588b839c07cba640d6a/markupsafe-3.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300", size = 23049, upload-time = "2026-10-02T23:05:41.864Z" }, + { url = "https://files.pythonhosted.org/packages/30/f3/b6a425206e6964efda6acee544d0eb01d1501784d0b8e2dcc74986f33b17/markupsafe-3.0.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0", size = 22088, upload-time = "2026-10-02T23:05:43.014Z" }, + { url = "https://files.pythonhosted.org/packages/ea/8a/84d3582fc1f0d5bd466cdf2eebf175e172158a6e70701aacec1de1b35430/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977", size = 23846, upload-time = "2026-10-02T23:05:44.098Z" }, + { url = "https://files.pythonhosted.org/packages/1c/65/db101cce51b7ba4864ac491a9859d297dd1adf0e55b103fee9db9c47c527/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7", size = 22674, upload-time = "2026-10-02T23:05:45.23Z" }, + { url = "https://files.pythonhosted.org/packages/e0/49/ddee9813d71db0c7a5c9d97c832125e6758a0c844777f1cf076569bb0e22/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17", size = 24104, upload-time = "2026-10-02T23:05:46.398Z" }, + { url = "https://files.pythonhosted.org/packages/aa/0e/7d8518d726726870a2399d69fd30d0fa36c5e57a2132c336b58d7c491073/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c", size = 21637, upload-time = "2026-10-02T23:05:47.48Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b0/b505e8a361ba557dbf3b3aa7331ea39b00d2022a26e925ff8463b9714bb3/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4", size = 23081, upload-time = "2026-10-02T23:05:48.611Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ea/9cc3cea873f980c75cbdb6f4277ce30ee955de38be0b3d02f14c108e0698/markupsafe-3.0.4-cp314-cp314-win32.whl", hash = "sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c", size = 14272, upload-time = "2026-10-02T23:05:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/80/f0/5792ff768a410f93ee3f84fc19345295ffc352d2c936b424cb37e514714c/markupsafe-3.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe", size = 14501, upload-time = "2026-10-02T23:05:50.788Z" }, + { url = "https://files.pythonhosted.org/packages/5f/cf/3d074a8edffcc6899355232ff2543ae8d929733239596423b7db79698bc9/markupsafe-3.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a", size = 14364, upload-time = "2026-10-02T23:05:51.857Z" }, + { url = "https://files.pythonhosted.org/packages/d9/31/87ce42159aae2163cf3bbbd0c44bc87780510eecab1ea3859099aed95dcb/markupsafe-3.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2", size = 11759, upload-time = "2026-10-02T23:05:52.951Z" }, + { url = "https://files.pythonhosted.org/packages/5f/53/b047207eeb7752e960aca3eb1df5fb7eefa7dd4c62ac49bb156456c8a702/markupsafe-3.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977", size = 12096, upload-time = "2026-10-02T23:05:54.066Z" }, + { url = "https://files.pythonhosted.org/packages/ee/51/4326c88a13c7b755657d44b4bb986f8c3d9843ecba7e22d98661d87f9a57/markupsafe-3.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289", size = 25699, upload-time = "2026-10-02T23:05:55.15Z" }, + { url = "https://files.pythonhosted.org/packages/f2/bb/990581b7474bfcf2cf34bed6ba5ea23bd87adb9d671213d68e88620e7a6b/markupsafe-3.0.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe", size = 27804, upload-time = "2026-10-02T23:05:56.29Z" }, + { url = "https://files.pythonhosted.org/packages/6b/89/89491878c28e8291f5aa2fffe2c2d57230d10ae366d55dd810b840513d78/markupsafe-3.0.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a", size = 25912, upload-time = "2026-10-02T23:05:57.416Z" }, + { url = "https://files.pythonhosted.org/packages/30/77/680998b54efdea06fc114565cd739b6d059f826a0279219b218dfa750d29/markupsafe-3.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733", size = 23623, upload-time = "2026-10-02T23:05:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/ae/75/2709f5ac5de9467b40b10e2bb8f89cc63dfb74582e09aa734b1124a217de/markupsafe-3.0.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34", size = 23301, upload-time = "2026-10-02T23:05:59.94Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c8/39eadc6c5b14c9c7679bfb98f4d4c6a97863b5beb91839aca4d2d6e16e55/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978", size = 24950, upload-time = "2026-10-02T23:06:01.289Z" }, + { url = "https://files.pythonhosted.org/packages/1a/5e/01037f8a43e8ccb0bffb4fbdc5212db05bf080fdd7286cd392332d58128a/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc", size = 23330, upload-time = "2026-10-02T23:06:02.441Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f4/23e83ce0596bb0cbe670502d31df8f757bbd01a392aa486fa3b40d1ed399/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc", size = 25239, upload-time = "2026-10-02T23:06:03.579Z" }, + { url = "https://files.pythonhosted.org/packages/88/5b/3708897368073cc683d524750474f41a77d2986152c380dcc55b20fdf340/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932", size = 22767, upload-time = "2026-10-02T23:06:04.699Z" }, + { url = "https://files.pythonhosted.org/packages/c6/61/ebda1307864b409e6b3115757a3d4a09cca46cfb6cc65191b5de226b424b/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6", size = 23668, upload-time = "2026-10-02T23:06:05.9Z" }, + { url = "https://files.pythonhosted.org/packages/09/15/98075cceac3b5ba0dbb8e4762a847be967d2befc349a2cf2d0ac77f62c9d/markupsafe-3.0.4-cp314-cp314t-win32.whl", hash = "sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691", size = 14301, upload-time = "2026-10-02T23:06:07.109Z" }, + { url = "https://files.pythonhosted.org/packages/0b/a3/768b560fcc4156685cb563d922b217810cfa7bc135773367f62f1f9d2078/markupsafe-3.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464", size = 14526, upload-time = "2026-10-02T23:06:08.276Z" }, + { url = "https://files.pythonhosted.org/packages/93/63/da554b4c97a6b0ea3229ca7fe8cbfb620be81613d517f482e85958550537/markupsafe-3.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c", size = 14421, upload-time = "2026-10-02T23:06:09.402Z" }, + { url = "https://files.pythonhosted.org/packages/a9/30/54d11c8ca027114898cab97421fb39e4ffd9ddf47cdbc44df2ec76722da9/markupsafe-3.0.4-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65", size = 12791, upload-time = "2026-10-02T23:06:10.485Z" }, + { url = "https://files.pythonhosted.org/packages/10/6d/97c913e253a14bd3cd0e15a5c56d13203b823fa7ee32498342896a072dc4/markupsafe-3.0.4-cp315-cp315-android_24_x86_64.whl", hash = "sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163", size = 12527, upload-time = "2026-10-02T23:06:11.834Z" }, + { url = "https://files.pythonhosted.org/packages/26/f9/b86d032042a4d597d9e1997f0e5f63a3eedaf11258e0a05760b0a0a826ea/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92", size = 11602, upload-time = "2026-10-02T23:06:13.122Z" }, + { url = "https://files.pythonhosted.org/packages/f2/dc/73c14c1eedf0ac5fa3292ba43435e6c49d2c2050f33cebde541f8f4807f1/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a", size = 11817, upload-time = "2026-10-02T23:06:14.227Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/2c2fcaa5fcee22d72c7819c0d536fd181c74a688e6143845419579cd2863/markupsafe-3.0.4-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429", size = 11446, upload-time = "2026-10-02T23:06:15.574Z" }, + { url = "https://files.pythonhosted.org/packages/88/54/9e5ec76c62e6e2834d5a93623018c943e8b3bb41d663e3fd4c03303b9b85/markupsafe-3.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8", size = 11719, upload-time = "2026-10-02T23:06:16.701Z" }, + { url = "https://files.pythonhosted.org/packages/96/24/3ec292b44064c16229e064d770b2625bd8ea941aa61f44905a9fa44942c0/markupsafe-3.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97", size = 12075, upload-time = "2026-10-02T23:06:17.855Z" }, + { url = "https://files.pythonhosted.org/packages/aa/85/b64fdb1f304848518742136983c24e96d967bfb59a0ea160e92736901ab0/markupsafe-3.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b", size = 24656, upload-time = "2026-10-02T23:06:18.963Z" }, + { url = "https://files.pythonhosted.org/packages/9c/18/23997d4c65b355da6390d61cd56e0ab3befd6ba8dda25cb40c602bd0fa6b/markupsafe-3.0.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9", size = 27737, upload-time = "2026-10-02T23:06:20.117Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/35998dead3c6af88c38265a56e58100211f036234ab88eb2283fd4cbce44/markupsafe-3.0.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653", size = 25003, upload-time = "2026-10-02T23:06:21.284Z" }, + { url = "https://files.pythonhosted.org/packages/82/96/ef49135ce260db4ca4a12b119ed468449cd248db6b1468e2112b546d7a2e/markupsafe-3.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369", size = 23111, upload-time = "2026-10-02T23:06:22.524Z" }, + { url = "https://files.pythonhosted.org/packages/50/7d/83126e338bd88c17a220668235368ad719fd4638e426739858cbb8508f77/markupsafe-3.0.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19", size = 22403, upload-time = "2026-10-02T23:06:23.785Z" }, + { url = "https://files.pythonhosted.org/packages/83/dd/daf7e420de23c8206c365204e7b85e1251d8e19d34196a56336f316e5ed2/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e", size = 24083, upload-time = "2026-10-02T23:06:25.037Z" }, + { url = "https://files.pythonhosted.org/packages/19/3c/11eecdc06bc44ad5570350085b572ebf049e8f9a38d1ece6d76640b739cd/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811", size = 22931, upload-time = "2026-10-02T23:06:26.328Z" }, + { url = "https://files.pythonhosted.org/packages/0d/9e/ac0fd77f2a726e56ecc3ca0235d095feace1358d1b822406c2a2ef26a4dc/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea", size = 24299, upload-time = "2026-10-02T23:06:27.742Z" }, + { url = "https://files.pythonhosted.org/packages/d7/09/c6bd842ad58ff5b3bc76eeed7e9a42a6f11adc5d090ec697b72c9672731e/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916", size = 21948, upload-time = "2026-10-02T23:06:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/a3/46/82f586711fed61e86faa1ee1bc317d68cd45a10c8bdbe3f7d1fdf9026ad8/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741", size = 23150, upload-time = "2026-10-02T23:06:30.583Z" }, + { url = "https://files.pythonhosted.org/packages/19/2d/2dfdce99318abbfa26925195fbc17db188c46a1ec6457be121b6f9cfeb42/markupsafe-3.0.4-cp315-cp315-win32.whl", hash = "sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b", size = 14269, upload-time = "2026-10-02T23:06:31.949Z" }, + { url = "https://files.pythonhosted.org/packages/5b/ec/6000fd82e8791e58fcd0456ec20f098957e2b03d5ed02eb73241a577c0ba/markupsafe-3.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214", size = 14496, upload-time = "2026-10-02T23:06:33.258Z" }, + { url = "https://files.pythonhosted.org/packages/bc/66/e73bd5016421d5d6e2fb6de7dd609f9de020942ac8c626526bd8c6eeaf82/markupsafe-3.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67", size = 14361, upload-time = "2026-10-02T23:06:34.539Z" }, + { url = "https://files.pythonhosted.org/packages/90/df/cb8c3dc98d313a951df2f8968f44e4cb5643df6d3cab749a530ce2f7d972/markupsafe-3.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad", size = 11760, upload-time = "2026-10-02T23:06:35.807Z" }, + { url = "https://files.pythonhosted.org/packages/d6/bb/4af9b3ca0753d654ac75f9531d5bd741bb77ca6e696f36807c475ffc099a/markupsafe-3.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99", size = 12108, upload-time = "2026-10-02T23:06:37.089Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d4/b56429313aee5fd59b079c3df5615299959e25e7113eb6d8caadbdd7d38a/markupsafe-3.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002", size = 25762, upload-time = "2026-10-02T23:06:38.419Z" }, + { url = "https://files.pythonhosted.org/packages/65/f5/34c181e891aa4f7d59c918584672e0c5eb7fffe76c1387d1246008bf4081/markupsafe-3.0.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e", size = 28400, upload-time = "2026-10-02T23:06:39.819Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b5/ad14694fd0ac9a5ce30bc6498f2999378f418583dd1679cca5a1b512957e/markupsafe-3.0.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c", size = 25946, upload-time = "2026-10-02T23:06:41.381Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a8/26b606445387d0ceb1eb1f21840094b84e4e3c3c3983d80d10b89823b490/markupsafe-3.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8", size = 23634, upload-time = "2026-10-02T23:06:42.748Z" }, + { url = "https://files.pythonhosted.org/packages/39/a2/b8814de672f1f0094d498bf646f2fec9d6356b503d28ef500b71c5095377/markupsafe-3.0.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe", size = 23488, upload-time = "2026-10-02T23:06:44.176Z" }, + { url = "https://files.pythonhosted.org/packages/db/c7/287223376fb73335a3cc5d6eb22c6ab01358cf33945a9c39c06b9dac3f4b/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2", size = 25037, upload-time = "2026-10-02T23:06:45.646Z" }, + { url = "https://files.pythonhosted.org/packages/f9/29/4df8355e313426d19e62ba33e0253c009ca12a0894ee77d67fa67255361c/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38", size = 23543, upload-time = "2026-10-02T23:06:47.264Z" }, + { url = "https://files.pythonhosted.org/packages/71/e5/8377731e8495668dcc768f645e717df18318c841edaf023a99395f6da9b4/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494", size = 25282, upload-time = "2026-10-02T23:06:48.795Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5f/373456e37ceb1478d657d6fe769cbe0a39f0a8dfc1548eeb19c471eefdd9/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d", size = 22993, upload-time = "2026-10-02T23:06:50.31Z" }, + { url = "https://files.pythonhosted.org/packages/d7/93/2cbd5628435afb6f541bbaced4bce0c2edac4b09a142e6e928b8b0da9858/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894", size = 23712, upload-time = "2026-10-02T23:06:51.759Z" }, + { url = "https://files.pythonhosted.org/packages/81/99/157e10966b033b363aeda5263e82596ee232a0b1d082fdbf90aa417ff083/markupsafe-3.0.4-cp315-cp315t-win32.whl", hash = "sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78", size = 14300, upload-time = "2026-10-02T23:06:53.241Z" }, + { url = "https://files.pythonhosted.org/packages/33/05/55884815414c9706a23deca150b72c25a62109e65b0b6ce232077802c719/markupsafe-3.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c", size = 14522, upload-time = "2026-10-02T23:06:54.729Z" }, + { url = "https://files.pythonhosted.org/packages/92/f9/ecbde7149e95b8a0f18e16d5d747f7dc06049d5da2e4f77f6f5e4a1f46a8/markupsafe-3.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba", size = 14417, upload-time = "2026-10-02T23:06:56.246Z" }, +] + [[package]] name = "mcp" version = "2.2.0" @@ -1615,6 +1791,86 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, ] +[[package]] +name = "psycopg" +version = "3.3.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/11/c8/3bd7e09770a5829eb26667df5e49f084d78bd106d5949ade9447288a8e18/psycopg-3.3.8.tar.gz", hash = "sha256:86c135a9a6f5e98404975c5787e620bf436a7807e088baebd1b20fa48d3b4b4f", size = 168902, upload-time = "2026-11-04T09:44:26.142Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/5c/50a0b0796ccb69b11934f7c5758051c08019bda2fafb417501109fffd569/psycopg-3.3.8-py3-none-any.whl", hash = "sha256:ca50af6072ba9ea6866f33021975230c2555d7bfdb9d8f94ca3af5c3d1bf2167", size = 216209, upload-time = "2026-11-04T09:37:35.491Z" }, +] + +[package.optional-dependencies] +binary = [ + { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, +] + +[[package]] +name = "psycopg-binary" +version = "3.3.8" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/04/674c4048729b5ad90d1036c7c6c4ce13d2e05ca3d16ed68368e00c092e71/psycopg_binary-3.3.8-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:42718d7e5732aa1feb0a7f0ff7e0404fd080528bd4694b40b31ef0b146eda8e1", size = 4731192, upload-time = "2026-11-04T09:38:56.473Z" }, + { url = "https://files.pythonhosted.org/packages/03/6d/98b98c95dae1c53e52dac2301093b89640afb178ebfed745dc8465a3d64d/psycopg_binary-3.3.8-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1126ff5eae645a304e6ca94e1c79cc19249fb54517b923ee5862badd2fabb334", size = 4779497, upload-time = "2026-11-04T09:39:00.917Z" }, + { url = "https://files.pythonhosted.org/packages/77/e9/8aa5b11a272d97c7240796c16bce5f98c3ab07fbb2643e60432fc446d0f6/psycopg_binary-3.3.8-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:281d0e891fa8c2bb231a97a5a57522cc2a9664c3f77b9fb007d2719bc1afd29e", size = 5602158, upload-time = "2026-11-04T09:39:07.903Z" }, + { url = "https://files.pythonhosted.org/packages/cd/33/28dde854cf3175e0e68609e8b3b5f4e3c40cdf14c08ae1f8d66930451191/psycopg_binary-3.3.8-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:39bc3b42e6486ae8ace820df93b00dce4858338e8a428d14d8e71130e852bab1", size = 5271229, upload-time = "2026-11-04T09:39:14.207Z" }, + { url = "https://files.pythonhosted.org/packages/48/7b/f57955d6cb1a5b1b530faeb12df2eaa3f3eff14626d6862a7b5de4b49c59/psycopg_binary-3.3.8-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4bedd0fbbbebe0c0f66b34c3f6be972ce38357ce3451510e1dcf5025f7011dba", size = 6864844, upload-time = "2026-11-04T09:39:19.686Z" }, + { url = "https://files.pythonhosted.org/packages/91/50/3fa8790d539f14e8e10f904fca22226555d7fff773854974d163cfa47bdd/psycopg_binary-3.3.8-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fe26e72b87ca280e538f4f78d1a956df0ae6ed51aab73ccc4c1dcf6f25256438", size = 5111039, upload-time = "2026-11-04T09:39:24.07Z" }, + { url = "https://files.pythonhosted.org/packages/57/a4/12fda52aa11297ca0e3aec5b6433232a42dc8e6c29a2413b4470a7b69bd3/psycopg_binary-3.3.8-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5a3925d0c67b0452db066d97d0452af012e7bd2fdf8e6ab4ab0392df8906a6e1", size = 4631127, upload-time = "2026-11-04T09:39:29.372Z" }, + { url = "https://files.pythonhosted.org/packages/8e/6c/1fd9639c6f27f527ac991ad9cf827ddcdd524e0482085fd0d9acacba23d3/psycopg_binary-3.3.8-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d4de096987b9f7c346879e164637de91a66067378b1ee4b49f07d1bac0e2847a", size = 4324090, upload-time = "2026-11-04T09:39:34.332Z" }, + { url = "https://files.pythonhosted.org/packages/f5/58/dd3a5fa5d23b42e0cb466f3d4a9e9759399dcf03a2a2b7a6a3e4cd67197f/psycopg_binary-3.3.8-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:c3ac86af1a7ac65fe3461d831e8bc9fa62bc247ef1b73d58e9dd4ed406be4bfd", size = 4051699, upload-time = "2026-11-04T09:39:38.424Z" }, + { url = "https://files.pythonhosted.org/packages/e6/01/9b20b20d240c075b5fb7e4b2baf4c70cdedd34806a87de65537ec809da19/psycopg_binary-3.3.8-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:09676448a9bbc5c09ce8d578a6958a0bb8175e63c94edf6d88a62d2b07fadd23", size = 4354989, upload-time = "2026-11-04T09:39:43.509Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f1/e2b149237e5c7ea559deba7ffa9527cb11866424933c1418d22fc5f81590/psycopg_binary-3.3.8-cp311-cp311-win_amd64.whl", hash = "sha256:ed65d1b32a7f9684ab682296ac7cac1dd972bb8d86c9336753bc915efc3515f4", size = 3636517, upload-time = "2026-11-04T09:39:49.676Z" }, + { url = "https://files.pythonhosted.org/packages/6c/e8/10db627d04a32afbba6e4a6aaf192c0ae88321e44669c0224ee88e11ad68/psycopg_binary-3.3.8-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a09aa2ba7927e9b11bd5bddb6d33cec274235d6f54f1ab777ed71c932cfc8d72", size = 4710638, upload-time = "2026-11-04T09:39:59.55Z" }, + { url = "https://files.pythonhosted.org/packages/67/f5/ddfd762133fda147c8779f3014dfa5404868aea1d3f4cc6f6bc5b8c3a076/psycopg_binary-3.3.8-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e0972d8de5a0d855d76624f559a6ce5dd068fb4bbfa01e1d7cf929e6800dc4f0", size = 4773113, upload-time = "2026-11-04T09:40:04.058Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f5/d9944976536d4f94ce36f4cc9eec43be66a227159d91cab6cec2c36fe109/psycopg_binary-3.3.8-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:41c31b175084a85232b6ea5f8eb474491b6c963302c69b46fa2ed60afb888b62", size = 5561093, upload-time = "2026-11-04T09:40:09.27Z" }, + { url = "https://files.pythonhosted.org/packages/c7/04/aef0b229adc200259d3aec4c8ba17a2ff233505dec8712f37f7168e45c06/psycopg_binary-3.3.8-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a7cdba018e4decf3837793c1e18dbe3dd71709adef54892ab83d81c00e866dc3", size = 5241603, upload-time = "2026-11-04T09:40:14.778Z" }, + { url = "https://files.pythonhosted.org/packages/95/f3/eda400c9b76805996e3d7197fc0b0b3c7068311f623b72f71f20f1bfe620/psycopg_binary-3.3.8-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:804041b79916b0e8021a1130650d724741eff1e81ccec8133abf357b4d284a24", size = 6838293, upload-time = "2026-11-04T09:40:22.645Z" }, + { url = "https://files.pythonhosted.org/packages/78/7a/dfc5c75661c4677b853f91c52273904b1ab24ae8272e14bb74644dc74d10/psycopg_binary-3.3.8-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9daff4d6257969b02678943d62bfd83b971004f6efef68d5b767ac69c2222751", size = 5073947, upload-time = "2026-11-04T09:40:29.461Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/fedb9ddef0ae0ee03bcbb4f2ced765f3cf7a82a0836e4bc175b775949ecf/psycopg_binary-3.3.8-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e8f1addbaec62c9e2bf5b3ae4b32a20c793c06de7d57471f6509a127f1c902f4", size = 4602727, upload-time = "2026-11-04T09:40:36.744Z" }, + { url = "https://files.pythonhosted.org/packages/3f/ac/bd948283a127e03df0d89d19b81c02de54b3176b9d068ebe2a9ac0acf628/psycopg_binary-3.3.8-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:5f51d97b67276e90cda022ad363eca61dbe855dbb5342e358469006d4b5254df", size = 4283009, upload-time = "2026-11-04T09:40:42.027Z" }, + { url = "https://files.pythonhosted.org/packages/1c/8a/d8fdd24b3356d188e84892663d403d4f2ae02326f342b0806cfdd9e0433e/psycopg_binary-3.3.8-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:aa7af0d2d1194b65b8c4d0056c5607de6c38fb6a295f04087d17e1c9d2d11fba", size = 4013053, upload-time = "2026-11-04T09:40:47.155Z" }, + { url = "https://files.pythonhosted.org/packages/e7/fc/ca06d048860f210d84b2ea7d49d15ed8780143454619c371d91868077d05/psycopg_binary-3.3.8-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f09cb4e7744522d71048a8998ff841c7af942a61ffbd4142a140b42d89b950fe", size = 4325780, upload-time = "2026-11-04T09:40:52.139Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c7/d96e8ff851d1f83e5cd6ec57e9a7f6eb9fb526ecdb4bbbf017a5066e9199/psycopg_binary-3.3.8-cp312-cp312-win_amd64.whl", hash = "sha256:ec6773395189417c92102b34c77ed299f6111fbbc37d50d4fa12ab819f763669", size = 3619067, upload-time = "2026-11-04T09:40:59.475Z" }, + { url = "https://files.pythonhosted.org/packages/04/27/3b2dc3eb98d32ac87746fb327e889404e611fc017397b3b83057de38a701/psycopg_binary-3.3.8-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0d483014dde0bd5404801aa91ebbd7912006065dd8d244a962f228fe44bfc08b", size = 4715357, upload-time = "2026-11-04T09:41:07.346Z" }, + { url = "https://files.pythonhosted.org/packages/72/fb/2bee345580b59e749078da581d7b0fc16ec9dec53a57225d698da391d1bc/psycopg_binary-3.3.8-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6ff02f23b7d95de68f42d5ebe91374540d3d31851d83d9cd37e6e71a5dbd0bcd", size = 4775924, upload-time = "2026-11-04T09:41:11.838Z" }, + { url = "https://files.pythonhosted.org/packages/53/4f/b1569176285bc74b031eb287bc9dba75fcb22aa3be9a3faee5fa593b5f88/psycopg_binary-3.3.8-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:31dd2597df303d22a2cabf73c40bb05afaf4ca1394e22935b97f627d4968c87d", size = 5561131, upload-time = "2026-11-04T09:41:18.604Z" }, + { url = "https://files.pythonhosted.org/packages/94/bb/89ce891e7897638df5eb34c3e7c36143c59933fd6602e61a7b9b8e905644/psycopg_binary-3.3.8-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f72c18d75d16500fe2f7f300945d68fba9dbb883aef20ba4be0c386afbbf2e9", size = 5243034, upload-time = "2026-11-04T09:41:27.936Z" }, + { url = "https://files.pythonhosted.org/packages/e2/55/a676f32b29096651f9725e9cae78a033bcf88697df4e1d31b7b77589be6c/psycopg_binary-3.3.8-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:00c226f718901ce022bcee2e0779dc2f0a6d8bcedd5a3818e21ff25564efaa97", size = 6837999, upload-time = "2026-11-04T09:41:37.213Z" }, + { url = "https://files.pythonhosted.org/packages/dd/00/e83def05e558d011bcddb2cba10d7087b92980a4abc387f4c58cad75d6b4/psycopg_binary-3.3.8-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c3a8420317a3b3910a08b77a952ef8f8051da61622c6a2e03fc51b75761c6acf", size = 5076374, upload-time = "2026-11-04T09:41:42.432Z" }, + { url = "https://files.pythonhosted.org/packages/55/75/46a29692f7b87d96efc675087fe4495d01d2811720c16abce351ec78547a/psycopg_binary-3.3.8-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a565d8446b59d26dcf75b08d3ccd4e85b750edba9e53a396cb7a4652d7cbc9e8", size = 4603132, upload-time = "2026-11-04T09:41:49.434Z" }, + { url = "https://files.pythonhosted.org/packages/eb/cc/e3bd0dc83e52aff75bb8131f200e336f6d8a5642de60cc96694eb53540af/psycopg_binary-3.3.8-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:6891b6d9d25103c31411b50f83f9a8aba63f4cbcc63b009f461c115bfaf7b78d", size = 4282092, upload-time = "2026-11-04T09:41:54.868Z" }, + { url = "https://files.pythonhosted.org/packages/9b/e1/db358ef11a5e5b7590aba3dfa2ef7af685210e27f37a2ae3b93c5af99bc4/psycopg_binary-3.3.8-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:7d2b484e8ced7c3292e811d28087814467aecd3ef19badb64ed45a0f5fd78bf8", size = 4014488, upload-time = "2026-11-04T09:42:03.348Z" }, + { url = "https://files.pythonhosted.org/packages/0d/6d/45f8401f1b1dd65303892a786d190814279d212a663f840572da3b73084d/psycopg_binary-3.3.8-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:522acdc8a71a042b407851658eb1da85fe09c78b222b2233faef7da3385a757b", size = 4326427, upload-time = "2026-11-04T09:42:09.224Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/3db3e063f05f50641d3e8483132507504b781c8f045f0c3ef883adf73baa/psycopg_binary-3.3.8-cp313-cp313-win_amd64.whl", hash = "sha256:e42c0e37eaed1ff03c24008561bca218eae8ec5ca4405a37897c6245ead8d612", size = 3618316, upload-time = "2026-11-04T09:42:13.761Z" }, + { url = "https://files.pythonhosted.org/packages/7a/67/7da6c17ce91cc8f991c104d7d557396d37bd2394436d446af87493e8bed7/psycopg_binary-3.3.8-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:e09cc11a367cbb147bacec0a41d748d22245e322827911d9c82b6066a8ba2059", size = 4723560, upload-time = "2026-11-04T09:42:20.14Z" }, + { url = "https://files.pythonhosted.org/packages/f3/0c/56a7a35b304a7ae9f2796f76dd76a847d34f0cdaa76f0945294c06d13220/psycopg_binary-3.3.8-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:bf9388216da2069ca0dbad58479bb83e4b979ed35c4a80d247399ac93361417c", size = 4786289, upload-time = "2026-11-04T09:42:25.777Z" }, + { url = "https://files.pythonhosted.org/packages/17/d1/99852fa4ebae1956c664be13758cf98219e9bf9613d58b9f4b21301dd1a9/psycopg_binary-3.3.8-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:78f92c5c9c9177b247b0f72f03412bc829185786525a8cf8742460066762a7d1", size = 5573883, upload-time = "2026-11-04T09:42:30.487Z" }, + { url = "https://files.pythonhosted.org/packages/6d/70/b0e38a0f80439e3b4a4ce52d1421ee5c6aa2803a43c50d32cfd16efb6df9/psycopg_binary-3.3.8-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:710183a2e29c72050c3a447f9f566de27c6efea9da40bf7b800381ac57026204", size = 5251968, upload-time = "2026-11-04T09:42:37.21Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b3/8bc56251ee11c9fcbf83fd87970116d9997834bb7ff8b9d1b8e23b468581/psycopg_binary-3.3.8-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:df35063b88af16c08bb8960aac9882cce620aea478dfec5a67cff397b575b97d", size = 6851902, upload-time = "2026-11-04T09:42:43.903Z" }, + { url = "https://files.pythonhosted.org/packages/4a/c7/64fd282c7a16dbb56af75f336c58e16c7e00be147d8efb93eeec6a4d4def/psycopg_binary-3.3.8-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a63be4f745b778654e3c438d1b0e31bcf5ce265151c6982d5c6d5d286bae84c0", size = 5085640, upload-time = "2026-11-04T09:42:48.945Z" }, + { url = "https://files.pythonhosted.org/packages/80/da/88d70f65c54a828f3d89597749e6c1b90991297e34de5f50b0f8f394022b/psycopg_binary-3.3.8-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:ced3499d480a979b956536b3f71a4736451bf3a976e4e400fc5c4b8dd3f43b23", size = 4617446, upload-time = "2026-11-04T09:42:53.985Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fe/0bdcc827e2fdb4a63e9516ad9e6e3989c39076796074ee752e0fd5c7e2bd/psycopg_binary-3.3.8-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:bf96efb4530605813b30d664f5d3b510540d89434a8e89dd7c62fb2d4fa4278f", size = 4299889, upload-time = "2026-11-04T09:42:59.846Z" }, + { url = "https://files.pythonhosted.org/packages/8e/7c/d870616fd18f371c710a08fee92d1f7c663753e992e03472b84954fa8a82/psycopg_binary-3.3.8-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0fd106e47b7d1f82744b23b6dd31856435e46c3d1b3d4972325d76f2e7a3d771", size = 4025817, upload-time = "2026-11-04T09:43:07.8Z" }, + { url = "https://files.pythonhosted.org/packages/1b/bd/af3b881b42954a5cf406b084588dd7e2fd069bb998beeef2ab5057d4cbec/psycopg_binary-3.3.8-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5deec7746acf1c742572b8bf8599f2f61a38c9925015d77254d87d3781169b3f", size = 4337790, upload-time = "2026-11-04T09:43:13.097Z" }, + { url = "https://files.pythonhosted.org/packages/00/72/132dd54feeac60ecb77eae04bac76cdcf84f8fc1e8e7cae596cd2a9d43c9/psycopg_binary-3.3.8-cp314-cp314-win_amd64.whl", hash = "sha256:6d899f361effad9a23d90940b6b55683bc87ed2d457ef64a7fa76fee7c3b9dfc", size = 3715672, upload-time = "2026-11-04T09:43:17.504Z" }, + { url = "https://files.pythonhosted.org/packages/22/85/7589ec7690974b56b5cd2c5c00174f9b78f958fb6a381317a33620696380/psycopg_binary-3.3.8-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:419a52eb62bdc0bf9eff80039329435c55a1943b1fa12f4d0cbdc45b5f856c5b", size = 4722790, upload-time = "2026-11-04T09:43:22.917Z" }, + { url = "https://files.pythonhosted.org/packages/49/cd/7a01cfa27b2f062727d3abe82726915cc45789a4649bdab6f7740b779348/psycopg_binary-3.3.8-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:f31dea98f8c5c6c60e8e049388f24eec14088518e2ded0f892d96c785401e688", size = 4785164, upload-time = "2026-11-04T09:43:31.258Z" }, + { url = "https://files.pythonhosted.org/packages/e5/ae/06211024de518c5a5d02733fba9639a062dc41f1f322e273ad611973bb3b/psycopg_binary-3.3.8-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:5fd40b5ced3f8b458024ea434f2dfee7aa62a65663089bde26c41302f6c31b2e", size = 5571610, upload-time = "2026-11-04T09:43:39.714Z" }, + { url = "https://files.pythonhosted.org/packages/e5/48/82a13d5b04fb046582b87f0651252f66dc5e1cc3183d6807aff1ea126189/psycopg_binary-3.3.8-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fc134798cd646a15326004bbeff4c2719e000a9ac52f6b893a767f7c5276e24b", size = 5254032, upload-time = "2026-11-04T09:43:45.525Z" }, + { url = "https://files.pythonhosted.org/packages/ee/24/01ddf5382fe55372f85f174e9531bdcc5350a6c9b980e25e19653d038bf8/psycopg_binary-3.3.8-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da101085aa9f74817e48fc96dda859528fc52fabcf81e27c3640d1df17dd6dcb", size = 6851760, upload-time = "2026-11-04T09:43:51.235Z" }, + { url = "https://files.pythonhosted.org/packages/51/42/192a69f42c797d8dc09ebd97f69c2c3f745abba810379df83c38490fc428/psycopg_binary-3.3.8-cp315-cp315-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:bb88457e8357a8709ab04f542c07361a816793f012a1c9818a4edd86d02cde4d", size = 5093186, upload-time = "2026-11-04T09:43:56.269Z" }, + { url = "https://files.pythonhosted.org/packages/82/73/a420dc5c2888d5c91bd40ddd7a8a604b622f3d883048a6b92e5c33ac1e9b/psycopg_binary-3.3.8-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:eb4cd3f0ad6ebcf2baeb94f93d87138044976b57b7113b6321ac3c5cf70a8130", size = 4618178, upload-time = "2026-11-04T09:44:01.001Z" }, + { url = "https://files.pythonhosted.org/packages/29/57/b30555a448fcc60607cbee68880a4126786680e71b7cc25e0a836b31da8b/psycopg_binary-3.3.8-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:9199be795608cbd3e6cc39b21c19e6043c44bc15d5a1d28f1df379830c553dd5", size = 4297173, upload-time = "2026-11-04T09:44:06.939Z" }, + { url = "https://files.pythonhosted.org/packages/48/4b/a6ead08df35feb2f5e10897e33c1ba26809f85365a7c2a0efa244acf9008/psycopg_binary-3.3.8-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:6bde86fb307fe1698fbbfeaa96130d4825f265afbeff217b959c1905b86f924d", size = 4032823, upload-time = "2026-11-04T09:44:15.209Z" }, + { url = "https://files.pythonhosted.org/packages/68/8a/7ff05b083c676024beb549863a19d59b205931010ec7f3a12aadf5de9901/psycopg_binary-3.3.8-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:c2154bd84cf20148d9a59e3ade04f0f754462b96cfac91d54d76ef33af7946e5", size = 4341050, upload-time = "2026-11-04T09:44:21.257Z" }, + { url = "https://files.pythonhosted.org/packages/59/a7/58ab2cf0a6da11d5c2b00d524f5d5b114e2e6359e629d34360cf57a22e20/psycopg_binary-3.3.8-cp315-cp315-win_amd64.whl", hash = "sha256:0332e83c2e78b1c8c00c1095688f9b332bdde9d5e9d61b8ce1cdcaf716a19b9e", size = 3716321, upload-time = "2026-11-04T09:44:24.631Z" }, +] + [[package]] name = "pycparser" version = "3.0" @@ -1793,7 +2049,7 @@ resolution-markers = [ "python_full_version < '3.12'", ] dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.12'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8b/04/e7c1fe4dc78a6fdbfd6c337b1c3732ff543b8a397683ab38378447baa331/pyee-13.0.1.tar.gz", hash = "sha256:0b931f7c14535667ed4c7e0d531716368715e860b988770fc7eb8578d1f67fc8", size = 31655, upload-time = "2026-02-14T21:12:28.044Z" } wheels = [ @@ -1810,7 +2066,7 @@ resolution-markers = [ "python_full_version >= '3.12' and python_full_version < '3.14' and sys_platform != 'emscripten'", ] dependencies = [ - { name = "typing-extensions", marker = "python_full_version >= '3.12'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1d/f1/fdedc2c75c3e31a330659c85e5793bb18b3397981fbf0844c6dee5b18926/pyee-14.0.0.tar.gz", hash = "sha256:76dd0f4314ecd27f02dc73589dea7fd3853f9b6176d8ef9b122860657e3602de", size = 98760, upload-time = "2026-08-13T04:26:11.021Z" } wheels = [ @@ -2302,6 +2558,7 @@ name = "skill-agent-loop-backend" version = "0.1.0" source = { editable = "." } dependencies = [ + { name = "alembic" }, { name = "anthropic" }, { name = "beautifulsoup4" }, { name = "cryptography" }, @@ -2316,7 +2573,6 @@ dependencies = [ { name = "packaging" }, { name = "pydantic" }, { name = "pydantic-settings" }, - { name = "pymysql" }, { name = "pypdf" }, { name = "python-docx" }, { name = "python-dotenv" }, @@ -2335,21 +2591,32 @@ dev = [ { name = "pytest-asyncio" }, { name = "ruff" }, ] +dm = [ + { name = "dmpython" }, +] +mysql = [ + { name = "pymysql" }, +] packaging = [ { name = "certifi" }, { name = "pyinstaller" }, { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin'" }, { name = "pyobjc-framework-webkit", marker = "sys_platform == 'darwin'" }, ] +postgres = [ + { name = "psycopg", extra = ["binary"] }, +] [package.metadata] requires-dist = [ + { name = "alembic", specifier = ">=1.13" }, { name = "anthropic", specifier = ">=0.117.0,<0.121.0" }, { name = "beautifulsoup4", specifier = ">=4.12.3" }, { name = "certifi", marker = "extra == 'packaging'", specifier = ">=2024.2.2" }, { name = "cryptography", specifier = ">=42.0.0,<49.0.0" }, { name = "defusedxml", specifier = ">=0.7.1" }, { name = "dingtalk-stream", specifier = ">=0.24.3,<0.25.0" }, + { name = "dmpython", marker = "extra == 'dm'", specifier = ">=2.5" }, { name = "fastapi", specifier = ">=0.111.0" }, { name = "greenlet", specifier = ">=3.0.3" }, { name = "httpx", specifier = ">=0.27.0" }, @@ -2358,10 +2625,11 @@ requires-dist = [ { name = "mcp", specifier = ">=1.9.0" }, { name = "openai", specifier = ">=1.40.0" }, { name = "packaging", specifier = ">=24.0" }, + { name = "psycopg", extras = ["binary"], marker = "extra == 'postgres'", specifier = ">=3.1" }, { name = "pydantic", specifier = ">=2.7.0" }, { name = "pydantic-settings", specifier = ">=2.3.0" }, { name = "pyinstaller", marker = "extra == 'packaging'", specifier = ">=6.6.0" }, - { name = "pymysql", specifier = ">=1.1.0" }, + { name = "pymysql", marker = "extra == 'mysql'", specifier = ">=1.1" }, { name = "pyobjc-framework-cocoa", marker = "sys_platform == 'darwin' and extra == 'packaging'", specifier = ">=10.0" }, { name = "pyobjc-framework-webkit", marker = "sys_platform == 'darwin' and extra == 'packaging'", specifier = ">=10.0" }, { name = "pypdf", specifier = ">=4.2.0" }, @@ -2372,12 +2640,12 @@ requires-dist = [ { name = "python-multipart", specifier = ">=0.0.9" }, { name = "requests", specifier = ">=2.32.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.5.0" }, - { name = "sqlmodel", specifier = ">=0.0.21" }, + { name = "sqlmodel", specifier = ">=0.0.21,<0.0.39" }, { name = "tzdata", specifier = ">=2025.2" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" }, { name = "wecom-aibot-python-sdk", specifier = ">=1.0.2" }, ] -provides-extras = ["dev", "packaging"] +provides-extras = ["dev", "postgres", "mysql", "dm", "packaging"] [[package]] name = "sniffio" @@ -2447,16 +2715,16 @@ wheels = [ [[package]] name = "sqlmodel" -version = "0.0.45" +version = "0.0.38" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pydantic" }, { name = "sqlalchemy" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/33/05/2883610972556b37dcbe6e98cdf81f0117bd78f2abc7bf42864d27218611/sqlmodel-0.0.45.tar.gz", hash = "sha256:cd9761e964400311c2fb8f052b8adba4fa8ed569c4681d4573763d12d5efc91e", size = 97782, upload-time = "2026-09-21T21:51:54.149Z" } +sdist = { url = "https://files.pythonhosted.org/packages/64/0d/26ec1329960ea9430131fe63f63a95ea4cb8971d49c891ff7e1f3255421c/sqlmodel-0.0.38.tar.gz", hash = "sha256:d583ec237b14103809f74e8630032bc40ab68cd6b754a610f0813c56911a547b", size = 86710, upload-time = "2026-04-02T21:03:55.571Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/ec/68/95308ae84de8a4cb07ab32ec961e17f274a4d503393e62e61d702b47f488/sqlmodel-0.0.45-py3-none-any.whl", hash = "sha256:f5abab62baea9a0d2c2483b8511e3a581b245f1e2fc78c92b49f84e0c5c66302", size = 31217, upload-time = "2026-09-21T21:51:53.29Z" }, + { url = "https://files.pythonhosted.org/packages/72/c7/10c60af0607ab6fa136264f7f39d205932218516226d38585324ffda705d/sqlmodel-0.0.38-py3-none-any.whl", hash = "sha256:84e3fa990a77395461ded72a6c73173438ce8449d5c1c4d97fbff1b1df692649", size = 27294, upload-time = "2026-04-02T21:03:56.406Z" }, ] [[package]] diff --git a/packaging/ultrarag.spec b/packaging/ultrarag.spec index b20b835d0..a5fd3a0d3 100644 --- a/packaging/ultrarag.spec +++ b/packaging/ultrarag.spec @@ -42,6 +42,7 @@ datas = [ (str(ASSETS / "staffdeck.png"), "packaging/assets"), (str(BACKEND / "app" / "llm" / "prompts"), "app/llm/prompts"), (str(BACKEND / "app" / "db" / "seed_fixtures"), "app/db/seed_fixtures"), + (str(BACKEND / "app" / "db" / "migrations"), "app/db/migrations"), (str(BACKEND / "mock_servers"), "mock_servers"), ] + collect_data_files("tzdata") + copy_metadata("lark-channel-sdk") datas += collect_data_files("staffdeck") diff --git a/scripts/smoke_postgres.sh b/scripts/smoke_postgres.sh new file mode 100755 index 000000000..caf475147 --- /dev/null +++ b/scripts/smoke_postgres.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +# Postgres/高斯冒烟:DATABASE_URL=postgresql+psycopg://... 下验证 +# create_all、/api/health 与日分桶/知识库/渠道配置三处方言路径。 +# 用法: +# DATABASE_URL='postgresql+psycopg://user:pass@host:5432/dbname' scripts/smoke_postgres.sh +# DATABASE_URL='opengauss+psycopg://user:pass@host:5432/postgres' scripts/smoke_postgres.sh +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PYTHON_BIN="$ROOT_DIR/backend/.venv/bin/python" +[[ -x "$PYTHON_BIN" ]] || PYTHON_BIN="${PYTHON:-python3}" + +if [[ -z "${DATABASE_URL:-}" ]]; then + echo "请先设置 DATABASE_URL=postgresql+psycopg://user:pass@host:5432/dbname" >&2 + exit 1 +fi +if [[ "$DATABASE_URL" != postgresql* && "$DATABASE_URL" != opengauss* ]]; then + echo "DATABASE_URL 必须是 postgresql+psycopg 或 opengauss+psycopg 方言: $DATABASE_URL" >&2 + exit 1 +fi + +echo "== 1/4 create_all(schema 初始化) ==" +(cd "$ROOT_DIR/backend" && DATABASE_URL="$DATABASE_URL" "$PYTHON_BIN" - <<'PY' +from app.db.database import init_db + +init_db() +print("create_all ok") +PY +) + +echo "== 2/4 日分桶/知识库/渠道配置方言路径 ==" +(cd "$ROOT_DIR/backend" && DATABASE_URL="$DATABASE_URL" "$PYTHON_BIN" - <<'PY' +"""三处生产方言点冒烟:全部走 ORM/方言助手,失败即抛异常。""" +from sqlmodel import Session, select + +from app.api.channels import _patch_binding_config_key +from app.api.knowledge import _safe_bucket_chunk_rows, _safe_document_bucket_rows +from app.db import engine +from app.db.dialect import get_dialect +from app.db.models import ( + ChannelBinding, + ChannelDelivery, + KnowledgeBucket, + KnowledgeChunk, + utc_now, +) + +backend = engine.url.get_backend_name() +dialect = get_dialect(backend) +print(f"backend={backend} dialect={dialect.name}") + +# advisory lock 闭环:acquire → check → release(真实 PG 验证会话级锁与 pg_locks 校验) +from sqlalchemy import text as sa_text + +with Session(engine) as lock_session: + assert dialect.acquire_advisory_lock(lock_session, "smoke-connector"), "acquire 失败" + assert dialect.check_advisory_lock(lock_session, "smoke-connector"), "check 未持锁" + # 回归:制造并发池流量(其他连接频繁 checkout)后,锁校验必须仍 True—— + # 专属 Connection 不归池,pg_backend_pid 稳定;Session.commit 方案在此会误判 + for _ in range(3): + with engine.connect() as busy_conn: + busy_conn.execute(sa_text("SELECT 1")) + with Session(engine) as busy_session: + busy_session.execute(sa_text("SELECT 1")) + busy_session.commit() + assert dialect.check_advisory_lock(lock_session, "smoke-connector"), "并发 checkout 后锁校验误判" + dialect.release_advisory_lock(lock_session, "smoke-connector") + assert not dialect.check_advisory_lock(lock_session, "smoke-connector"), "release 后仍持锁" +print("advisory lock roundtrip ok") + +# 部分唯一索引存在(PG 方言按方言 DDL 创建,不进 metadata) +from sqlalchemy import inspect as sa_inspect + +index_names = {i["name"] for i in sa_inspect(engine).get_indexes("model_configs")} +assert "uq_model_configs_tenant_default" in index_names, index_names +print("partial index present ok") + +with Session(engine) as db: + binding = ChannelBinding( + tenant_id="smoke_tenant", + agent_id="agent_smoke", + channel="wecom", + status="active", + config_json={"corp_id": "corpSmoke", "bot_id": "bot_smoke"}, + ) + db.add(binding) + db.commit() + db.refresh(binding) + + # 渠道配置补丁:ORM 读-改-写(原 json_set 路径) + _patch_binding_config_key(db, binding.tenant_id, binding.id, "auto_route", False) + db.commit() + db.refresh(binding) + assert binding.config_json.get("auto_route") is False, binding.config_json + assert get_dialect(backend).json_config_get(binding.config_json, "corp_id") == "corpSmoke" + + # 日分桶:方言助手表达式可执行且分组正确 + db.add( + ChannelDelivery( + tenant_id="smoke_tenant", + binding_id=binding.id, + session_id="s_smoke", + kind="reply", + text="smoke", + status="delivered", + next_attempt_at=utc_now(), + idempotency_key="smoke_day_bucket", + ) + ) + bucket = KnowledgeBucket( + tenant_id="smoke_tenant", + knowledge_base_id="kb_smoke", + knowledge_base_version_id="kbv_smoke", + document_id="doc_smoke", + bucket_key="bucket_smoke", + title="冒烟片段", + summary="smoke", + ) + db.add(bucket) + db.flush() + db.add( + KnowledgeChunk( + tenant_id="smoke_tenant", + knowledge_base_id="kb_smoke", + knowledge_base_version_id="kbv_smoke", + document_id="doc_smoke", + bucket_id=bucket.id, + chunk_index=0, + content="smoke chunk", + ) + ) + db.commit() + + day_bucket = dialect.day_bucket(ChannelDelivery.created_at) + day_rows = db.exec( + select(day_bucket) + .where(ChannelDelivery.binding_id == binding.id) + .group_by(day_bucket) + ).all() + assert len(day_rows) == 1, day_rows + + # 知识库安全读(非 SQLite 走 ORM 分支) + bucket_rows = _safe_document_bucket_rows(db, "smoke_tenant", "doc_smoke") + assert len(bucket_rows) == 1 and bucket_rows[0]["title"] == "冒烟片段" + chunk_rows = _safe_bucket_chunk_rows(db, "smoke_tenant", bucket.id) + assert len(chunk_rows) == 1 and chunk_rows[0]["content"] == "smoke chunk" + + # 清理冒烟数据 + db.delete(binding) + db.delete(bucket) + db.commit() +print("dialect paths ok") +PY +) + +echo "== 3/4 应用启动 + /api/health ==" +UVICORN_PORT="${SMOKE_PORT:-58099}" +(cd "$ROOT_DIR/backend" && DATABASE_URL="$DATABASE_URL" \ + "$PYTHON_BIN" -m uvicorn app.main:app --port "$UVICORN_PORT" >/tmp/smoke_pg_uvicorn.log 2>&1 & + echo $! > /tmp/smoke_pg_uvicorn.pid) +trap 'kill "$(cat /tmp/smoke_pg_uvicorn.pid)" 2>/dev/null || true' EXIT +for _ in $(seq 1 30); do + if curl -fsS "http://127.0.0.1:${UVICORN_PORT}/api/health" >/dev/null 2>&1; then + echo "/api/health ok" + break + fi + sleep 1 +done +curl -fsS "http://127.0.0.1:${UVICORN_PORT}/api/health" + +echo "== 4/4 冒烟完成 =="