Chang-LeHung
Chang-LeHung

I am Chang-LeHung (牧牛的铃铛). I am interested in how programming languages are implemented — virtual machines, interpreters, compilers — and lately in how LLM agents work: generating tools on demand, compacting context, and splitting work between agents.

Email: changlehung@(126/gmail).com · GitHub · Blog · CSCore · Dive into CPython

About

I write about Python internals and computer systems, more than 120 pieces so far. Most of them are source-code walkthroughs: take a part of the interpreter, run it, and write down what it does and why it is built that way.

I learn the same way: start from a small program, add one piece at a time, and keep it runnable. Languages, virtual machines, databases and agent runtimes are the things I have rebuilt this way.

“What I cannot create, I do not understand.”

— Richard Feynman

What I work on

  • LLM agent runtimes: a JIT harness — the model writes the tool it needs during the turn, loads it and calls it, instead of picking from a fixed toolbelt — plus session compaction, several agents working on one task, and the local-first knowledge tools around them.
  • The CPython virtual machine: bytecode execution, the object model and compiler optimization; the tutorials follow the source.
  • Compilers and language implementation: lexing, parsing and code generation, written as implementations small enough to run.
  • Distributed systems and performance analysis: sessions, background daemons and message passing between agents; sampling profilers and flame graphs, which is where telex comes in.

Education

Hunan University · M.S. in Computer Science · September 2022 – June 2025 (Recommended Admission)

Experience

  • Tencent · WXG — Software Engineer (C++), October 2024 – Present
    • 支付之星 (youngest recipient) · AI Coding 之星 · 代码委员会优秀委员 (youngest member, selected within first year)
    • Zero production incidents and zero financial loss across owned services
  • Tencent · WXG — Software Engineering Intern, July 2024 – October 2024 (Grade-S internship evaluation, awarded to only a handful across WXG)
  • ByteDance · Douyin E-commerce — Software Engineering Intern, April 2024 – July 2024

Slides

  • Uinmc:微信 64 位 UIN 静态分析与自动迁移框架 — 我发起并开发的 64 位 UIN 存量升级核心工具链(支付之星 / AI Coding 之星获奖项目):基于 Clang/LLVM 构建静态类型检查器 uinc 与污点迁移引擎 taint,结合跨编译单元不动点迭代、AST 磁盘缓存与 AI Agent Skill 协同迁移,已广泛落地 WXG 及微信多部门。

Uinmc:微信 64 位 UIN 静态分析与自动迁移框架

从业务背景、Proto 契约到跨编译单元不动点污点分析

2026-12-03

项目背景:微信 64 位 UIN 存量升级

什么是 UIN?为什么必须升级?

  • 用户唯一标识:UIN 是微信体系内标识用户与公众号的核心数字 ID
  • 32 位空间逼近上限:历史长期使用 uint32_t 存储,最大仅 232≈42.9 亿
  • 演进约束:随着用户与业务主体持续增长,全网必须将 UIN 体系平滑升级至 64 位

存量 C++ 改造的现实难度

  • 分布极广:UIN 遍布数千个后台服务的 RPC 接口、结构体、局部变量、模板容器与存储链路
  • 历史表达混乱:int / uint32_t / uint64_t 混用,命名不统一,无法靠关键词简单检索
  • 必须灰度兼容:全网无法停服一刀切,升级期间必须保证零截断、零资损

核心问题

如何识别海量存量 C++ 代码中所有承载 UIN 语义的程序元素,并在编译阶段强制其一致升级为 64 位?

核心风险:局部升级引发 64→32 位静默截断

仅升级部分服务或字段时,64 位 UIN 流入未升级的 32 位节点,C++ 隐式窄化在编译期常无报错,运行期高 32 位被直接丢弃:

发起方 A(64 位源) 向目标用户 B 发起转账 0x0000_0001_0000_1234 64 bit 未升级的 32 位中间节点 uint32_t uin = req.uin(); 高位 0x0000_0001 被静默截断 剩余低 32 位:0x0000_1234 预期到达 目标用户 B(未收款) UIN: 0x0000_0001_0000_1234 实际落入 错误账户 C(意外入账!) UIN: 0x0000_0000_0000_1234

静默发生 C++ 允许 64 位向 32 位整型隐式窄化,常规编译难以拦截。

严重后果 引发用户串号、路由错位乃至资金误入他人账户。

防御原则 绝不能依赖线上暴露,必须将风险前置到编译期确定性拦截。

Proto 方案:用 wxuin_t 与注解升级接口契约

Proto 注解
message PayRequest {
  optional uint64 payer_uin = 1
    [(WxUin64Type) = "wxuin_t"];
}
service PayService {
  option (UinType) = "wxuin_t";
}
AutoGen 生成的 C++ 接口
class PayRequest {
 public:
  wxuin_t payer_uin() const;
  void set_payer_uin(wxuin_t value);
};

为什么不直接换 uint64_t?

裸整型之间仍允许静默隐式窄化;引入领域类型 wxuin_t(64 位存储 + 独立类型身份),配合 Proto 注解实现:线路兼容 uint64,C++ 入口强类型化。

级别 交互类型 策略
SAFE wxuin_t ↔ wxuin_t 直接传递
GUARDED wxuin_t ↔ uint64_t 显式构造,告警
REJECTED wxuin_t ↔ 32 位/有符号整型 编译期报错

Proto 解决到哪一步?

Wire 保持 uint64 协议兼容,AutoGen 把所有 Getter / Setter 与 RPC 接口统一升级为 wxuin_t,将旧的 32 位调用暴露在编译期门口。

为什么还需要静态分析?契约升级引爆调用链

Proto 解决范围(接口边界) 服务端 Proto 升级 [(WxUin64Type) = "wxuin_t"] AutoGen 新 Client 接口 req.uin() → wxuin_t 约束传入 调用方 Uinmc 接力范围(调用方业务内部 · 跨文件传播) 业务入口变量 uint32_t u = ... 深层函数与结构体 struct User { uint32_t } STL 模板容器 vector<uint32_t> ids 日志与下游边界 LOG("%u") / to_string 跨文件传播 shared.h ↕ A.cpp · B.cpp

深层调用链与模板 Proto 只卡住入口,业务内部仍充斥 uint32_t 变量、结构体与 vector<uint32_t>。

跨头文件多 TU 耦合 一个共享 .h 牵连数十个 .cpp,单文件视角极易漏改或改坏签名。

海量存量人工改不动 需要编译器级工具自动查出全部违规(uinmc)并整条链自动改写(uinmf)。

直观效果:uinmc 定位违规与 uinmf 自动改写

改写前(worker.cpp)

void transfer(uint32_t local_uin) {
  std::vector<uint32_t> recipients{local_uin};
  for (uint32_t uin : recipients)
    send(uin);
}

void handle(const PayRequest& req) {
  uint32_t payer = req.payer_uin();
  transfer(payer);
}
$ uinmc -c src/worker.cpp -p build/
worker.cpp:1:24: error [R15] 'local_uin' is uint32_t
worker.cpp:8:12: error [R3]  cannot convert wxuin_t

改写后(uinmf fmt -c src/worker.cpp -r)

void transfer(wxuin_t local_uin) {   // T3 参数
  std::vector<wxuin_t> recipients{local_uin}; // T5
  for (wxuin_t uin : recipients)     // T1 局部变量
    send(uin);
}

void handle(const PayRequest& req) {
  wxuin_t payer = req.payer_uin();   // T1 局部变量
  transfer(payer);
}
$ uinmc -c src/worker.cpp -p build/
Checked 1 file, no issues found
(Applied: T1 vars / T3 params / T5 template args)

可见效果

返回值产生的 wxuin_t 污点沿赋值、函数参数、容器模板实参与循环变量同步传播改写,复检零诊断。

总体架构:共享污点闭包驱动检查与修复

Input C++ 源码 Proto 契约 compile_db Clang 前端 AST / TypeLoc AST Matchers SourceMgr Analysis Core · 共享污点闭包图 wxuin_t local/vec field/arg uint32_t 普通变量(retry / trace / log)无边隔离 Diagnose(uinmc) R1–R17 规则 · JSON 诊断 · Proto 依赖 Rewrite(uinmf) T1–T8 / C1 自动重写 · .taint.db · DOT 图 Python 编排与多级缓存 多进程调度 · uinmcd HTTP 缓存 · 持久化 TaintCache & AST 缓存 跨 TU 全局不动点闭环(Global Fixed-Point) seed-db 汇总 → 增量重跑 → 收敛后 HeaderLock 一次性落盘
  • 关注点分离:C++ 双引擎静态链接 LLVM/Clang 保证编译器级语义精度;Python 层负责多进程调度、Proto 依赖追踪、跨 TU 不动点与缓存服务

