Skip to content

Raft AppendEntries: entry.Index=0 且无快照时 relativeIndex=-1 导致 r.raft.log[-1] 越界 panic #120

@NeverENG

Description

@NeverENG

@

现象

hermetic 环境(清空 raft_data 后)单独跑 TestAppendEntriesRPC 会 panic 在 Raft/rpc.go:161:

panic: runtime error: index out of range [-1]
github.com/NeverENG/BanDB/Raft.(*RaftRPC).AppendEntries  Raft/rpc.go:161

根因

AppendEntries 的日志匹配循环:

for _, entry := range args.Entries {
    relativeIndex := entry.Index - int(r.raft.LastIncludedIndex) - 1   // 0 - 0 - 1 = -1
    if relativeIndex < len(r.raft.log) && r.raft.log[relativeIndex].Term != entry.Term {  // -1 < 0 → true, 再取 log[-1] 越界

entry.Index == 0LastIncludedIndex == 0(全新节点、空日志)时, relativeIndex == -1, 条件 -1 < len(log)=0 成立, 随即 r.raft.log[-1] 越界。

影响

建议

匹配/截断前对 relativeIndex < 0 做保护(负索引视为命中快照区间或跳过), 与 PrevLogIndex 的快照分支保持一致。

关联

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions