Skip to content

computers.gateway_key_hash 加唯一索引,网关认 key 不再扫全表 - #83

Merged
joesmart merged 1 commit into
mainfrom
joesmart/perf-gateway-key-index
Oct 23, 2026
Merged

joesmart merged 1 commit into
mainfrom
joesmart/perf-gateway-key-index

Conversation

@joesmart

Copy link
Copy Markdown
Contributor

改了什么

给 computers.gateway_key_hash 加唯一索引 computers_gateway_key_hash_idx,迁移 0048_computers_gateway_key_hash_idx.sql 由 pnpm --filter @baize/control-plane generate 生成,已有迁移没动。

为什么

网关每次模型请求都走 findComputerByGatewayKey,只凭哈希反查电脑,原先这一列没有索引,每次扫全表;列也不唯一,万一重复 limit(1) 会默默取第一行。唯一索引把查找变成索引扫描,重复在写入时就会被拒绝。

其他按秘密查身份的列逐个看过,不需要加:

  • computers.token_hash:authenticateComputer 先按主键 id 取行,再在内存里 timingSafeEqual 比对,从不作为查询条件。
  • sessions:token 本身就是主键 id。
  • oauth_states.state:主键。
  • webhook token:走 routines_triggers_idx(GIN),schema 注释写明了不做全局唯一约束的理由,本 PR 不改。

数据核对:gateway_key_hash 是 notNull,值为 hashSecret(32 字节随机数),每次 hello 都会轮换;开发库 computers 2 行、2 个不同哈希、0 个 null,迁移不会撞上唯一约束。

怎么验证的

在临时库上跑全部 49 个迁移,插入 2 万台电脑后 EXPLAIN ANALYZE:

explain analyze select * from computers where gateway_key_hash = encode(sha256('k12345'::bytea),'hex') limit 1;

 Limit  (cost=0.41..8.43 rows=1 width=269) (actual time=0.016..0.016 rows=1 loops=1)
   ->  Index Scan using computers_gateway_key_hash_idx on computers  (cost=0.41..8.43 rows=1 width=269) (actual time=0.009..0.009 rows=1 loops=1)
         Index Cond: (gateway_key_hash = '054b40ca...b347'::text)
 Execution Time: 0.022 ms

同一个库在事务里 drop 掉这个索引对照:

 Limit  (cost=0.00..727.00 rows=1 width=269) (actual time=1.208..1.209 rows=1 loops=1)
   ->  Seq Scan on computers  (cost=0.00..727.00 rows=1 width=269) (actual time=1.208..1.208 rows=1 loops=1)
         Rows Removed by Filter: 12344
 Execution Time: 1.227 ms
pnpm format:check && pnpm typecheck && pnpm lint      # 通过
pnpm --filter @baize/control-plane generate           # No schema changes, nothing to migrate
pnpm --filter @baize/control-plane test               # Test Files 117 passed | 1 skipped,Tests 1530 passed | 1 skipped
pnpm --filter @baize/e2e test                         # Test Files 26 passed,Tests 53 passed

没有加测试:这次改动没有用户能观察到的行为变化,按约定不写断言索引存在的测试。

Closes #22

🤖 Generated with Claude Code

https://claude.ai/code/session_01DKvSzuVcWTvHeLZgmkKVrh

@joesmart
joesmart force-pushed the joesmart/perf-gateway-key-index branch from 5609e64 to 230af84 Compare October 23, 2026 14:09
@joesmart
joesmart merged commit 8353ca7 into main Oct 23, 2026
1 check passed
@joesmart
joesmart deleted the joesmart/perf-gateway-key-index branch October 23, 2026 14:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

computers.gateway_key_hash 没有索引,每次模型请求扫全表

1 participant