Metadata-Version: 2.5
Name: ys_base
Version: 0.2.0
Summary: YS 统一 SDK：契约模型 / auth 客户端与差量同步 / 应用服务骨架
Author-email: ys <popsars@gmail.com>
License: MIT
Requires-Python: >=3.13
Requires-Dist: cryptography<50,>=43
Requires-Dist: loguru<1,>=0.7
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: pymongo<5,>=4.17
Requires-Dist: websockets<16,>=13
Provides-Extra: server
Requires-Dist: fastapi<1,>=0.115; extra == 'server'
Requires-Dist: pyjwt[crypto]<3,>=2.9; extra == 'server'
Requires-Dist: uvicorn[standard]<1,>=0.30; extra == 'server'
Requires-Dist: zstandard<1,>=0.23; extra == 'server'
Description-Content-Type: text/markdown

# ys_base

YS 统一 SDK：契约模型（contracts）、auth 客户端与差量同步（auth）、WebSocket RPC 基类（ws）、
Mongo 存储（store，随基础安装）、子系统服务骨架（server，extra）。
交易网关已独立为 `ys_trade_sdk`，网关改动不再升本包。

```bash
pip install ys_base            # 契约 + auth 客户端 + Mongo 存储
pip install ys_base[server]    # + FastAPI 子系统骨架
```

使用 uv 添加依赖：

```bash
uv add ys_base             # 契约 + auth 客户端 + Mongo 存储
uv add "ys_base[server]"   # + FastAPI 子系统骨架
uv add ys_trade_sdk        # 交易网关，独立版本
```

本仓库开发与全量测试需要安装全部 extras：

```bash
uv python install 3.13
uv sync --all-extras --frozen
uv run pytest
```

## 列表搜索（0.1.98 起）

服务端过滤的列表用 `ys_base.search`，规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
（全角转半角、不分大小写、空格分隔多关键词全部命中、拼音首字母/全拼/zh ch sh/最后一字半个全拼/多音字、
数字两边去千分位、数字原值自动加两位小数）。拼音数据与前端同源，由 `tools/pinyin/build.py` 生成，无第三方依赖。

```python
from ys_base.search import ys_filter, ys_match, ys_matcher, ys_search_text


def text_of(row: dict) -> str:
    # 传页面上显示的文字（含格式化后的数字），数字字段再传一次原值
    return ys_search_text(row["name"], row["status_label"], f"{row['amount']:,.2f}", row["amount"])


ys_match(text_of(row), "zhs 1,377")  # 单行判断
rows = ys_filter(rows, keyword, text_of)  # 逐行过滤，关键词只处理一次
match = ys_matcher(keyword)  # 或自己循环：match(text) -> bool
```

`Decimal`、`bson.Decimal128` 按数字处理；`bool` 写成 `true`/`false`，`list`/`tuple` 展开，`None`、空串跳过。

## 文件存储（0.1.99 起，0.1.100 改为内容寻址）

业务文件（附件、凭证、材料）存进本系统 Mongo，用 `ys_base.files` 统一处理分块、压缩、加密、上传会话、秒传、断点续传、
重复提示和清理，业务仓只传配置、写权限。需要 `ys_base[server]`（含 `zstandard`）。

### 存储结构

同一份内容只存一次，多个文件（不同名字、上传人、业务对象）引用同一份内容：

| 集合（默认名，可配） | 一行是 | 主要字段 |
| --- | --- | --- |
| 文件元数据 `files` | 一个文件 | `name`、`ext`、`content_type`、`size`、`stored_size`、`chunk_count`、`checksum`（原文件 sha256）、`content_id`、上传人（`owner_field`）、`status`、创建/更新时间、业务字段；上传中另有 `received`、`upload_expires_at`、`resume_key` |
| 内容 `file_contents`（`contents=`） | 一份内容 | `_id` = 内容 sha256（两人同时上传同一内容时后开始的那份为「sha256-文件ID」）、`sha256`、`size`、`chunk_count`、`stored_size`、`status`（`uploading` / `ready`）、`created_at`、`updated_at`，上传中带 `upload_id`，配置 `transform` 时带它的标记 |
| 块 `file_chunks` | 内容的一块 | `_id` = 「内容ID:序号」、`content_id`、`index`、`size`、`compression`（`zstd` / `none`）、`raw_sha256`、`data`，加 `transform` 标记 |

