fix(scheduler)!: 中断栈语义(嵌套抢占 LIFO),并修掉抢占空转

用户指正:存在**中断被中断**的场景,所以被打断的现场要进**中断栈**。
我此前把 suspendPool 明确写成“不是栈、按优先级取”,是错的。

改动:
- suspendPool 改名 suspendStack,恢复纪律改为**严格 LIFO(只比栈顶)**;
  栈内不做优先级重排——嵌套抢占天然使栈自底向上基础级递增,
  且“后被打断的先恢复”才是栈语义。取出即弹栈。
- 修掉一个由此暴露的真 bug(抢占空转):一次抢占生效后,被挂起的原任务
  会因饥饿防护提升有效级,与抢占者同级;此时若按“先到先服务”,原任务
  (入队更早)会被立刻选回,抢占者永远排不到 —— 抢占等于没发生。
  现在**同级时 pendingInterrupts 优先于其它两类**,保证抢占必然生效。
- 状态 DTO:SuspendPool/suspend_pool → SuspendStack/suspend_stack
- 设计稿:§2 用语更正(它**就是**中断栈)、§4.1 选择函数(候选只含栈顶 +
  pending 同级优先,并说明为何必需)、§6.2/§6.3/§9/§11 用例同步

测试新增 scheduler_stack_test.go 3 项:
- 嵌套 L1→L2→L3,恢复严格 LIFO(B 先于 A)
- 只比栈顶:人为构造“栈底 L3、栈顶 L2”,必须取栈顶(区分两种实现)
- 嵌套下的深度上限

验收:agent 全量 + -race;全仓 build/vet 通过
This commit is contained in:
JianFeeeee
2026-09-13 06:30:23 +08:00
parent d4764e3682
commit 86a702b3b0
8 changed files with 287 additions and 60 deletions

View File