附页:检查规则(R1–R17)与重写规则(T1–T8 / C1)速查

检查规则 覆盖场景
R1–R6 构造、用户定义转换、显式强转
R7–R8 函数参数与返回值隐式转换
R9–R13 二元算术、比较与直接初始化
R15 命名命中 UIN 模式但为裸整型
R16–R17 间接传播整型与容器模板实参
重写规则 改写对象(保留 const / * / &)
T1 / T2 局部/全局变量、结构体成员字段
T3 / T4 函数形参、函数返回值
T5–T8 容器模板实参(如 vector<uint32_t>)
C1 调用点适配(printf / to_string / 取模)

核心算法:单 TU 交互图构建与 BFS 污点传播

算法 1Intra-TU Taint Propagation and Rewriting
Require: Translation unit AST T, initial seed set S0
Ensure: Rewrite sets R (T1–T8, C1), local taint DB D
G←(V=∅,E=∅)
for each match m∈ASTMatchers(T) do
u← nodeFor(m.lhs)
v← nodeFor(m.rhs)
E←E∪(u,v)
end for
Q←S0,S←S0
while Q≠∅ do
x← Pop(Q)
for each y∈NG(x)⧵S do
if ¬Blocked(y) then
S←S∪y
Push(Q,y)
end if
end for
end while
R← Classify(S), D← ExportDB(R)
ApplyRewrites(R)

四个关键 AST 设计(防误污染)

  1. 统一透明剥离 nodeFor() 穿透隐式转换、括号、一元运算与单参构造,直达底层变量或字段节点,避免边断裂。
  2. 选择性声明规范化 VarDecl 合并跨文件声明;FunctionDecl 刻意不合并,杜绝「函数体变量 → 规范形参 → 不同调用点实参」的假路径污染。
  3. 外部库调用隔离与阻断 每个外部库调用分配独立 Synth 节点,并配合 --block-func-regex 阻断通用函数误扩散。
  4. TypeLoc 精确重写 按 Token 区间替换底层整型,原样保留 const、指针、引用与模板结构。

核心算法:跨 TU 不动点迭代与收敛证明

算法 2Cross-TU Fixed-Point Analysis with AST Cache
Require: Module source files F, AST cache directory C
Ensure: Global taint closure S*, rewritten .taint.cpp / .h files
S0←∅,k←1
while true do
if k=1 then
Parse F in parallel (--no-rewrite); dump .taint.db and save ASTs to C
else
Load cached ASTs from C in parallel with --seed-db S0
end if
S1← UnionDB(F) keyed by (real_path, line, col, kind)
if S1=S0 then
break
end if
S0←S1,k←k+1
end while
Run Final Write in parallel with header-lock to emit .taint.cpp / .h

有限格收敛与系统工程优化

  1. 单调算子与最小不动点 有限声明格 L=(2D,⊆) 上,F(S)=S∪⋃tuAtu(S) 单调递增,必在有限步收敛至最小不动点 S*。
  2. 共享头文件作为跨 TU 汇合点 用四元组 (real_path, line, col, kind) 唯一标识声明,消除重载、匿名结构与软链歧义。
  3. AST 磁盘缓存加速 Phase 2+ 直接加载序列化 AST,跳过 C++ 头文件预处理与模板解析,仅重跑图传播。
  4. 并发与缓存一致性 收敛后一次性落盘 + HeaderLock 防头文件竞态;持久化缓存按模块 All-or-Nothing 校验。

Harness Engineering:AI 可验证闭环修复

AI Agent 拆解任务与边界 scope fix-uin Skill 注入规则与迁移模式 rules uinmf 重写 确定性批量改写 patch 真实构建/测试 编译与单测验收 verify uinmc 诊断 JSON 残余违规 diagnose 未清零则携结构化诊断继续迭代,直到编译通过且 uinmc 零报错

