多线程确定性是怎么做到的 How a Parallel Simulation Stays Deterministic
让几千个线程跑出来的结果逐位一致 · 2026-11-22What keeps thousands of threads bit-identical · 2026-11-22
系列这些文章写给人和他的 agent 一起看。这套文档怎么读 →SeriesThese posts are for you and your agent. How to read these docs →
先把"确定性"收窄到可以检验的说法 Narrow the Word Until It Can Be Tested
“确定性”这个词太大,检验不了,先把它收窄:同样的输入、同样的种子、同样的二进制、同样的硬件,两个进程跑同一段模拟,最后的状态逐位一致。四个前提少一个,这句话就不成立。跨平台一致是另一个问题,那是定点数的活,另一篇讲过。
"Deterministic" is too big a word to test. Narrow it: same input, same seed, same binary, same hardware, and two processes running the same simulation end up bit-identical. Drop any one premise and the claim is false. Cross-platform agreement is a separate problem, the fixed-point one, covered in another post.
为什么要这么苛刻?锁步里两端各算各的,没有人广播“正确答案”。一帧对不上,差异就只会往大里滚,几十帧之后连一条指令落在哪都不一样了。确定性是这套联机方式的前提,没有它就没有这回事。
Why so strict? In lockstep each peer computes its own answer and nobody broadcasts the right one. One frame of disagreement compounds; a few dozen frames later, a command lands somewhere else entirely. Determinism is what makes this mode possible at all.
第一条规则:发生在该发生的时候 Rule One: Happening at the Right Moment
最容易漏的一条跟数学没关系:任何对 Mass 实体状态的读写,都必须发生在位置固定的处理器里,或者定义明确的子系统边界上。RPC 回调、引擎回调(PostLogin、BeginPlay、OnRep_*)、定时器委托,这些都不是可预测的执行点,什么时候触发由引擎决定。
The easiest rule to miss has nothing to do with arithmetic: every read and write of Mass entity state happens inside a processor at a fixed position, or at a well-defined subsystem boundary. RPC handlers, engine callbacks (PostLogin, BeginPlay, OnRep_*), timer delegates — the engine decides when those fire, so none of them is a predictable point of execution.
我们真在这上面栽过:有个函数直接在“客户端请求重同步”的 RPC 里抓实体快照。两个服务器在同一个 tick 的不同时刻收到这条 RPC,抓到的就是不同的状态,快照不同,客户端恢复出不同的世界,永久失步。修法是把形状改掉:RPC 只置标记或入队一个 id,下一个 tick 由固定位置的处理器去抓,tick 末由子系统消费缓存。
We hit this one for real: a function captured an entity snapshot straight inside the "client requests resync" RPC. Two servers receiving that RPC at different points of a tick capture different states — different snapshot, different recovered world, permanent desync. The fix was a change of shape: the RPC only sets a flag or enqueues an id; a processor at a fixed position captures on the next tick; the subsystem consumes the cache at end of tick.
这条最后会变成一句很硬的话:你在不可预测的上下文里需要“此刻的实体状态”,只能让下一个确定性 tick 去抓,再从缓存里取;当场查,查到的值本身就不确定。
If you need the entity state right now and you are standing in an unpredictable context, have the next deterministic tick capture it and read the cache. Query it in place and the value itself is not determined.
并行本身不破坏确定性 Parallelism Is Not the Enemy
很多人以为要确定性就得单线程。不用。并行只要守住一条:每次迭代只写自己的槽位,两个线程不写同一块内存。守住这条,并行波里算出来的结果就是确定的,因为每个实体的输出只依赖它自己的输入。
The reflex is that determinism means single-threaded. It does not. A parallel pass needs one thing above all: each iteration writes its own slot, and no two threads write the same memory. Meet that and the wave is deterministic, since each entity's output depends only on its own input.
真正破坏确定性的是另外三样,下面各占一节:顺序(同一批东西以不同次序被访问)、共享写入(两个写者,或者读到别人正在写的东西)、未定义的值(没初始化的内存、浮点的边缘状态)。并行只是让这三样更容易出现,它本身不是原因。
Three other things actually break it, one section each below: order (the same set visited in a different sequence), shared writes (two writers, or a read of something mid-write), and undefined values (uninitialised memory, float edge states). Parallelism makes all three more likely; it is not the cause.
顺序:只能靠排序要回来,而键只能用"两端都有的东西" Order: You Buy It Back with a Sort, Keyed Only on What Both Peers Have
并行跑完,结果的顺序取决于哪个线程先完成,也就是不可复现。要拿回唯一的顺序,只能排序;排序要有效,键得是两端都相同的量。所以我们有一条硬规则:排序键只能用 UniqueID 或静态数据,实体句柄的 Index 绝不能出现。
After a parallel pass, order follows whichever thread finished first, which is not reproducible. The only way back is a sort, and a sort only helps when the key is a quantity both peers share. So: sort keys may use UniqueID or static data, never the entity handle's Index.
原因很具体。重同步时客户端按 (EntityType, UniqueID) 的顺序重建实体,它那边的句柄 Index 顺序就等于 UID 顺序;服务器从不恢复,Index 还是历史上的创建顺序。同一批实体,两端 Index 的相对顺序不一样,任何按 Index 排的队列,恢复之后都会排出不同结果。
The reason is concrete. On resync the client rebuilds entities in (EntityType, UniqueID) order, so its handle Index order equals UID order; the server never restores and keeps creation history. The same set of entities has a different relative Index order on the two peers, so any queue sorted by Index sorts differently after a recovery.
| 反模式Anti-pattern | 为什么错Why it fails |
|---|---|
直接用 A.Entity.Index < B.Entity.IndexPlainly A.Entity.Index < B.Entity.Index |
恢复后两端 Index 顺序不同,池顺序分叉After recovery the Index orders differ and the pool order forks |
| "主键唯一,次键用 Index 理论上不会触发""The primary key is unique, so the Index tiebreaker never fires" | 不允许,就算能证明安全也不允许。它把一个“今天恰好不触发”的假设留在了代码里Not allowed, not even when provably safe. It leaves a "happens not to fire today" assumption in the code |
| 有 UID 用 UID、没有就退回 IndexUse UID when present, fall back to Index when absent | 一旦混进一个本地实体(UID = -1),整段就退回 Index,分叉One local entity (UID = -1) in the mix drops the whole comparison back to Index and forks |
正确写法没几种:全网络实体直接按 UID 排;本地实体(UID 为 -1)统一用 MIN_INT 排到最前;要二级键也只能用别的确定性量(附着目标的 UID、配置枚举),仍然不许 Index。还有一个更细的坑:Algo::Sort 不稳定,比较器最后必须落到 UniqueID 上,距离相同、分数相同的两个实体,不带 UID 的话两次跑出来的顺序可以不一样。
The correct forms are few. Networked entities sort on UID. Local ones (UID = -1) map to MIN_INT and come first. A secondary key has to be another deterministic quantity (the attach target's UID, a config enum), never Index. One finer trap: Algo::Sort is not stable, so the comparator always has to end on UniqueID; two entities at the same distance or the same score can otherwise come out in a different order between runs.
收集器:并行结果先收成一条队列,排序后再串行消费 Gatherers: Collect, Sort, Then Consume Serially
跨实体的产物(伤害、生成请求、网格登记、待移除的渲染器)不能就地写进共享结构,于是走收集器:并行段里各线程往自己的槽里塞,合并成一条数组,排序之后再串行消费。它解决两件事:线程安全和顺序确定。一个没排序的收集器,等于把随机顺序喂给下游所有逻辑。
Cross-entity products — damage, spawn requests, grid registrations, renderers to drop — cannot be written into shared structure in place, so they go through a gatherer: each thread pushes into its own slot, the slots merge into one array, and that array is sorted before it is consumed. It solves two things: thread safety and a determinate order. An unsorted gatherer is a random sequence piped into everything downstream.
遍历也一样:按排好序的键走,绝不能用 TSet / TMap 的遍历顺序,哈希顺序在进程之间不保证一致。这条看着琐碎,可“什么都没改,结果变了”十有八九出在这里。
Iteration works the same way: walk sorted keys, never the traversal order of a TSet or TMap, because hash order is not guaranteed to agree between processes. Sounds trivial; it is the most common shape of "nothing changed but the result did".
排序的代价也不是无条件付的:SortByUniqueID 第一行就是 if (bDeterministic)。不需要逐帧一致的单机模式直接跳过,这份代价只为"两端同一结果"付。
And the cost is conditional: the first line of SortByUniqueID is if (bDeterministic). Single-player modes that do not need frame agreement skip the sort entirely; the cost is paid for peer agreement.
跨实体读:一条遍历里既写又读,就必须读副本 Cross-Entity Reads: If One Traversal Both Writes and Reads, Read a Copy
这一类最隐蔽。判据是同一个遍历里,这个字段是不是既被写、又被跨读,跟跨不跨实体没关系。是的话,你读到的值取决于目标先跑还是后跑。四种情况里,前三种安全,第四种要加条件:
This class is the hardest to see. The criterion is whether one traversal both writes the field and cross-reads it; crossing entities is not the question. If it does, the value you read depends on whether the target ran before or after you. Of the four cases, three are safe and the fourth needs a condition:
| 情况Case | 结论Verdict |
|---|---|
| 这一趟只读它(写发生在更早、已完成的阶段)This pass only reads it (the write happened in an earlier, completed stage) | 现读就是确定的A live read is deterministic |
| 这一趟只写它This pass only writes it | 本趟没有读者受影响No reader inside the pass is affected |
| 同一趟既写又跨读The same pass writes it and cross-reads it | 必须读一个在本波之前就已经写完的副本Must read a copy finished before this wave |
| 跨实体写(A 改 B 的片段)Cross-entity write (A mutates B's fragment) | 有条件允许,但我们一律不这么写。改值不动原型、不动结构,所以它本身不违反线程安全的规矩:只要能保证每个目标恰好一个写者,直接写是可行的。这里要求的是每个目标只有一个写者,跟图有没有环无关:A 写 B、B 写 C、C 写回 A 没关系,每个目标仍然只有一个写者。致命的是多个写者落到同一个目标:A 和 B 都在写 C,最后留下谁的值取决于调度。并行循环里所有实体跑同一段逻辑,这种多对一几乎必然出现,所以规矩是:除非你能点名每个目标的唯一写者,一律走收集器。Conditionally fine, and still something we never do. Writing a value moves no archetype and no structure, so it is not a thread-safety taboo in itself: as long as every target has exactly one writer, a direct write works. What is required is a function, one writer per target, and the graph may cycle: A writes B, B writes C, C writes back to A is fine, because each target still has one writer. What is fatal is two writers on the same target: if A and B both write C, the scheduler decides which value survives. A parallel loop runs the same logic for every entity, so that many-to-one pattern turns up almost immediately — hence the rule: unless you can name a sole writer for every target, go through a gatherer. |
“副本”在生产里有四种形态:帧首网格更新时逐实体自写的 PreLocation;索敌处理器在循环开头刷新的目标快照(TargetLocation 及同族);网格里那份 64 字节每单位记录,这也是移动从不解引用邻居片段的原因;以及收集器加串行排序冲刷。
Four shapes of "a copy" are in production: PreLocation, written per entity by the frame-start grid pass; the target snapshot the trace processor refreshes at loop top (TargetLocation and its siblings); the 64-byte per-agent record in the hash grid, which is why move never dereferences a neighbour's fragment; and a gatherer with a sorted serial flush.
副本要算“稳定”,两条都得满足:写入那一趟在两端都早于消费方,写入本身与顺序无关(逐实体自写,或者串行排序之后写)。在消费那一趟里现刷的缓存,两条都不满足。
A copy counts as stable only when both hold: its writing pass finishes before the consumer on both peers, and the write itself is order-independent (a per-entity self-write, or a serial one after a sort). A cache refreshed inside the consuming pass satisfies neither.
最后是一个测试上的陷阱,值得单独说一句。我们给每一处并行都编了号,可以强制全部单线程跑。可单线程跑绿了说明不了什么:它只消掉了调度抖动,顺序依赖还在,重同步之后照样分叉。
One testing trap deserves its own line. Every parallel region carries a name and can be forced single-threaded. But a green run under that proves nothing: it removes scheduling jitter; order dependence stays, and the fork comes back after a resync.
随机与编号:不能让"谁先跑"决定结果 Randomness and IDs: Never Let "Who Ran First" Decide
随机数只有一种安全用法:每个实体一条自己的随机流,用它的 UniqueID 播种。共享一个随机源就完了,谁先抽谁拿到第一个值,而“谁先”本身就不确定。
Randomness has one safe use: a stream per entity, seeded from its UniqueID. A shared source is fatal; whoever draws first takes the first value, and who that is depends on scheduling.
编号也一样:在并行里分配 ID 是不确定的,分配顺序就是线程完成顺序。要么把编号挪到串行段,要么让并行段只产出“候选”,按上游 UID 排序后由串行段分配。这类错误很讨厌,不崩也不报,只是两端的对象带着不同的编号活一辈子。
Identifiers are the same: allocating ids in parallel is not deterministic, because allocation order is completion order. Move allocation into a serial section, or let the parallel pass emit candidates and have the serial section assign after sorting by upstream UID. This class is nasty — nothing crashes, nothing warns, and the two peers live with differently numbered objects forever.
快照:当帧的可以不进,跨帧的必须进 Snapshots: Same-Frame May Stay Out, Cross-Frame Must Go In
判据一句话:当帧产出、当帧消耗的值可以不进快照;跨逻辑帧的运行时可变值必须进。但“当帧”是个要举证的义务,跟类型没关系——你得能指出那一趟 pass,它在这个 tick 内、在所有消费者之前重算这个值,而且它的输入本身已经注册。指不出来,它就是状态。
The criterion is one line: a value produced and consumed in the same logical frame may stay out of the snapshot; a runtime-mutable value that outlives the frame must go in. But "same frame" is a proof obligation, not a property of a type: point at the pass that recomputes it, inside that tick, ahead of every consumer, from inputs that are themselves registered. Fail to point at it and the value is state.
而有一种组合绝对不能有:跨帧状态只进哈希、不进快照。它会折进逐帧哈希,分叉能被发现;可它不进快照,重建或重同步会把这一端复位成默认值,另一端还留着原值。哈希要等 resync 把现场盖掉之后,才把症状报出来。我们植入过一个缺陷,正是这个形状:一个指数平滑速度从快照行里删掉,却留在哈希行里。
And one combination must never exist: a cross-frame value that is hashed but not snapshotted. It folds into the per-tick hash, so a fork is caught; it never enters the snapshot, so a rebuild resets it to the default on one peer while the other keeps its own value. The hash reports the symptom only after the resync has already overwritten the scene. One defect we planted had exactly this shape: an exponentially smoothed speed dropped from the snapshot row and left in the hash row.
这条判据是不对称的,审计也照这个不对称来做:进了哈希没进快照,报错;进了快照没进哈希,只提示。能恢复但没被校验通常是合法的(网络元数据、静态数据)。
The criterion is asymmetric, and the audit follows it: hashed without snapshot is an error; snapshotted without hashing is a note. Restored but unverified is usually fine — network metadata, static data.
未初始化的位域,是"逐进程的内存史" Uninitialised Bitfields Are Per-Process Memory History
这一条平时看起来像洁癖,直到它真的分叉一次:结构体构造函数里漏掉的位域,值是不确定的,它取决于这块内存在这个进程里之前被谁用过,所以两个进程不一样。只要有一处拿它做过判断(if (N.bIsObstacle) continue; 这种),两端就走上了不同的分支。
This one reads like hygiene until it forks once: a bitfield missing from a struct's constructor holds an indeterminate value, whatever that memory was used for earlier in this process, and the two processes differ. One decision taken from it (if (N.bIsObstacle) continue;) sends the peers down different branches.
它的指纹很好认,难查也正是因为这个:哈希里的浮点值小数点后十几位都对得上,某个布尔判定却翻了。看到这个组合,先怀疑没初始化的成员,别去怀疑浮点。
Its fingerprint is easy to state, which is exactly why it is hard to find: the hashed floats agree to fourteen decimal places while a boolean verdict flips. With that combination, suspect an uninitialised member before you suspect the floats.
纪律:让错误的写法不可能通过 Discipline: Make the Wrong Shape Fail Fast
上面每一条都能写成“注意点”,可“注意点”会被忘。所以我们能把它们变成不变量的都变了:顺序错了启动就崩(物理必须在移动之后,通知必须在物理之后,Host 独占最后一段,全是 checkf);排序键里出现句柄 Index 就是违规,每写完一段代码要专门审一遍 .Sort(;新增并行段必须过那十一条检查单。
Every rule above could be phrased as "be careful", and "be careful" gets forgotten. So whatever can become an invariant does: a wrong order crashes at startup (physics after move, notify after physics, Host alone in the last stage, all checkf); a handle Index in a sort key is a violation, and every .Sort( gets a review; every new parallel pass goes through the eleven-point checklist.
还有一条查错时的纪律,替我们省了很多时间:先信框架,再查输入。同样的输入和种子必然给出逐位一致的状态,所以分叉永远意味着“输入变了”:状态恢复、命令流、边界输入,不会是“框架算错了”。把时间花在那三个地方,比怀疑浮点累加或块遍历顺序有用得多。
One more debugging discipline has saved us a lot of time: trust the framework, audit the inputs. The same input and seed must produce bit-identical state, so a fork always means the inputs differ — state recovery, the command stream, a boundary input. It never means the framework computed wrong. Spend the time on those three; it beats suspecting float accumulation or chunk traversal order.
一句话 In One Line
坏掉确定性的是顺序、共享写入和未定义的值,并行只是让它们更容易出现。所以:状态只在固定位置读写(不可预测的上下文里只入队),结果一律排序且键只用 UID,跨实体读只读本波之前写好的副本,随机和编号不交给“谁先跑”,跨帧状态必须进快照,位域一个都不能漏。每条都能变成不变量,就都变成不变量。
What breaks determinism is order, shared writes and undefined values; parallelism only makes them easier to hit. So: touch entity state only at fixed points (unpredictable contexts enqueue), sort every result and key it on UID, cross-entity reads take a copy finished before the wave, randomness and ids never depend on who ran first, cross-frame state always enters the snapshot, and not one bitfield is left uninitialised. Whatever can be an invariant becomes one.