@ -11,7 +11,7 @@ package core
// - **每任务 panic 隔离**panic 只使该任务失败,调度器本身存活(不变量 I6
//
// M2 全部任务都是 LevelBackground默认级因此排序结果等价于 FIFO——
// 与改造前的 channel 语义逐条一致。抢占、suspendPool、pendingInterrupts、
// 与改造前的 channel 语义逐条一致。抢占、中断栈、pendingInterrupts、
// 任务级回执在 M3M6 加入。
//
// 并发模型(不变量 I2readyQueue/running/stats 只由 schedulerLoop 写,
@ -152,9 +152,10 @@ type SchedulerSnapshot struct {
Running *Task
Queue []*Task
PendingInterrupts []*Task
SuspendPool []*suspendedTask
Stats SchedulerStats
MaxSuspendDepth int
// SuspendStack中断栈含嵌套抢占的多个现场**栈顶**优先恢复。
SuspendStack []*suspendedTask
Stats SchedulerStats
MaxSuspendDepth int
}
// schedulerStatus 把快照转成对外的状态 DTO不暴露帧内容
@ -166,7 +167,7 @@ func (a *Agent) schedulerStatus() sdk.SchedulerStatus {
out := sdk.SchedulerStatus{
ReadyQueueDepth: len(snap.Queue),
PendingInterrupts: len(snap.PendingInterrupts),
SuspendPool: len(snap.SuspendPool),
SuspendStack: len(snap.SuspendStack),
MaxSuspendDepth: snap.MaxSuspendDepth,
Enqueued: snap.Stats.Enqueued,
Executed: snap.Stats.Executed,
@ -194,8 +195,9 @@ type scheduler struct {
// pendingInterrupts因优先级不足或运行任务在临界区而未立即抢占的中断请求。
// 与 readyQueue 分离:取出时以中断语义启动(设计文档 D3
pendingInterrupts []*Task
// suspendPool被抢占后保存现场、等待恢复的任务(**不是栈**,按优先级取)。
suspendPool []*suspendedTask
// suspendStack**中断栈**。被抢占后保存现场的任务压栈LIFO
// 用于“中断被中断”的嵌套场景:只有**栈顶**参与恢复选择,栈内不做优先级重排。
suspendStack []*suspendedTask
// preemptArmed/preemptLevel运行任务的“让位信号”。
// interruptLoop 只写这两个字段与 pendingInterrupts帧永远只由调度器读写。
preemptArmed bool
@ -206,7 +208,7 @@ type scheduler struct {
// wake 用于把空闲的调度器叫醒pendingInterrupts 不是 channel
// 没有这个信号时“空闲时到达的中断”会一直等下一次输入(设计 §5.1 ③)。
wake chan struct{}
// maxSuspendDepthsuspendPool 深度上限(设计文档 §6.3,默认 4
// maxSuspendDepth中断栈深度上限(设计文档 §6.3,默认 4
maxSuspendDepth int
}
@ -293,7 +295,32 @@ func (s *scheduler) nextRef() (*Task, *TaskFrame, nextSelection) {
var bestFrame *TaskFrame
bestKind := nextNone
consider := func(t *Task, k nextSelection, fr *TaskFrame) {
if bestTask == nil || taskBefore(t, bestTask) {
if bestTask == nil {
bestTask, bestKind, bestFrame = t, k, fr
return
}
lt, lb := effectiveLevel(t), effectiveLevel(bestTask)
if lt != lb {
if lt > lb {
bestTask, bestKind, bestFrame = t, k, fr
}
return
}
// 同级时 **pending 中断优先**。
//
// 为何必需:一次抢占生效后,被挂起的原任务会因饥饿防护提升有效级,
// 于是与抢占者同级;若此时按“先到先服务”,原任务(入队更早)会被
// 立刻选回,抢占者永远排不到——抢占变成空转。
if k == nextPending && bestKind != nextPending {
bestTask, bestKind, bestFrame = t, k, fr
return
}
if bestKind == nextPending && k != nextPending {
return
}
// 同级同类先到先服务ID 兜底保证确定性)。
if t.EnqueuedAt.Before(bestTask.EnqueuedAt) ||
(t.EnqueuedAt.Equal(bestTask.EnqueuedAt) && t.ID < bestTask.ID) {
bestTask, bestKind, bestFrame = t, k, fr
}
}
@ -303,8 +330,11 @@ func (s *scheduler) nextRef() (*Task, *TaskFrame, nextSelection) {
for _, t := range s.pendingInterrupts {
consider(t, nextPending, nil)
}
for _, st := range s.suspendPool {
consider(st.Task, nextSuspended, st.Frame)
// 中断栈:只比**栈顶**(严格 LIFO。栈内不做优先级重排——
// 嵌套抢占天然使栈自底向上优先级递增,且“后被打断的先恢复”才是栈语义。
if n := len(s.suspendStack); n > 0 {
top := s.suspendStack[n-1]
consider(top.Task, nextSuspended, top.Frame)
}
if bestTask == nil {
return nil, nil, nextNone
@ -316,12 +346,8 @@ func (s *scheduler) nextRef() (*Task, *TaskFrame, nextSelection) {
case nextPending:
s.pendingInterrupts = removeTask(s.pendingInterrupts, bestTask)
case nextSuspended:
for i, st := range s.suspendPool {
if st.Task == bestTask {
s.suspendPool = append(s.suspendPool[:i], s.suspendPool[i+1:]...)
break
}
}
// 只有栈顶可能被选中,故弹出即截断末位。
s.suspendStack = s.suspendStack[:len(s.suspendStack)-1]
}
s.running = bestTask
return bestTask, bestFrame, bestKind
@ -408,10 +434,10 @@ func (s *scheduler) clearPreempt() {
func (s *scheduler) suspend(t *Task, f *TaskFrame) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.suspendPool) >= s.maxSuspendDepth {
if len(s.suspendStack) >= s.maxSuspendDepth {
s.stats.Rejected++
}
s.suspendPool = append(s.suspendPool, &suspendedTask{Task: t, Frame: f})
s.suspendStack = append(s.suspendStack, &suspendedTask{Task: t, Frame: f})
s.stats.Suspended++
// 饥饿防护:抢占计数 +1提升有效级并记录冷却起点。
t.PreemptCount++
@ -430,7 +456,7 @@ func (s *scheduler) suspend(t *Task, f *TaskFrame) {
func (s *scheduler) canSuspend() bool {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.suspendPool) < s.maxSuspendDepth
return len(s.suspendStack) < s.maxSuspendDepth
}
// done 标记任务执行结束。
@ -540,7 +566,7 @@ func (a *Agent) DumpScheduler() SchedulerSnapshot {
snap := SchedulerSnapshot{Running: a.sched.running, Stats: a.sched.stats}
snap.Queue = append(snap.Queue, a.sched.queue...)
snap.PendingInterrupts = append(snap.PendingInterrupts, a.sched.pendingInterrupts...)
snap.SuspendPool = append(snap.SuspendPool, a.sched.suspendPool...)
snap.SuspendStack = append(snap.SuspendStack, a.sched.suspendStack...)
snap.MaxSuspendDepth = a.sched.maxSuspendDepth
return snap
}

View File

@ -67,8 +67,8 @@ func TestPreempt_DeferredDuringToolExec(t *testing.T) {
if a.DumpScheduler().Running == nil {
t.Fatal("工具执行中不得挂起StepToolExec 是临界区)")
}
if len(a.DumpScheduler().SuspendPool) != 0 {
t.Fatal("工具执行中 suspendPool 应为空")
if len(a.DumpScheduler().SuspendStack) != 0 {
t.Fatal("工具执行中 suspendStack 应为空")
}
// 放行工具 → 工具返回后的安全点才挂起。
@ -80,11 +80,11 @@ func TestPreempt_DeferredDuringToolExec(t *testing.T) {
}
snap := a.DumpScheduler()
if len(snap.SuspendPool) != 1 {
t.Fatalf("工具返回后 suspendPool=%d期望 1", len(snap.SuspendPool))
if len(snap.SuspendStack) != 1 {
t.Fatalf("工具返回后 suspendStack=%d期望 1", len(snap.SuspendStack))
}
if snap.SuspendPool[0].Frame.Step != StepToolAfter {
t.Fatalf("应在工具执行后的安全点挂起StepToolAfter实际 %v", snap.SuspendPool[0].Frame.Step)
if snap.SuspendStack[0].Frame.Step != StepToolAfter {
t.Fatalf("应在工具执行后的安全点挂起StepToolAfter实际 %v", snap.SuspendStack[0].Frame.Step)
}
if len(snap.PendingInterrupts) != 1 {
t.Fatalf("中断请求不得丢失pendingInterrupts=%d", len(snap.PendingInterrupts))
@ -142,7 +142,7 @@ func TestBatch_NotAbandonedWithoutPreemption(t *testing.T) {
t.Fatalf("同批工具应全部按序执行,实际 %v", ran)
}
snap := a.DumpScheduler()
if len(snap.SuspendPool) != 0 || len(snap.PendingInterrupts) != 0 {
if len(snap.SuspendStack) != 0 || len(snap.PendingInterrupts) != 0 {
t.Fatalf("无抢占时不应有挂起或待处理中断:%+v", snap)
}
if snap.Stats.Executed != 1 {

View File

@ -42,14 +42,14 @@ func waitQuiescent(t *testing.T, a *Agent, wantExecuted uint64, timeout time.Dur
for {
snap := a.DumpScheduler()
if snap.Running == nil && len(snap.Queue) == 0 &&
len(snap.PendingInterrupts) == 0 && len(snap.SuspendPool) == 0 &&
len(snap.PendingInterrupts) == 0 && len(snap.SuspendStack) == 0 &&
snap.Stats.Executed >= wantExecuted {
return snap
}
if time.Now().After(deadline) {
t.Fatalf("未在 %v 内排空running=%v queue=%d pending=%d suspend=%d executed=%d",
timeout, snap.Running != nil, len(snap.Queue), len(snap.PendingInterrupts),
len(snap.SuspendPool), snap.Stats.Executed)
len(snap.SuspendStack), snap.Stats.Executed)
}
time.Sleep(20 * time.Millisecond)
}
@ -147,7 +147,7 @@ func TestObservability_SchedulerEventsAndStatus(t *testing.T) {
// 状态快照(供状态页/诊断):计数一致、三集合为空。
st := a.GetKernelStatus().Scheduler
if st.SuspendPool != 0 || st.PendingInterrupts != 0 || st.ReadyQueueDepth != 0 {
if st.SuspendStack != 0 || st.PendingInterrupts != 0 || st.ReadyQueueDepth != 0 {
t.Fatalf("排空后状态非空:%+v", st)
}
if st.Suspended == 0 || st.Resumed == 0 {

View File

@ -1,6 +1,6 @@
package core
// M3b 验收测试:四级优先级 + 严格大于抢占 + 现场保存/恢复 + suspendPool
// M3b 验收测试:四级优先级 + 严格大于抢占 + 现场保存/恢复 + suspendStack
//
// 设计依据 docs/zh/input-scheduler-design.md §11P1P4、R1、R5、D1T、Q3
//
@ -124,13 +124,13 @@ func TestPreempt_HigherPreemptsAndResumes(t *testing.T) {
if snap.Running != nil {
t.Fatal("挂起后不应还有 running")
}
if len(snap.SuspendPool) != 1 {
t.Fatalf("suspendPool=%d期望 1", len(snap.SuspendPool))
if len(snap.SuspendStack) != 1 {
t.Fatalf("suspendStack=%d期望 1", len(snap.SuspendStack))
}
if len(snap.PendingInterrupts) != 1 {
t.Fatalf("pendingInterrupts=%d期望 1", len(snap.PendingInterrupts))
}
sf := snap.SuspendPool[0].Frame
sf := snap.SuspendStack[0].Frame
if sf.Terminal != terminalSuspended {
t.Fatalf("挂起任务终态=%v期望 terminalSuspended", sf.Terminal)
}
@ -186,7 +186,7 @@ func TestPreempt_HigherPreemptsAndResumes(t *testing.T) {
t.Fatalf("LLM 总调用=%d期望 3丢弃 1 + 中断 1 + 恢复 1", sp.callCount())
}
snap = a.DumpScheduler()
if len(snap.SuspendPool) != 0 || snap.Running != nil {
if len(snap.SuspendStack) != 0 || snap.Running != nil {
t.Fatalf("全部结束后应无挂起与运行任务:%+v", snap)
}
if snap.Stats.Executed != 2 {
@ -239,7 +239,7 @@ func TestPreempt_LowerOrEqualDoesNotPreempt(t *testing.T) {
}
}
// D1TsuspendPool 满时不再下潜canSuspend=false让位信号也不会 arm。
// D1TsuspendStack 满时不再下潜canSuspend=false让位信号也不会 arm。
func TestPreempt_DepthCapBlocksSuspension(t *testing.T) {
a := newPreemptAgent(t, newPreemptProvider())
@ -259,7 +259,7 @@ func TestPreempt_DepthCapBlocksSuspension(t *testing.T) {
if a.DumpScheduler().Stats.Rejected != before+1 {
t.Fatal("超限挂起必须计数 Rejected")
}
if len(a.DumpScheduler().SuspendPool) != a.sched.maxSuspendDepth+1 {
if len(a.DumpScheduler().SuspendStack) != a.sched.maxSuspendDepth+1 {
t.Fatal("兜底路径必须保留帧而不是丢弃")
}
}

View File

@ -0,0 +1,192 @@
package core
// 中断栈(嵌套抢占)验收测试。
//
// 用户明确:存在**中断被中断**的场景,所以被打断的现场要压进**中断栈**。
// 因此恢复纪律是**严格 LIFO只比栈顶**,而不是“全栈按优先级挑最优”。
//
// 为什么这个区别成立:抢占判据是 adopted.level > effectiveLevel(running)
// 所以嵌套时栈自底向上的**基础级**天然递增;但饥饿防护的“有效级提升”会让
// 栈内某个更老的任务有效级超过栈顶,此时“只比栈顶”才保证嵌套语义不被破坏。
import (
"context"
"sync"
"testing"
"time"
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
)
// nestingProvider 第 1、2 次调用阻塞到 ctx 取消;第 3 次起按脚本返回。
// 用序号精确对应 AL1→ BL2→ CL3→ 恢复 B → 恢复 A 的调用顺序。
type nestingProvider struct {
mu sync.Mutex
calls int
entered chan int
script []string
}
func newNestingProvider(script ...string) *nestingProvider {
return &nestingProvider{entered: make(chan int, 16), script: script}
}
func (p *nestingProvider) Name() string { return "nesting" }
func (p *nestingProvider) Chat(ctx context.Context, req *agentAPI.CompletionRequest) (*agentAPI.CompletionResponse, error) {
p.mu.Lock()
p.calls++
n := p.calls
p.mu.Unlock()
p.entered <- n
if n <= 2 {
<-ctx.Done()
return nil, ctx.Err()
}
p.mu.Lock()
defer p.mu.Unlock()
i := n - 3
if i < len(p.script) {
return &agentAPI.CompletionResponse{Content: p.script[i]}, nil
}
return &agentAPI.CompletionResponse{Content: "?"}, nil
}
func (p *nestingProvider) ChatStream(ctx context.Context, req *agentAPI.CompletionRequest) (<-chan agentAPI.StreamChunk, error) {
return nil, context.Canceled
}
func (p *nestingProvider) MaxContextTokens() int { return 8192 }
func awaitEnter(t *testing.T, ch chan int, want int) {
t.Helper()
select {
case got := <-ch:
if got != want {
t.Fatalf("LLM 进入序号=%d期望 %d", got, want)
}
case <-time.After(3 * time.Second):
t.Fatalf("等第 %d 次 LLM 调用超时", want)
}
}
// 中断被中断A(L1) → B(L2) → C(L3),恢复必须按 LIFOB 先A 后)。
func TestStack_NestedPreemptionResumesLIFO(t *testing.T) {
sp := newNestingProvider("c-done", "b-done", "a-done")
a := newPreemptAgent(t, sp)
// AL1开始运行
if _, _ = enqueueTask(t, a, LevelBackground, "qq", "任务A"); true {
}
at, _, _ := a.sched.nextRef()
doneA := make(chan struct{})
go func() { a.executeNewTask(at); close(doneA) }()
awaitEnter(t, sp.entered, 1)
// BL2抢占 A
bEvt, _ := textEvent("qq", "任务B")
if !a.sched.requestPreempt(bEvt, LevelMessage) {
t.Fatal("B(L2) 应抢占 A(L1)")
}
a.cancelCurrentLLM()
<-doneA
if n := len(a.DumpScheduler().SuspendStack); n != 1 {
t.Fatalf("第一次抢占后栈深=%d期望 1", n)
}
// B 开始运行
bt, _, k := a.sched.nextRef()
if k != nextPending || bt.Level != LevelMessage {
t.Fatalf("应取到 Bpendingkind=%v level=%v", k, bt.Level)
}
doneB := make(chan struct{})
go func() { a.executeNewTask(bt); close(doneB) }()
awaitEnter(t, sp.entered, 2)
// CL3抢占 B —— 这就是“中断被中断”
cEvt, _ := textEvent("cli", "任务C")
if !a.sched.requestPreempt(cEvt, LevelInteractive) {
t.Fatal("C(L3) 应抢占 B(L2)")
}
a.cancelCurrentLLM()
<-doneB
snap := a.DumpScheduler()
if len(snap.SuspendStack) != 2 {
t.Fatalf("嵌套后栈深=%d期望 2", len(snap.SuspendStack))
}
if snap.SuspendStack[0].Task.Level != LevelBackground {
t.Fatalf("栈底应为 A(L1),实际 %v", snap.SuspendStack[0].Task.Level)
}
if snap.SuspendStack[1].Task.Level != LevelMessage {
t.Fatalf("栈顶应为 B(L2),实际 %v", snap.SuspendStack[1].Task.Level)
}
// C 运行完毕(第三次调用,不阻塞)
ct, _, k := a.sched.nextRef()
if k != nextPending || ct.Level != LevelInteractive {
t.Fatalf("应取到 Ckind=%v level=%v", k, ct.Level)
}
a.executeNewTask(ct)
// LIFO先恢复栈顶 B再恢复 A
rt, rf, k := a.sched.nextRef()
if k != nextSuspended {
t.Fatalf("应恢复栈顶kind=%v", k)
}
if rt.Level != LevelMessage {
t.Fatalf("应先恢复栈顶 B(L2),实际 %v", rt.Level)
}
a.resumeTask(rt, rf)
rt2, rf2, k2 := a.sched.nextRef()
if k2 != nextSuspended {
t.Fatalf("应继续恢复 Akind=%v", k2)
}
if rt2.Level != LevelBackground {
t.Fatalf("最后应恢复 A(L1),实际 %v", rt2.Level)
}
a.resumeTask(rt2, rf2)
if n := len(a.DumpScheduler().SuspendStack); n != 0 {
t.Fatalf("全部恢复后栈应清空,实际 %d", n)
}
}
// 只比栈顶:栈内更老的任务即使(因有效级提升)优先级更高,也不得越过栈顶。
func TestStack_TopOnlyWinsOverHigherPrioritySuspended(t *testing.T) {
a := newPreemptAgent(t, &scriptProvider{})
// 人为构造“A(L3) 在栈底、B(L2) 在栈顶”。真实抢占不会产生这种顺序
// (栈自底向上基础级递增),这里专门用来区分两种实现:
// · 只比栈顶 → 取 B
// · 全栈扫最优 → 取 AL3 > L2
a.sched.suspend(&Task{ID: 1, Level: LevelInteractive, EnqueuedAt: time.Now()},
a.newTaskFrame("A", a.stageCtxFromInput("A", "", "")))
a.sched.suspend(&Task{ID: 2, Level: LevelMessage, EnqueuedAt: time.Now()},
a.newTaskFrame("B", a.stageCtxFromInput("B", "", "")))
rt, _, k := a.sched.nextRef()
if k != nextSuspended {
t.Fatalf("kind=%v期望 nextSuspended", k)
}
if rt.ID != 2 {
t.Fatalf("应取栈顶 B(ID=2),实际 ID=%d —— 说明在做全栈优先级扫描而非栈语义", rt.ID)
}
if n := len(a.DumpScheduler().SuspendStack); n != 1 {
t.Fatalf("取出栈顶后栈深=%d期望 1", n)
}
}
// 深度上限对嵌套同样成立:到顶后新的抢占请求不再下潜。
func TestStack_DepthCapDuringNesting(t *testing.T) {
a := newPreemptAgent(t, &scriptProvider{})
frame := func() *TaskFrame { return a.newTaskFrame("x", a.stageCtxFromInput("x", "", "")) }
for i := 0; i < a.sched.maxSuspendDepth; i++ {
a.sched.suspend(&Task{ID: uint64(i + 1), Level: Level(i + 1)}, frame())
}
if a.sched.canSuspend() {
t.Fatal("栈已满canSuspend 应为 false")
}
if n := len(a.DumpScheduler().SuspendStack); n != a.sched.maxSuspendDepth {
t.Fatalf("栈深=%d期望上限 %d", n, a.sched.maxSuspendDepth)
}
}

View File

@ -6,7 +6,7 @@ package core
//
// M1 只做一件事:把原先「一个 425 行的 process() 大函数」拆成
// **显式 step 游标 + TaskFrame**。目的不是加能力,而是让「现场」变成数据——
// 之后 M3 才能把帧存进 suspendPool 并在安全点恢复。
// 之后 M3 才能把帧存进 suspendStack 并在安全点恢复。
//
// 行为等价的判据:既有全部 agent 测试通过,且 R3/X3见设计文档 §11通过。
//