Knowledge · 领域知识 通过 fix-uin Skill 注入 64 位生成规则与典型迁移模式。

Tools · 确定性接口 uinc 静态诊断、uinmf 自动重写、真实构建与 diff 对比。

Guardrails · 验收门禁 真实编译 + uinc 零报错为停止条件,连续失败即终止。

落地与认可

发起人 & 作者 · 获 支付之星 / AI Coding 之星 · 已广泛落地 WXG 及微信多部门,成为 64 位 UIN 存量升级核心工具链。

  • 精简 x86-64 协程切换寄存器保存 — 我在 WXG 做的一项底层优化:基于 System V AMD64 ABI 精简 colib 中 coctx_swap 汇编的寄存器读写,核心切换指令数减少 39%,纯切换耗时降低约 11%,推动微信后台业务整体吞吐量提升 0.8%,折合每年节省数万 CPU 核心(千万级算力成本)。

精简 x86-64 协程切换寄存器保存

基于 System V AMD64 ABI 的微信后台 colib 汇编优化

2026-12-02

1. 结论先行:背景与核心收益

业务背景

  • 微信后台 svrkit 使用 colib 执行用户态协作式协程
  • 单次请求常多次等待下游 RPC 或锁,高频经过底层切换汇编 coctx_swap
  • 原版 x86-64 实现每次切换都冗余保存并恢复 6 个 caller-saved 寄存器

优化方案

  • 依据 Linux x86-64 System V AMD64 ABI,删去多余寄存器读写
  • 合并 rsp 保存指令,同步精简自动销毁路径 coctx_swap2
指标 优化前 优化后 变化
汇编指令数(含 ret) 28 17 -39%
内存写 / 读次数 13 / 13 7 / 9 -46% / -31%
纯切换 (GCC 7.5) 10.68 ns 9.53 ns -10.8%
纯切换 (Clang 23) 10.31 ns 9.19 ns -11.0%
co_resume / co_yield ~52 ns ~50 ns -3.2%

规模化收益

推动微信后台业务整体吞吐量提升约 0.8%,在全网集群规模下折合每年直接节省数万 CPU 核心(千万级算力成本)。

2. 问题从哪来:一次请求的协程切换链路

svrkit 预创建工作协程池复用处理请求;业务按同步方式写 RPC,底层由 syscall hook 触发用户态切换:

空闲工作协程池 预创建 N 个复用 取请求 执行业务逻辑 同步发起下游 RPC hook 挂起 coctx_swap 高频热路径(用户态) 切回 事件循环 调度其他协程 epoll fd 就绪 co_resume 再次经过 coctx_swap 恢复同一协程继续执行 请求结束,归还空闲队列 单次请求每等待一次下游 RPC / 锁,就发生至少 2 次 coctx_swap(挂起 + 恢复),且不陷入内核
  • 高频热路径:业务一次请求往往串行/并发访问多次下游 RPC、缓存与存储,coctx_swap 是全进程调用最密集的底层函数之一
  • 工作池复用:等待 I/O 的协程仍占用池内名额并保留完整调用栈,线程只负责切换去运行其他就绪协程

补充:有栈 vs 无栈,对称 vs 非对称

维度 有栈(colib / Go) 无栈(C++20 / Rust)
执行现场 独立或共享调用栈 + 寄存器 编译器状态机 + 帧对象
挂起深度 任意调用深度,可 hook 系统调用 需沿调用链逐层 await
切换方式 底层汇编换 rsp 与寄存器 再次调用状态机函数跳转
内存开销 独立栈(默认 128 KB)或共享栈 仅存必要状态,更轻量
  • 非对称:yield 只能回到 resume 它的调用方(colib、Lua)
  • 对称:任意协程可直接交出控制权(如 boost.context)

为什么微信后台选择有栈协程?

存量 C++ 同步业务代码体量巨大,有栈协程配合 syscall hook 可在任意调用深度无侵入挂起,避免 async / await 沿整条调用链层层传染。

补充:各语言与库的协程实现

语言 / 库 类型 实现要点
Go goroutine 有栈 可增长小栈;协作让出走 gogo / mcall,1.14+ 信号异步抢占需保存全部寄存器
Java 21 虚拟线程 有栈 基于 Continuation,挂起时将栈帧拷到堆上 stack chunk
Lua coroutine 有栈(VM) 独立 lua_State 与 Lua 栈,切换在解释器内部完成
C++20 / Rust / Kotlin 无栈 编译器生成状态机与帧对象,由执行器 poll / Continuation 推进
Python 两类都有 async def 无栈;greenlet 通过拷贝 C 栈片段实现有栈切换
C/C++ 库 有栈 ucontext(调 sigprocmask 进内核,慢)、boost.context、libco / colib

补充:colib 核心结构与 co_resume 流程

co_routine.cpp(简化)
void co_resume(stCoRoutine_t* co) {
  auto* env = g_local_env;
  auto* curr = env->pCallStack[env->iCallStackSize - 1];
  if (!co->cStart) {
    coctx_make(&co->ctx,
               (coctx_pfn_t)CoRoutineFunc, co, 0);
    co->cStart = 1;
    co->ctx.pco = co;
  }
  env->pCallStack[env->iCallStackSize++] = co;
  co_swap_wrapper(curr, co, env);
}
  • stCoRoutine_t 管理入口、状态与栈内存
  • coctx_t 仅存 regs[14]、pco 与栈边界(不存栈内容)
  • pCallStack 记录谁唤醒了谁,不是 CPU 调用栈
regs[14] 槽位(偏移) 寄存器 角色
regs[0..3] (0..24) r15–r12 callee-saved
regs[4..5] (32..40) r9, r8 caller-saved(冗余)
regs[6] (48) rbp callee-saved
regs[7..8] (56..64) rdi, rsi 首次启动传参
regs[9] (72) ret 历史遗留槽位
regs[10..11] (80..88) rdx, rcx caller-saved(冗余)
regs[12] (96) rbx callee-saved
regs[13] (104) rsp 栈指针

3. 底层机制:一次切换到底做了什么?

按 SysV 调用约定,进入 coctx_swap(cur, next) 时 rdi = cur、rsi = next,当前返回地址已压在栈顶:

当前协程 cur(挂起) cur->regs[14] 保存 rsp + callee-saved cur 独立栈 call 压入的返回地址 ← rsp 局部变量与完整调用链 ① 保存当前寄存器与 rsp 写入 rdi(cur->regs) ② 恢复寄存器并切换 rsp 从 rsi(next->regs)加载 ③ 执行 ret 跳转 从 next 栈顶弹出返回地址 目标协程 next(恢复) next->regs[14] 含 rsp + 首次入口 rdi / rsi next 独立栈 上次返回地址 / pfn ← rsp 无需显式保存 rip
  • 首次启动:coctx_make 将入口地址 pfn 写入 16 字节对齐的新栈顶,ret 弹出后 rsp ≡ 8 (mod 16) 正好满足 ABI

补充:coctx_make 与 coctx_swap2

coctx.cpp
int coctx_make(coctx_t *ctx, coctx_pfn_t pfn, const void *s, const void *s1) {
  char *sp = ctx->ss_sp + ctx->ss_size - sizeof(void *);
  sp = (char *)((unsigned long)sp & -16LL);     // 16 字节对齐
  memset(sp + sizeof(void *), 0, sizeof(void *));
  memset(ctx->regs, 0, sizeof(ctx->regs));
  *(void **)sp = (void *)pfn;                   // 入口地址作返回地址
  ctx->regs[kRSP] = sp;
  ctx->regs[kRETAddr] = (char *)pfn;
  ctx->regs[kRDI] = (char *)s;                  // arg1
  ctx->regs[kRSI] = (char *)s1;                 // arg2
  return 0;
}
  • 栈顶对齐与回溯终止:sp 向下 16 字节对齐,ret 弹出 pfn 后 rsp ≡ 8 (mod 16) 满足 SysV ABI;栈顶清零确保栈回溯在此自然停止
  • coctx_swap2 安全释放:协程结束需自动释放时,不能在自身栈上释放自身,因此先切到目标栈再调 co_free_inner,随后恢复目标现场

4. 问题定位:原版 28 条指令里的冗余读写

