Go Sequencing Windows — Containing Partial Batch Failures on a Delivery Tracking Map

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

Go Sequencing Windows — Containing Partial Batch Failures on a Delivery Tracking Map

A live map has one constraint that changes the design: after a disconnect, the client must distinguish an event it never received from an event it received and then lost from memory. A faster transport cannot answer that question. Only an ordered, replayable delivery contract can. Short answer: Assign every device-status event a stable identity and a monotonic position within its stream, acknowledge batch members individually, and reconnect from the last contiguous position rather than the largest position observed. That choice treats a batch as a transport envelope, not a transaction. If positions 410 through 419 arrive and 414 fails validation, the dashboard may render later positions provisionally, but its durable checkpoint remains 413. The server can then backfill from 414 without guessing, while deduplication makes the repeated 415 through 419 harmless. This is the same conservative instinct used for a ledger: progress means a contiguous, auditable prefix, not a collection of optimistic successes.

实时地图有一个改变设计的约束:在断开连接后,客户端必须能够区分“从未接收到的事件”和“已接收但随后从内存中丢失的事件”。更快的传输无法回答这个问题,只有有序且可重放的交付契约才能做到。简而言之:为每个设备状态事件分配一个稳定的标识和一个流内的单调位置,单独确认批处理成员,并从最后一个连续位置而不是观察到的最大位置重新连接。这种选择将批处理视为传输信封,而非事务。如果位置 410 到 419 到达,而 414 验证失败,仪表板可以临时渲染后续位置,但其持久化检查点仍保持在 413。服务器随后可以从 414 开始回填而无需猜测,同时去重机制使得重复的 415 到 419 变得无害。这与账本所使用的保守本能相同:进度意味着一个连续的、可审计的前缀,而不是乐观成功的集合。

How should realtime event delivery recover from batch partial failures? Start by separating three facts that are often collapsed into one boolean: whether the producer accepted an update, whether the delivery service durably recorded it, and whether a particular dashboard applied it. An accepted: true response can establish the second fact only if the response identifies the exact member; it cannot establish the third. Likewise, a socket write completing says little about what survived a browser refresh. Don’t promote transport completion into business completion. For a medical-device delivery tracking map, a useful stream key is the tracked shipment or device journey, not the entire tenant. Each event needs an immutable event ID, a stream ID, a stream position, an occurrence time, and the status payload. The position orders changes within that one journey; it does not pretend to establish a universal order among unrelated deliveries.

实时事件交付应如何从批处理部分失败中恢复?首先要区分三个经常被合并为一个布尔值的真相:生产者是否接受了更新、交付服务是否持久记录了它,以及特定的仪表板是否应用了它。只有当响应标识了确切的成员时,“accepted: true”响应才能确立第二个事实;它无法确立第三个事实。同样,套接字写入完成并不能说明浏览器刷新后保留了什么。不要将传输完成提升为业务完成。对于医疗设备交付跟踪地图,有用的流键是受跟踪的货运或设备行程,而不是整个租户。每个事件都需要一个不可变的事件 ID、流 ID、流位置、发生时间和状态负载。位置用于对该行程内的变更进行排序;它并不试图在不相关的交付之间建立通用顺序。

A correction is a new event that refers to the affected state rather than an edit that erases history. That preserves the evidence needed for reconciliation and any retention or access controls required by the applicable compliance regime. The exact retention period is a policy decision, not something the realtime protocol should invent. The batch result must have the same granularity as the input. One response shape can classify each member as accepted, already accepted, or rejected, with a stable reason for rejection. A whole-batch success flag loses information. A whole-batch retry is acceptable only when event IDs make it idempotent; otherwise a single malformed member turns retry into duplicate state transitions. Keep the checkpoint rule strict: advance it while next_position == checkpoint + 1, then stop at the first gap. The batch contract is an accounting boundary.

更正是一个引用受影响状态的新事件,而不是擦除历史的编辑。这保留了对账所需的证据,以及适用合规制度所要求的任何保留或访问控制。确切的保留期限是政策决定,而不是实时协议应该发明的东西。批处理结果必须与输入具有相同的粒度。一种响应格式可以将每个成员分类为已接受、已重复接受或已拒绝,并提供稳定的拒绝原因。全批次成功标志会丢失信息。只有当事件 ID 使其具有幂等性时,全批次重试才是可接受的;否则,单个格式错误的成员会将重试变成重复的状态转换。保持检查点规则严格:当 next_position == checkpoint + 1 时推进它,然后在第一个间隙处停止。批处理契约是一个会计边界。

