Replace legacy Go project with Rust Bedrock bootstrap

This commit is contained in:
2026-11-29 23:33:11 +08:00
parent fa79b1e6ce
commit 59f2ef1bf2
140 changed files with 17 additions and 24124 deletions
-115
View File
@@ -1,115 +0,0 @@
-- Foundry 数据库源码阅读注释索引(仅注释,不执行迁移)。
-- 历史 db/*.sql 的 SHA-256 由 deploy/migrate.py 原文计算并记录;即使只改注释,
-- 已部署库也会拒绝同名文件的新校验和。因此按迁移文件与对象名在此维护中文说明。
-- 顺序:001 认证 → 002 平台 → 003 快照 → 004 会话期限 → 005 子图事务 →
-- 006 资产 → 007 AI 队列 → 008 canonical 模型 → 009–011 AI 身份/回执/位置。
-- db/001-auth.sql:四张基础认证表在一个事务中安装。
-- project_accounts:账户身份以 (project,id) 为主键,Google subject 在项目内唯一。
-- 同一 Google 用户可在不同项目有不同账户,邮箱是可空资料,不作为跨提供方自动合并依据。
-- oauth_attempts:十分钟 OAuth 尝试;state/browser 保存摘要,frontend_challenge 绑定
-- 前端兑换证明,google_verifier 原文用于服务器向 Google 兑换 PKCE 授权码。
-- 回调通过 DELETE ... RETURNING 原子消费,外部兑换失败也不会恢复已消费尝试。
-- login_grants:一分钟一次性交换码只存 token_hash,复合外键保证账户属于同一项目。
-- project_sessions:bearer 明文只交客户端,数据库仅存摘要和期限;删除账户级联清会话。
-- 三个 expires_at 索引提供过期定位能力,本文件本身不创建定时清理任务。
-- db/002-platform.sql:扩展身份提供方与协作资源,保留旧 Google 账户/会话。
-- project_accounts:google_subject 放宽可空;username 在项目内按 lower 唯一,
-- display_name/avatar_url 是可由用户维护的资料,updated_at 由应用更新。
-- oauth_attempts.provider 默认 google 兼容已有行;Slack 增加 oidc_nonce 防止 ID token 重放。
-- account_identities:以项目/提供方/subject 唯一定位账户,迁入既有 Google subject;
-- 项目/提供方/account 唯一约束限定同一账户每提供方只有一个绑定。
-- email_credentials:已验证邮箱凭据,邮箱须小写,password_hash 是 bcrypt;
-- 项目/email 主键及项目/account 唯一性不允许多个凭据冒用同一邮箱或账户。
-- email_registrations:未验证注册单独保存密码摘要和验证码摘要,未确认前不建立账户;
-- 重发注册由应用在邮箱级事务锁下替换待验证记录及过期时间。
-- email_outbox:邮件与注册同事务写入,available_at/attempts 控制重试;lease_id/
-- lease_until 使后台 worker 可认领并在租约失效后恢复,sent_at 标成功。
-- 发送成功后应用清空 body;SMTP 成功与数据库标记不原子,不能宣称严格只投递一次。
-- auth_rate_limits:仅保存限频键摘要,固定窗口过期后由应用 upsert 重置次数。
-- onboarding_responses:项目/账户唯一完成记录,answers/result 必须 JSON 对象;
-- 配合账户行锁,使并发首次引导只能创建一次工作区并重放已存结果。
-- workspaces:所有者外键指向同项目账户;工作区行锁是角色/所有权变更共享的串行点。
-- workspace_members:每人每工作区一个角色,admin/editor/viewer 的写权限由应用解释;
-- owner 必须保留 admin 成员的规则由服务控制,表约束没有单独自动生成该成员。
-- materials:按项目/工作区隔离的可复用内容对象,kind 为受限类型;version 是素材
-- 内容/元数据的乐观版本,后续新增 canvas_version 与它分离。
-- material_modified/material_created/material_alphabetical:对应列表排序的复合索引。
-- material_opens:账户级最近打开时间,可反复 upsert,不修改素材正文;专用索引支持最近打开。
-- tags/material_tags:标签名在工作区内忽略大小写唯一;双复合外键阻止跨工作区关联,
-- 标签/素材删除级联清关联,应用负责让受影响素材版本递增。
-- board_layouts:旧布局引用可复用素材,位置/尺寸与内容独立;禁止引用自身,
-- “必须 board 且不可嵌套 board”及每板最多 2000 条由服务检查。
-- material_grants:显式 editor/viewer 素材权限,不存在素材级 admin 授予;
-- 根画布继承和归档祖先检查由 lockMaterial 的递归查询决定。
-- share_links:仅保存邀请摘要;可指工作区或单素材,单素材不允许 admin;
-- max_uses/use_count 是额度,expires_at/revoked_at 控制之后的兑换资格。
-- share_redemptions:同账户同链接只兑换一次;应用在持锁事务内插入成功后才加额度并提升角色。
-- link_clicks:公开点击独立于兑换计数,仅存 Referer origin,避免收集路径、查询和令牌。
-- bigint identity 支持递减 ID 分页;应用角色需单独授予序列 USAGE/SELECT。
-- db/003-canvas.sql:为 board 增加独立 canvas_version 和可空 canvas_document。
-- canvas_board_only 禁止非 board 保存快照;旧空文档在读取时投影为初始空 v1 图。
-- workspaces/materials 的 slug 先按名称/标题加 UUID 回填,再设 NOT NULL 和作用域唯一。
-- foundry_default_slug:仅 INSERT 且未给 slug 才派生值,名字更改不会隐式改 URL。
-- label 规范化并限长,空结果回退 canvas;触发器在两个表共享,因此区分 name/title。
-- db/004-session-lifetime.sql:加入 created_at 和九十天 absolute_expires_at 缺省。
-- 旧会话原始发行时间未知,绝对上限从迁移时开始,但原 expires_at 完全不变,
-- 已闲置过期的旧会话不会被此迁移复活。应用续期取 min(三十天后,绝对期限)。
-- db/005-canvas-subgraphs.sql:持久唯一所有权与多画布事务恢复信息。
-- canvas_subgraphs:Child 是主键中的唯一所有者身份,活跃 Parent/Frame 受部分唯一索引限制;
-- archived_at 保留恢复关系但从活跃树移除;migration_source 保存旧框迁移证据。
-- 父/子外键均 RESTRICT,不能删掉素材而留下无法解释的所有权记录。
-- foundry_check_subgraph:先锁工作区,确认两端是 board,再递归算祖先和后代,
-- 拒绝循环与深度超八;数据库触发器也保护绕过 HTTP 的维护写入。
-- canvas_transactions:账户/画布/动作/幂等键唯一,payload_hash 防止同键换体。
-- response_status/body 冻结重放结果;before_state、after_versions、relation_changes
-- 支持条件撤销;expires_at 七天及 undone_at 控制撤销有效性,不会自动倒退当前版本。
-- db/006-canvas-assets.sql:编码原图 bytea 与绑定同库事务提交,URL 与存储后端解耦。
-- canvas_assets:限制格式和二十 MiB 编码预算,上传者/工作区/幂等键唯一,digest 为原图摘要;
-- 完整像素预算与解码有效性由应用在写入前检查,不能只依赖 MIME 字符串。
-- canvas_asset_bindings:资产可被多个画布引用,主键去重;删除画布级联清绑定,
-- 有绑定资产不能直接删除。可读性按当前绑定画布授权判断,缓存字节不能作为权限证明。
-- db/007-canvas-ai.sql:run/step/event 与旧取消/显式应用回执。
-- canvas_ai_runs:冻结 plan/create_response,保存队列时间、取消位、租约与单调 last_seq;
-- pending 部分索引服务认领,active 索引服务活跃列表;expires_at 表示三十天保留期限。
-- canvas_ai_steps:每 run 的拓扑 ordinal、冻结输入、目标指纹、输出与应用版本;
-- 局部 board/node 活跃部分唯一索引防止同目标同时重复生成。
-- canvas_ai_events:以 run/seq 主键保证重放顺序;appendAIEvent 用同一 SQL 推进 last_seq。
-- canvas_ai_mutations:旧协议按 run/账户/动作/键冻结应用和取消结果;不同于 run 生成重试。
-- 租约过期不证明模型尚未执行,恢复把未知执行标为中断,只有明确 codex_busy 才允许回队。
-- db/008-canvas-model.sql:只安装 canonical schema,不自动迁移已有用户快照。
-- canvas_model_projects:每根显式迁移身份屏障,记录源版本表与 migration_id。
-- canvas_model_canvases:树关系、入口元素、独立版本及 archived;父/入口同时可空,
-- 无父只能是根;延迟外键允许入口元素与孩子关系在同批创建,提交时再验证。
-- canvas_model_active_entry 部分唯一索引防止一个活跃入口拥有多个子画布。
-- canvas_model_elements:主键 (project,element_id) 使身份跨工作区/树不可被抢占;
-- record 的 id/owner/incarnation 必须与索引列相符,删除记录保留 deleted_incarnation。
-- owner 外键延迟验证,支持同事务移动所有权;应用验证整个最终树和连接共同祖先。
-- canvas_model_identity_map:保留来源画布/结构/旧 ID 到稳定元素 ID 的完整一次性映射。
-- canvas_model_requests:账户作用域请求键、动作、摘要、状态与冻结回执,确定拒绝也可恢复。
-- canvas_model_operations:逻辑 ID 独立于传输 request_id 去重,外键延迟到同事务回执落库;
-- 只有应用成功才消费逻辑身份,拒绝前缀不能把其中操作标为已执行。
-- foundry_guard_canonical_canvas:已迁入树的 canvas_document/version 改写需事务内
-- foundry.canonical_writer=on,阻止旧写入路径覆盖权威身份。此标志是应用协作约定,不替代数据库角色权限。
-- db/009-canvas-ai-operations.sql:为 run 增加可空 logical_operation_id,旧行保持 NULL。
-- 部分唯一索引限定项目/工作区/账户下同逻辑操作只能准入一个 run,换传输键不能重复付费执行。
-- db/010-canvas-ai-receipts.sql:把传输回执从执行保留周期中分离。
-- canvas_ai_requests:允许 run.start/cancel/apply,保存 applied/not-applied 与原始请求身份;
-- 不以 run 外键级联删除,使 run 清理后仍可判定已知结果,工作区删除则整体清理。
-- applied 逻辑操作部分唯一:确定零效果拒绝可显式用新键重计划,已应用操作不能再次执行。
-- INSERT ... SELECT 从旧 canonical run 回填 accepted 回执,ON CONFLICT 保留已有记录。
-- 回执缺失只能回答 unknown,不能证明历史付费调用从未发生。
-- db/011-canvas-ai-target-location.sql:分离冻结来源与实际应用位置。
-- applied_board_id:结果写到 owner 移动后的目标画布,旧已应用行按原 board_id 回填。
-- canvas_ai_canonical_target_busy:按根/稳定节点/代数而非原 board 唯一限制活跃步骤,
-- owner-only 移动不能逃过 node_busy,再次删除/恢复的新代则由生命周期检查单独处理。
-196
View File
@@ -1,196 +0,0 @@
# Shared research API
This work belongs to Thesisly 研迹 and uses Bedrock rather than a separate
application backend. The corpus is public; account sessions and future private
collections remain project scoped.
## Current implementation boundary
`internal/research` implements the HTTP contract and a PostgreSQL repository
based on the fixed Paper Atlas `a3b677b` schema (TEXT/BIGINT columns, native
English title/abstract search index). `cmd/bedrock` enables it only when
`FOUNDRY_RESEARCH_DATABASE_URL` is configured. The Paper Atlas migration is now published: 21 tables passed its independent
count/content-hash acceptance. A dedicated `foundry_research_reader` role has
SELECT on the ten tables consumed here, schema USAGE, and read-only defaults.
Its connection is stored only in the protected server file below.
The existing SQLite implementation was withdrawn. Real-corpus integration has
been checked through a loopback Core and the local frontend. Formal production
release still requires the user to merge and choose to deploy; this branch is
not deployed by these checks. Very broad queries remain subject to the budget
and performance limitation documented below.
Do not add `FOUNDRY_RESEARCH_DATABASE`.
The server-side deployment may load a protected
`/opt/endoleap-infra/foundry/research.env` containing
`FOUNDRY_RESEARCH_DATABASE_URL` and `FOUNDRY_RESEARCH_SCHEMA` (default `research`).
Keep the connection string out of Git, Actions variables, browser configuration
and command arguments. Use a dedicated role with schema USAGE and table SELECT
only. Core uses a separate two-connection pool, read-only connection defaults and
read-only transactions. Each research transaction disables JIT locally: the
measured count plan spent about 2.85 seconds compiling JIT functions, and its
end-to-end execution exceeded eight seconds. This does not alter shared
PostgreSQL settings or replace exact counts with estimates. Startup checks the published schema/SELECT permissions;
an explicitly enabled but invalid connection fails candidate readiness.
Deployment migration defaults now follow the shared `foundry-postgres`
container name. `FOUNDRY_POSTGRES_CONTAINER` or the existing `--container` option
can select a different container without changing database/table names.
## Routes
- `GET /projects/{project}/research/papers`
- `GET /projects/{project}/research/papers/{id}`
Only configured Foundry projects are accepted. Reading the public corpus does
not require a session; these routes do not expose private data or accept writes.
List parameters are `q` (200 Unicode characters, 20 words), `searchIn`
(`text` or `author`), `topic` (an exact arXiv category), `sort` (`recent` or
`title`), `cursor` (optional, opaque, at most 32768 characters), and
`pageSize` (1–50, default 8). Unknown, malformed
or repeated parameters return 400. `recent` means descending stable paper ID,
not publication date. Search terms must become bound query parameters, never
raw SQL or user-supplied full-text syntax.
Title/abstract search uses the migration's English vector with
`plainto_tsquery`; author search uses simple-language terms over the stored
author JSON. Both treat input as terms, never full-text operators. Initial full-corpus measurements showed eight-second timeouts for text,
author and topic counts; the unfiltered count took 7.25 seconds. Execution plans
confirmed sequential scans for authors and category joins.
`deploy/research/query-indexes.sql` supplies operator-run concurrent indexes for
those two missing access paths. It is separate from Core startup and auth
migrations; do not grant DDL to the runtime reader. Both indexes completed on the confirmed ECS (category 35.4 seconds, author
436.47 seconds); measured end-to-end checks are documented below.
List responses contain `items`, `nextCursor`, `previousCursor`, `topics`, and
`pageSize`. Empty cursor strings mean that direction is unavailable. There is
no `total`, page number, total page count or deep-page cap. The old `page`
parameter is rejected; coordinate the frontend/backend contract update.
Each paper preserves original title/abstract, authors, source dates, topics and
source links. Publication decisions need source evidence; absent decisions stay
unknown. No invented repositories, metrics or generated research conclusions.
Lists use a read-only repeatable-read snapshot without `count(*)` or `OFFSET`.
Keyset paging uses ID descending for recent order and `(title_key, id)` ascending
for title order, including a reverse query for previous pages. The title key is
kept in its stored codec and C collation. Cursors bind normalized query, search
scope, topic, sort and page size; changing filters requires a fresh cursor. They
are public row positions, not authorization tokens or guaranteed frozen snapshots
across requests. Concurrent corpus edits may alter later pages.
Only pageSize+1 positions are selected; the extra position indicates more data,
then full rows and batched metadata are loaded for at most pageSize papers.
For recent order with only a topic filter, page directly through the existing
`(tag_id,paper_id)` index and deduplicate evidence before LIMIT. For text/author
search in recent order, try an ID interval of 512 near the cursor, expanding
once to 4096 only if there are some matches but fewer than pageSize+1.
Only a full page plus one proves that interval contains the next page. If neither bounded attempt fills the page,
all local candidates are discarded and the complete indexed search is used;
rare or older matches are never silently truncated. The fallback materializes
matching IDs before sorting, avoiding an unbounded ordered heap scan for sparse
terms. Title-order filtered queries still use that complete search and can time
out for broad terms. No global database or proxy resource settings are changed.
The
HTTP layer permits two in-flight queries with an eight-second context budget.
Busy requests return 429 with `Retry-After: 1`; deadlines return 504; storage
errors return a generic 503 without database details. Missing papers return 404.
## Validation
`go test -race -count=1 ./internal/research` covers routing, query limits,
Unicode, anonymous reads, rejected mutations, project lookup, errors, saturation
and timeout slot release. Run compilation/tests only on the user-confirmed ECS
runner. These transport tests do not prove a database connection, full-corpus
query performance or production availability.
The PostgreSQL repository batches source/tag/identifier/submission queries in
the same read-only repeatable-read transaction. Author tuples are displayed as
given name, family name and suffix; an optional fourth affiliation field
is excluded from the display name (observed in real arXiv records); null abstracts/dates remain null. Publication
status comes from the latest observed decision, using decision date and ID as
tie-breakers, and stays unknown when no decision exists. Unit checks cover
author shapes, bound user values and schema qualification. The real Core detail
and homepage HTTP routes have returned 200.
The frontend has also rendered the actual 3,526,999-paper corpus through a
loopback SSH tunnel: eight rows, matching detail title/source, desktop and
mobile layout, no page exceptions or horizontal overflow in that check.
The earlier count-based API returned 146 author records in 0.336 seconds. Before the cursor optimization, after paging/author fixes, category `cs.AR` returned 9,457 records in 4.906
seconds, `CartoonGAN` returned three in 0.332 seconds, and the multi-term search
`attention is all you need` returned 8,653 in 6.325 seconds. These were sequential
manual HTTP checks, not a load test. Very broad text searches can still exceed
the eight-second budget; clients retain search controls so users can narrow
the query or retry. This known limit is not an estimated count or sample
fallback. This is not a
production deployment or an authentication acceptance result.
The existing `deploy/check-schema.sh` also loads the synthetic fixture in
`internal/research/testdata/corpus.sql` inside its disposable PostgreSQL
container (`--network none`, no host port). The research test process receives a
separate SELECT-only fixture role via `RESEARCH_TEST_DATABASE_URL`. These
integration checks execute real SQL for filtering, stable paging, nullable
content, source/tag/identifier joins, latest decision tie-breakers, permission
denial and SQL-backed HTTP routes. They never connect to the shared migration
instance and do not establish full-corpus performance or live-data correctness.
## Text storage compatibility (repair 4e62710)
The Paper Atlas repair uses `nul-soh-v1`: NUL is stored as SOH/SOH, and a
literal SOH as SOH/STX, preserving binary text ordering. Core reads the schema
comment `paper-atlas:text-codec=nul-soh-v1` through `pg_catalog` at startup,
restores SQL text before JSON parsing/API responses, and encodes bound search
terms. An absent/unrelated schema comment keeps legacy text unchanged; an
unsupported marked codec or malformed encoded text fails explicitly.
Schema comments are public metadata, so consumers need no privileges on the
private migration controller. The research role still needs only schema USAGE
and table SELECT. The codec adaptation is on the review branch, pushed with [skip ci] under the
user's no-CI instruction; the published schema marker has been verified with
the runtime reader.
All research tests passed manually against disposable PostgreSQL on the
confirmed ECS, including the encoded SQL fixture for schema detection, raw TEXT restoration,
JSON author/metadata decoding, search and the HTTP round trip. Passing isolated
fixtures does not establish full-corpus API performance.
## Identity handoff
The existing production Core received a configuration-only reload using its
unchanged release binary: the original projects were retained and thesisly was
registered. Both Google and Slack identity records were observed in this
project. The user independently confirmed each provider's real authorization,
reload/new-tab persistence and logout behavior. Browser control was unavailable,
so these browser results are attributed to user acceptance rather than an
automated real-account test. This does not deploy the research work branch;
mail delivery was not exercised.
## Cursor regression coverage
The disposable PostgreSQL fixture covers forward/backward traversal, identical
title keys with different IDs, published control-character encoding, sparse
matches separated by a large ID gap, and fallback from the bounded interval.
Invalid, oversized, cross-filter and wrong-version cursors are rejected before
repository execution. The runtime reader retains SELECT-only privileges; no DDL
or writes are added. Run tests manually on the confirmed ECS; skip CI for this
iteration and retain `[skip ci]` in commit and PR titles.
## Manual cursor measurements (2026-11-07)
On the confirmed ECS, after this task's compilation and disposable fixture had
finished, sequential direct requests to the temporary Core returned: homepage
65 ms, next/previous 39/21 ms, `graph` 345 ms, `CartoonGAN` 731 ms (3 papers),
`cs.AR` 145 ms, title order 180 ms, author `Buhrman` 769 ms, and
`attention is all you need` 1312 ms. Recent, topic and title cursor round trips
returned the same first page without overlap. These are individual manual
samples, not production latency guarantees; concurrent compilation earlier
produced multi-second cold measurements. No proxy, database memory, CPU or
production configuration was changed.
The final source compiled manually on the ECS; package unit checks and all ten
selected cursor/PostgreSQL integration tests passed, including interval expansion
and complete fallback. No CI or local build ran. The local authorized Next dev
uses the temporary API through the existing SSH tunnel. Independent Chrome also
verified real homepage/search navigation, a preserved document, one mobile
header/main, no page exceptions and no horizontal overflow. The production Core
was not replaced by these temporary preview updates.