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

  • 精简 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 篇文章 · 按标签浏览