The ingest path should validate identity and sequence metadata before publishing anything downstream. It may process members independently, yet it should return one result per input event so the caller can reconcile cardinality as well as status. If the caller submits ten events and receives nine results, the response itself is incomplete and none of its apparent success should silently close the audit record. A compact state table makes the retry rule explicit: Member result Producer action Consumer effect Accepted Record the event ID and position Apply once when its turn arrives Already accepted Treat as successful retry Ignore the duplicate payload Rejected, permanent Quarantine with the reason Do not advance across its position Outcome unknown Retry with the same event ID Deduplicate if the first attempt committed.

摄入路径应在向下游发布任何内容之前验证身份和序列元数据。它可以独立处理成员,但应为每个输入事件返回一个结果,以便调用者可以核对基数和状态。如果调用者提交了十个事件但只收到九个结果,则响应本身是不完整的,其任何表面上的成功都不应静默关闭审计记录。紧凑的状态表使重试规则变得明确:成员结果(Accepted)对应生产者操作(记录事件 ID 和位置),消费者效果(在其轮到时应用一次);已接受(Already accepted)对应生产者操作(视为成功重试),消费者效果(忽略重复负载);永久拒绝(Rejected, permanent)对应生产者操作(隔离并说明原因),消费者效果(不越过其位置推进);结果未知(Outcome unknown)对应生产者操作(使用相同的事件 ID 重试),消费者效果(如果第一次尝试已提交则去重)。

The permanent-rejection row deserves care. If position 414 is structurally invalid, retrying the same bytes forever cannot repair it, but silently skipping it would make the displayed route look complete when it is not. The operator needs an audited resolution: replace the invalid update with a valid, newly identified correction under a documented policy, or mark that position as deliberately resolved. Which option is lawful for device data depends on the organization’s recordkeeping rules. I’m not sure a generic transport library can make that decision correctly; the evidence needed is the data classification and the approved correction policy. Exactly-once delivery is the wrong external promise. Networks can lose acknowledgements, so a producer may have to send the same event again. The attainable contract is an idempotent write plus an exactly-once state transition at the consumer: insert the event ID under a uniqueness constraint, apply the transition in the same local transaction, and return the prior result when the ID already exists. Short version: retry facts, not guesses.

永久拒绝行需要谨慎处理。如果位置 414 在结构上无效,永远重试相同的字节无法修复它,但静默跳过它会使显示的路线看起来完整,而实际上并非如此。操作员需要一个经过审计的解决方案:根据记录在案的政策,用有效的、新标识的更正替换无效更新,或者将该位置标记为已刻意解决。对于设备数据,哪种选择合法取决于组织的记录保存规则。我不确定通用的传输库能否正确做出该决定;所需的证据是数据分类和批准的更正政策。“精确一次”交付是一个错误的外部承诺。网络可能会丢失确认信息,因此生产者可能不得不再次发送相同的事件。可实现的契约是幂等写入加上消费者端的“精确一次”状态转换:在唯一性约束下插入事件 ID,在同一个本地事务中应用转换,并在 ID 已存在时返回先前的结果。简而言之:重试事实,而不是猜测。

A Go consumer that refuses to checkpoint across a gap. The following state machine is deliberately smaller than a full websocket server. It shows the correctness boundary: duplicate IDs do nothing, out-of-order events wait, and the durable checkpoint moves only through a contiguous run. Persistence implementations should commit seen, pending events, derived status, and checkpoint atomically; the in-memory maps here express the contract rather than a storage recommendation.

一个拒绝跨越间隙进行检查点的 Go 消费者。以下状态机特意比完整的 websocket 服务器更小。它展示了正确性边界:重复的 ID 不做任何处理,乱序事件等待,持久化检查点仅在连续运行时移动。持久化实现应原子地提交已见事件、待处理事件、派生状态和检查点;此处的内存映射表达的是契约,而非存储建议。

package delivery
import (
    "errors"
    "sync"
)
type Event struct {
    ID string
    StreamID string
    Position uint64
    Status string
}
type Cursor struct {
    mu sync.Mutex
    checkpoint uint64
    seen map[string]struct{}
    pending map[uint64]Event
    status string
}
func NewCursor(checkpoint uint64) *Cursor {
    return &Cursor{
        checkpoint: checkpoint,
        seen: make(map[string]struct{}),
        pending: make(map[uint64]Event),
    }
}
func (c *Cursor) Apply(e Event) (uint64, error) {
    c.mu.Lock()
    defer c.mu.Unlock()
    if e.ID == "" || e.StreamID == "" || e.Position == 0 {
        return c.checkpoint, errors.New("missing event identity or position")
    }
    if _, duplicate := c.seen[e.ID]; duplicate {
        return c.checkpoint, nil
    }
    if e.Position <= c.checkpoint {
        c.seen[e.ID] = struct{}{}
        return c.