每块原始 1 MiB，zstd 10 级压缩，省不到 5% 原样存；压缩、解压、加解密、哈希都在线程里做。
`transform` 绑定内容：`encode/decode(data, content_id, index, compression)`，加密的附加数据用「内容ID:序号:压缩方式」，同内容共享加密块。

### 上传协议

事件名不变，新增 `prove_file_upload`；`begin` 必须带 `checksum`（整份 sha256，64 位小写十六进制）。

```text
begin_file_upload  {name, size, content_type, checksum, resume_key?, resume_id?, ...业务字段}
  内容已存在 → {status: "challenge", challenge_id, nonce, ranges: [{start, length}], chunk_size, chunk_count, duplicates}
  同一上传人同内容同 resume_key 有未完成上传 → {status: "resume", upload_id, chunk_size, chunk_count, received, duplicates}
  否则 → {status: "upload", upload_id, chunk_size, chunk_count, received: 0, duplicates}
prove_file_upload  {challenge_id, proofs: [sha256(nonce + 文件[start:start+length]) 的十六进制, ...]}
  → 与 finish 同构（on_finish 的结果或元数据），字典结果带 instant: true
upload_file_chunk  {upload_id, index, size, data(base64)} → {index, received}
resume_file_upload {upload_id, name?, size?, chunk_count?} → {upload_id, chunk_size, chunk_count, received}（按编号续传，保留兼容）
finish_file_upload {upload_id, checksum} → on_finish 的结果或元数据，字典结果带 instant: false
cancel_file_upload {upload_id} → {cancelled: true}
read_file_chunk    {_id, index} → {index, chunk_count, data, content_type, _id}
```

示例（内容已存在，秒传）：

```json
→ begin_file_upload {"name": "凭证.pdf", "size": 183204, "content_type": "application/pdf", "checksum": "9f86d0…0a08"}
← {"status": "challenge", "challenge_id": "5c1e…", "nonce": "a41b…", "ranges": [{"start": 10233, "length": 65536}, {"start": 77012, "length": 65536}, {"start": 1840, "length": 65536}], "chunk_size": 1048576, "chunk_count": 1, "duplicates": [{"_id": "f12", "name": "凭证（旧）.pdf"}]}
→ prove_file_upload {"challenge_id": "5c1e…", "proofs": ["3b7a…", "e021…", "77fd…"]}
← {"_id": "f31", "name": "凭证.pdf", "instant": true}
```

规则：

- 持有验证：随机 2～3 段、每段不超过 64 KB（文件不到一段时用整份）；5 分钟有效、一次性、只认发起人。不符报
  「文件校验不一致，请重新上传」（409），过期、重放、他人冒用报「上传已失效，请重新上传」（410）。只知道 sha256 拿不到内容。
  通过后同样交给 `validate` 查文件头（白名单不能靠秒传绕过），再调 `on_finish`。
- 按内容续传：服务重启不丢；改名也续（名字、类型、业务字段换成这次的，类型变了重新查文件头）。`resume_key` 区分同一文件
  传给不同业务对象，`resume_id` 精确指定会话。块写入幂等：重发已收到的块按 `raw_sha256` 核对一致即确认；只接受下一块。
- `finish` 逐块读回解码，核对每块大小、总大小与 sha256（必须等于 begin 声明的）；核对失败删除整个上传。
  两人同时传同一内容各写各的，后完成的丢掉自己的块、指向先完成的内容（50 MB 在内存存储上：上传约 0.3 秒、秒传约 0.02 秒）。