优化前:保存 cur(14 条)
leaq (%rsp), %rax     # 可合并
movq %rax, 104(%rdi)  # rsp
movq %rbx, 96(%rdi)
movq %rcx, 88(%rdi)   # ✗ caller
movq %rdx, 80(%rdi)   # ✗ caller
movq %rsi, 64(%rdi)   # ✗ caller
movq %rdi, 56(%rdi)   # ✗ caller
movq %rbp, 48(%rdi)
movq %r8,  40(%rdi)   # ✗ caller
movq %r9,  32(%rdi)   # ✗ caller
movq %r12, 24(%rdi)
movq %r13, 16(%rdi)
movq %r14, 8(%rdi)
movq %r15, (%rdi)
优化前:恢复 next(14 条)
movq 48(%rsi), %rbp
movq 104(%rsi), %rsp
movq (%rsi), %r15
movq 8(%rsi), %r14
movq 16(%rsi), %r13
movq 24(%rsi), %r12
movq 32(%rsi), %r9    # ✗ caller
movq 40(%rsi), %r8    # ✗ caller
movq 56(%rsi), %rdi   # 保留: arg1
movq 80(%rsi), %rdx   # ✗ caller
movq 88(%rsi), %rcx   # ✗ caller
movq 96(%rsi), %rbx
movq 64(%rsi), %rsi   # 保留: arg2
ret

优化空间汇总

原版共 28 条指令(13 次内存写 + 13 次内存读);其中 6 写 + 4 读为冗余 caller-saved 寄存器,外加 leaq (%rsp), %rax 可直接合并为 movq %rsp, 104(%rdi),共可精简 11 条指令(-39%)。

5. 理论依据:System V AMD64 ABI 与边界

类别 寄存器 ABI 约定 协作切换处理
caller-saved rax, rcx, rdx, rsi, rdi, r8–r11, xmm0–xmm15 被调函数可修改;调用方自保 无需保存
callee-saved rbx, rbp, r12–r15 返回前必须原样恢复 必须保存/恢复
栈指针 rsp 指向当前函数调用栈顶 显式保存/恢复
  • 对编译器而言,coctx_swap() 就是普通函数调用,调用后仍需使用的变量已存入 callee-saved 或栈上

适用边界:仅限协作式切换

抢占式切换(信号处理、Go 1.14+ 异步抢占)可发生在任意指令处,必须保存全部寄存器。

6. 工程落地:三个关键细节与精简版汇编

① 为什么保留 rdi / rsi 的加载?

  • 首次启动时,coctx_make 将两个入口参数写在 regs[7]、regs[8],必须装入 rdi / rsi 传给 CoRoutineFunc
  • 后续恢复从 coctx_swap() 返回,调用方已视 rdi / rsi 被破坏,装入任何值无副作用

② 为什么 rsi 必须最后加载?

  • rsi 同时是指向 next 的基址指针,提前覆盖会导致后续访存错误

③ rsp 合并与 coctx_swap2 保护

  • 直接 movq %rsp, 104(%rdi),省 1 条指令且不占 rax
  • coctx_swap2 调 co_free_inner 前后保留 rsi 的 push / pop
优化后:coctx_swap(17 条)
# 保存 cur(7 条)
movq %rsp, 104(%rdi)
movq %rbx, 96(%rdi)
movq %rbp, 48(%rdi)
movq %r12, 24(%rdi)
movq %r13, 16(%rdi)
movq %r14, 8(%rdi)
movq %r15, (%rdi)
# 恢复 next(9 条 + ret)
movq 48(%rsi), %rbp
movq 104(%rsi), %rsp
movq (%rsi), %r15
movq 8(%rsi), %r14
movq 16(%rsi), %r13
movq 24(%rsi), %r12
movq 96(%rsi), %rbx
movq 56(%rsi), %rdi  # arg1
movq 64(%rsi), %rsi  # arg2(最后)
ret

补充:跨架构边界(为什么不能直接照搬 ARM64)

不同指令集架构的 ABI 约定不同,精简列表必须逐架构核对:

架构 调用约定 浮点 / 向量寄存器规则
x86-64 System V AMD64 ABI xmm0–xmm15 全部为 caller-saved,协作切换无需保存
AArch64 AAPCS64 要求 callee 保存 v8–v15 的低 64 位(即 d8–d15)

工程约束

不能把 x86-64 的精简列表直接套用到 ARM64;同时保持 coctx_t.regs[14] 结构体偏移布局不变,确保零二进制兼容性风险。

  • 增量演进原则:只删汇编中冗余的 movq 读写,不改动结构体大小与字段偏移,避免影响依赖固定偏移的调试工具或历史二进制模块

7. 量化验证与理性归因

1000 万轮(每轮 2 次切换),taskset -c 2 绑核,区分纯切换与公开接口:

编译器 场景 原版 精简版 降幅
GCC 7.5 纯切换 10.68 ns 9.53 ns -10.8%
Clang 23 纯切换 10.31 ns 9.19 ns -11.0%
GCC 7.5 resume/yield 52.13 ns 50.51 ns -3.3%
Clang 23 resume/yield 51.24 ns 49.35 ns -3.1%
  • 正确性验证:条件变量交接、压测、svrkit 服务实跑
纯切换耗时对比(ns / 次,越低越好) GCC 7.5 原版 10.68 GCC 7.5 精简 9.53 (-10.8%) Clang 23 原版 10.31 Clang 23 精简 9.19 (-11.0%)
  • 指令少 39% 而耗时降 11%:现代 CPU 乱序执行可并行发射部分寄存器读写,换栈与 ret 跳转有固有开销
  • 克制归因:co_resume / co_yield 约 50 ns(含调用栈与指标统计),纯切换 11% 不等同于服务整体吞吐提升

8. 复盘与方法论

  1. 回到契约本身:协作式切换发生在普通函数调用点,遵守 System V AMD64 ABI 只需保存 rbx、rbp、r12–r15 与 rsp
  2. 扣紧边界与反例:保留首次启动所需的 rdi / rsi 加载(且 rsi 置尾)与 swap2 保护;明确不适用于抢占式切换与 ARM64
  3. 用数据说话、克制归因:消除 11 条冗余指令 → 纯切换 -11%、公开接口 -3%,零 ABI 破坏、全量压测与服务实跑通过

延伸交流方向

欢迎进一步讨论:独立栈 vs 共享栈的内存与拷贝权衡 · syscall hook 与 epoll 事件循环协作 · 微基准与线上吞吐归因方法。

Selected Projects

Agents and knowledge tools

  • ZettCode — A coding agent in your terminal, built on a JIT harness: every reasoning step and tool call is shown as a readable row, and it asks before it runs a shell command. In a single turn the model writes a small Python tool, loads it and calls it; it can hand a code review to a second agent, or keep running in the background and message other sessions.
  • Zett Agent — The lightweight Python runtime behind ZettCode, installable from PyPI: one provider-neutral loop with a JIT harness, where tools and skills are written and loaded on demand instead of up front, plus sessions, compaction, subagents and composable extensions.
  • Zett — A local-first, AI-assisted knowledge workspace that turns fleeting thoughts, conversations, links and assets into cards, articles, slides or papers. No account, no cloud workspace; everything stays on 127.0.0.1 on your own machine.

Tools

  • telex — A sampling profiler for Python: it grabs the stack every 8 ms by default, folds the samples into an interactive SVG flame graph, merges results across processes, and filters by file, function or regular expression so you only see the code you care about. GC analysis and a PyTorch profiler integration come with it.

Languages and systems

  • Dive into CPython — Tutorials on CPython internals, from the object model to bytecode execution.
  • CSCore — A tutorial series on computer systems fundamentals: data structures, algorithms, operating systems and compiler principles.
  • SPL — A coroutine-oriented programming language with functional programming support, including a compiler and virtual machine implementation.
  • JPVM — A lightweight, GIL-free Python virtual machine: faster startup and a smaller memory footprint than Jython and GraalPy.
  • Core-VM — A minimal template interpreter that explains how JVM-based interpreters work.

More projects on GitHub.

Contact

Feel free to email me at changlehung@126.com or changlehung@gmail.com about agents and LLMs, programming languages and virtual machines, or distributed systems and performance analysis.

微信公众号:一无是处的研究僧

微信公众号二维码:一无是处的研究僧

全部 119 篇文章 · 按标签浏览