- 重复：`duplicates` 是同内容、已生效、`visible_duplicates` 允许当前用户看到的文件，不传钩子时恒为空。默认允许并提示；
  单据类可在 `on_duplicate` 抛 `BusinessError("已存在相同内容的文件：xxx")` 禁止。
- 删除与清理：`delete(file_id)` 只删元数据；`purge_unreferenced()` 删除没有任何文件引用（`files` 里任何状态的行，加
  `extra_references()` 返回的外部引用）且 `purge_grace_seconds`（默认 1 小时）内未被引用的内容。未完成上传默认 24 小时没有
  新块即过期；`cleanup()` 依次清两者，`attach(server)` 在启动时和每小时调用；`cancel` 立即删。
- 文件名 1～120 字、无控制字符；空文件拒绝；每人同时上传默认 6 个；错误文案统一。

### API

```python
FileStore(
    store,  # server.store
    files="files",
    contents="file_contents",
    chunks="file_chunks",
    max_size=50 * 1024 * 1024,
    max_uploads_per_user=6,
    upload_ttl_seconds=24 * 3600,
    challenge_ttl_seconds=300,
    purge_grace_seconds=3600,
    time_unit="s",  # "s"：秒 float；"ms"：毫秒 int
    owner_field="user_id",
    created_field="created_at",
    updated_field="updated_at",
    ready_status="ready",
    validate=None,  # (name, size, content_type, head: bytes | None) -> str | None，可为 async
    transform=None,  # ChunkTransform：marks、encode(data, content_id, index, compression)、decode(...)
    on_finish=None,  # async (record) -> result | None
    extra_references=None,  # async () -> Iterable[content_id]：元数据不在 files 集合里的引用
    integrity_message="文件内容完整性校验失败",
)
```

方法：`begin(name, size, content_type, *, user_id, checksum, extra=None, file_id="", resume_key="", resume_id="")`、
`prove(challenge_id, user_id, proofs, *, on_finish=None)`、`pending_challenge(challenge_id)`、`put_chunk(upload_id, user_id, index, data, size)`、
`resume(upload_id, user_id, *, name, size, chunk_count)`、`finish(upload_id, user_id, checksum, *, on_finish=None)`、`cancel(upload_id, user_id)`、
`duplicates_of(checksum)`、`ready_content(checksum)`、`get(file_id)`、`get_file(file_id)`、`get_content(content_id)`、
`read_chunk(file_id, index, *, meta=None)`、`read_all(file_id, *, meta=None)`（外部元数据 `meta` 需带 `content_id`）、
`write_bytes(name, content, *, content_type, user_id, extra, file_id, on_finish)`（服务端写入，同内容不再写块）、
`delete(file_id)`、`cleanup_expired()`、`purge_unreferenced()`、`cleanup()`、`ensure_indexes()`、`attach(server)`、
`delete_chunks(file_id)`（只清 0.1.99 旧格式残留）。

标准事件 `register_file_events(router, files, *, authorize, prepare=None, on_finish=None, visible_duplicates=None, on_duplicate=None, names=FileEventNames())`：

- `authorize(ctx, action, record) -> user`：`action` 为 begin/prove/chunk/finish/cancel/resume/read；begin 时 `record` 为 None，prove 时为待建的元数据；
- `prepare(ctx, user, data) -> dict`：begin 时补业务字段；
- `on_finish(ctx, user, record) -> result`：生效后（含秒传）的处理，返回值即结果；
- `visible_duplicates(ctx, user, records) -> list[dict]`：records 为同内容、已生效的元数据，返回当前用户能看到的部分（字段自定）；
- `on_duplicate(ctx, user, data, records) -> None`：要禁止时抛 `BusinessError`，提示里只写用户能看到的名字。

### Template：标准接入

```python
from ys_base.files import FileStore, register_file_events, user_id_of
from ys_base.server import EventRouter

files = FileStore(server.store)  # files / file_contents / file_chunks、50 MB


async def authorize(ctx, action, record):
    return await require_user(ctx, "files")


async def prepare(ctx, user, data):
    return {"memo": text(data.get("memo"), "备注"), "deleted_at": None}


async def finished(ctx, user, record):
    await broadcast_change(ctx, "upsert", record["_id"])
    return public_file(record, await users(ctx.server))


async def visible(ctx, user, records):
    # 文件管理页大家都能看：未删除的同内容文件都提示
    return [
        {"_id": r["_id"], "name": r["name"], "created_at": r["created_at"]}
        for r in records
        if r.get("deleted_at") is None
    ]


server.include_ws_router(
    register_file_events(
        EventRouter("files"),
        files,
        authorize=authorize,
        prepare=prepare,
        on_finish=finished,
        visible_duplicates=visible,
    )
)
files.attach(server)  # 启动建索引、清理，之后每小时清过期上传和无引用内容
# 彻底删除：await files.delete(file_id)（只删元数据，内容由清理任务按引用删）
```

前端：`uploadChunked(store.call, file, { begin: { event: "begin_file_upload", data: { memo } }, chunkEvent: "upload_file_chunk", finishEvent: "finish_file_upload", cancelEvent: "cancel_file_upload", resume: {}, onProgress, onDuplicates })`，
结果 `instant` 为 true 时提示「秒传完成」。

### ys_bill：白名单、5 MB、凭证重复提示

```python
FILE_TYPES = {"application/pdf": (b"%PDF-",), "image/png": (b"\x89PNG\r\n\x1a\n",), "image/jpeg": (b"\xff\xd8\xff",)}


def validate(name, size, content_type, head):
    content_type = {"image/jpg": "image/jpeg"}.get(content_type.lower(), content_type.lower())
    if content_type not in FILE_TYPES:
        raise BusinessError("只能上传 PDF、PNG 或 JPG 文件")
    if head is not None and not head.startswith(FILE_TYPES[content_type]):
        raise BusinessError("文件内容与类型不符")
    return content_type  # begin 时写入规范化后的类型


files = FileStore(
    server.store,
    files="bill_files",
    contents="bill_file_contents",
    chunks="bill_file_chunks",
    max_size=5 * 1024 * 1024,
    validate=validate,
)


async def visible(ctx, user, records):
    # 同一张凭证已用在哪些记录：只提示当前角色能看到的页面里的
    pages = pages_for_role(user)
    return [
        {"_id": r["_id"], "name": r["name"], "created_at": r["created_at"]}
        for r in records
        if await used_in(r["_id"], pages)
    ]


# 默认只提示（前端 onDuplicates 弹确认「这张凭证已上传过：xxx，仍要上传吗」）；要禁止时：
# async def on_duplicate(ctx, user, data, records):
#     raise BusinessError(f"已存在相同内容的文件：{records[0]['name']}")
register_file_events(router, files, authorize=authorize, on_finish=finished, visible_duplicates=visible)
```

### ys_hrms：加密、毫秒时间、自定义事件名与 begin 包装、外部元数据

```python
class MaterialCipher:
    marks = {"encryption": "aes-gcm"}

    def __init__(self, server):
        self.server = server

    def encode(self, data, content_id, index, compression):
        nonce = os.urandom(12)
        return nonce + file_cipher(self.server).encrypt(nonce, data, f"{content_id}:{index}:{compression}".encode())

    def decode(self, data, content_id, index, compression):
        return file_cipher(self.server).decrypt(data[:12], data[12:], f"{content_id}:{index}:{compression}".encode())


async def policy_content_ids():  # 制度附件元数据记在 hr_policies.file，不在 employee_files
    return [p["file"].get("content_id") for p in await server.store.query_all(HR_POLICIES_TABLE) if p.get("file")]


files = FileStore(
    server.store,
    files="employee_files",
    contents="employee_file_contents",
    chunks="employee_file_chunks",
    time_unit="ms",
    owner_field="uploaded_by",
    created_field="uploaded_at",
    validate=lambda name, size, content_type, head: head is not None and check_head(file_extension(name), head),
    transform=MaterialCipher(server),
    extra_references=policy_content_ids,
    integrity_message="材料内容完整性校验失败",
)


# 多个 begin 事件自己写（plan_upload 校验说明、大小、页面权限后拼好记录）：
@router.on("begin_material_upload")
async def begin_material_upload(ctx, data):
    user = await require_page(ctx, ...)
    record = await plan_upload(ctx.server, user, data)
    reply = await files.begin(
        record["name"],
        data.get("size"),
        record["content_type"],
        user_id=operator_id(user),
        checksum=data.get("checksum"),
        extra=record,
        resume_key=data.get("resume_key"),
        resume_id=data.get("resume_id"),
    )
    return {**reply, "duplicates": []}  # 材料不提示他人的同内容文件


# 通用的秒传、发块、续传、完成、取消用标准事件；authorize 按记录上的业务字段重新校验页面授权
register_file_events(
    router,
    files,
    authorize=authorize_by_record,
    on_finish=commit_by_record,  # 材料 commit_upload / 制度附件 attach_policy_file（把 content_id 一并写进 hr_policies.file）
    names=FileEventNames(
        begin=None,
        prove="prove_material_upload",
        chunk="upload_material_chunk",
        finish="finish_material_upload",
        cancel="cancel_material_upload",
        resume="resume_material_upload",
        read=None,
    ),
)
# 制度附件读取：files.read_chunk(file_id, index, meta=policy["file"])（meta 带 content_id）
```

前端传 `proveEvent: "prove_material_upload"`，`resume: { key: 员工或制度 ID }`。

### Auth：按用途授权，管理通道上的事件

Auth 不是 AppServer：`FileStore` 用复用 Auth 连接的 `AuthFileMongo`，`attach` 交给 `FileMaintenance`（`main.lifespan` 里 start/stop）。
事件注册在管理通道路由上，`prove_file_upload` 与其他事件一样走同一个 `authorize_file`（按 `record["usage"]` 校验用途权限，
begin 时在 `prepare_file` 里核对用途、所属对象与用途上限）。转码类用途（银行卡照片、应用 Logo）在 `on_finish` 里
`write_bytes` 新文件后只删原上传的元数据（`files.store.delete_local(files.files, record["_id"])`，不要在 `on_finish` 里调
`files.delete`：finish 持有该文件的锁），原图内容没有引用后由清理任务删除。Auth 不提示他人的同内容文件（不传 `visible_duplicates`）。

```python
files = FileStore(
    AuthFileMongo(db, client), files="files", contents="file_contents", chunks="file_chunks", max_size=10 * MB
)
register_file_events(admin_router, files, authorize=authorize_file, prepare=prepare_file, on_finish=finish_by_usage)
files.attach(file_maintenance)
```

### 从 0.1.99 迁移

0.1.99 的块 `_id` 是「文件ID:序号」、没有内容层，升级 0.1.100 前停服跑迁移：逐文件读回（旧 transform 解码）、核对 sha256、
按内容合并、用新 transform 写新块和内容行，更新 `content_id` 后删旧块。默认 dry-run；可重跑（已迁移的跳过、补删残留旧块）；
单个文件失败只记下来、不删旧数据；旧版未完成的上传在 apply 时丢弃。

```python
migrate_to_content_store(
    target,  # 新配置的 FileStore（集合名、新 transform 从这里取）
    *,
    legacy_chunks=None,  # 旧块集合，默认与 target.chunks 相同
    legacy_transform=None,  # 旧块的 transform（附加数据「文件ID:序号:压缩方式」）
    apply=False,
    external=(),  # ExternalFiles(name, load, save)：元数据不在 files 集合里的文件
) -> MigrationReport  # files、migrated、new_contents、merged、skipped、discarded_uploads、failed、summary()
```

各仓几行包成 `python -m app.migrate_content_store [--apply]`：

```python
# Template app/migrate_content_store.py（ys_bill 同理，FileStore 换成 bill_files / bill_file_contents / bill_file_chunks）
import asyncio
import sys

from ys_base.files import FileStore
from ys_base.files_migrate import migrate_to_content_store
from ys_base.store.mongo import MongoStore

from app.config import settings
from app.files import CHUNKS, FILES, MAX_FILE_SIZE


async def main(apply: bool) -> int:
    store = MongoStore(settings.app_mongodb_uri)
    try:
        await store.ping()
        files = FileStore(store, files=FILES, chunks=CHUNKS, max_size=MAX_FILE_SIZE)
        report = await migrate_to_content_store(files, apply=apply)
    finally:
        await store.close()
    print(report.summary())
    for file_id, reason in report.failed:
        print(f"  失败 {file_id}: {reason}")
    return 1 if report.failed else 0


if __name__ == "__main__":
    sys.exit(asyncio.run(main("--apply" in sys.argv)))
```

```python
# ys_hrms：旧块用文件 ID 做附加数据、新块用内容 ID，同一个 MaterialCipher 两边都能用；制度附件走 ExternalFiles
from ys_base.files_migrate import ExternalFiles, migrate_to_content_store


async def load_policy_files():
    return [
        {**p["file"], "_id": p["file"]["id"], "policy_id": p["_id"]}
        for p in await store.query_all(HR_POLICIES_TABLE)
        if p.get("file")
    ]


async def save_policy_file(record):
    policy = await store.get(HR_POLICIES_TABLE, record["policy_id"])
    file = {key: value for key, value in record.items() if key not in ("_id", "policy_id")}
    await store.upsert_local(HR_POLICIES_TABLE, {**policy, "file": file})


cipher = MaterialCipher(server)
report = await migrate_to_content_store(
    files,  # transform=cipher 的新 FileStore
    legacy_transform=cipher,
    apply=apply,
    external=[ExternalFiles("hr_policies.file", load_policy_files, save_policy_file)],
)
```

```python
# Auth：files 集合同时有 file_metas 契约表，迁移只改存储层（files / file_chunks），file_metas 的 _id 不变
report = await migrate_to_content_store(build_file_store(db, client, max_size=MIGRATION_MAX_SIZE), apply=apply)
```

`LocalStore` 另有 `find_local(table, query)`、`delete_local_where(table, query)`（字段相等条件；MongoStore 走索引，
`delete_local_where` 不接受空条件）。

## 快速发布到 PyPI

先在 `ys_base/__init__.py` 中更新 `__version__`。PyPI 不允许覆盖已经发布的同版本文件，因此每次发布必须使用新版本号。
使用 project-scoped PyPI token，并将其保存在 macOS 钥匙串，不在项目目录、环境文件或 Shell 配置中保存明文 Token。

必须使用经典的“钥匙串访问”应用手动添加:文件 -> 新建密码项，不要使用新版“密码”App。新版“密码”App 管理的是网站密码，会强制要求填写网站，凭据类型不适合 PyPI 发布 Token。

在“钥匙串访问”中选择“登录”钥匙串，手动添加密码项目并填写：

- 钥匙串项目名称：`pypi:__token__`
- 账户名称：当前 macOS 用户名
- 密码：完整的 PyPI project-scoped Token

保存后不要使用会直接输出密码内容的命令检查 Token。发布脚本会从钥匙串读取该通用密码，并只注入单次 `uv publish` 进程，不会打印、写入项目文件或长期导出为环境变量。

在 `ys_platform` 仓库根目录执行：

```bash
cd ys_base
./publish-pypi.sh
```

脚本会自动运行测试、构建、审计 wheel/sdist、上传，并校验 PyPI 文件哈希。发布成功后等清华镜像可下载该版本，再在消费仓升锁：

```bash
uv cache clean ys-base
version=$(sed -n 's/__version__ = "\([^"]*\)"/\1/p' ys_base/ys_base/__init__.py)
# 确认清华镜像已有该版本后再执行
uv add "ys_base==$version"
```

交易客户端、行情、静态信息和收益数据服务在 `ys_trade_sdk`。每个 `TradeManager` 独占一个 `TradeRuntime`。

业务系统使用 `ys_base 0.1.29` 后，Auth 协议逻辑表名继续保持 `users`、`owners`、`accounts`、`brokers`；Mongo 物理镜像统一为 `_auth_*`，同步状态为 `_auth_sync_state`，本地身份集合为 `_local_users`、`_local_user_roles`。MongoStore 启动时只对历史集合执行预检后的原地 rename，检测到新旧集合或同步状态键并存会拒绝启动。

```python
from ys_trade_sdk import (
    Account,
    TradeManager,
    TradeRuntimeConfig,
)

manager = TradeManager(
    accounts=[
        Account(
            account="A001",
            password="...",
            trade_source="xt",
            trade_uri="ws://trade.example.com",
            profit_enabled=True,
        )
    ],
    runtime_config=TradeRuntimeConfig(
        quote_data_base_url="http://quote.example.com",
        symbol_data_base_url="http://symbol.example.com",
        symbol_data_username="symbol-user",
        symbol_data_password="symbol-password",
        trade_data_base_url="http://trade-data.example.com",
        trade_data_username="trade-user",
        trade_data_password="trade-password",
    ),
)

quotes = await manager.query_snapshots({"600000.SH", "300750.SZ"})
refreshed = await manager.query_snapshots_with_refresh({"600000.SH"}, {"f43", "f58", "f60"})
statics = await manager.query_static_infos({"600000.SH"}, {"name", "pre_close"})
alive = await manager.check_snapshot_service_alive()
```

`DefaultSnapshotFields == "f43,f58,f60"`，返回原始 `f*` 字段，并固定映射
`f43 -> close`、`f60 -> pre_close`、`f58 -> name`。不提供 `last_price` 或 `pre_price` 兼容字段；
可通过字符串或字段集合指定其他 `fields`。

- `query_snapshots()` 是无缓存单次查询，不登记后台刷新标的。
- `query_snapshots_with_refresh()` 登记当日标的和字段，并在 `09:00:00-15:30:00` 每 2 秒持续刷新；
  当日标的和字段只增不减。
- Snapshot 和 StaticInfo 缓存在上海自然日变化时会同时清空日期、标的、字段和记录。
- 只有账号 `profit_enabled=True`（Trade 本地字段，缺省为 True）时，才要求 Snapshot、StaticInfo 和 TradeData 三类服务地址齐全。

刚发布的新版本若已在 PyPI 页面可见，但 uv 仍提示该版本不存在，通常是清华镜像尚未同步，或本地缓存的 Simple Index 尚未更新。生产锁文件必须继续走清华镜像，禁止 `--default-index https://pypi.org/simple`。

先确认镜像：

```bash
curl -fsS "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/ys-base/" | grep "ys_base-$version"
```

镜像已有该版本后，清理单包缓存再升锁：

```bash
uv cache clean ys-base
uv add "ys_base==$version" --refresh
```

如果仍无法解析，再清理完整缓存后重试同一条 `uv add`，不要改官方源。镜像长时间没有该版本时停止升锁并等待同步。

当前四仓边界、公共包依赖和配置规则见仓库根 `docs/业务系统架构方案.md`；开发与发版见 `docs/业务系统开发规范.md`。
