返回 DeepSeek-Reasonix
turn_loop.go
根目录 / internal / control / turn_loop.go
1 package control
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "time"
8
9 "reasonix/internal/agent"
10 "reasonix/internal/event"
11 "reasonix/internal/extension"
12 "reasonix/internal/session"
13 )
14
15 type queuedTurnKind int
16
17 const (
18 queuedUser queuedTurnKind = iota
19 queuedGoal
20 )
21
22 type queuedTurn struct {
23 kind queuedTurnKind
24 body func(ctx context.Context) error
25 onStart func()
26 goalRound *goalRoundReservation
27 // admissionCtx is only used for the synchronous durability boundary. The
28 // model turn has its own controller-owned context and survives RPC return.
29 admissionCtx context.Context
30 }
31
32 // turnLoop is the session-scoped execution authority. Controller.mu guards it.
33 type turnLoop struct {
34 phase session.RuntimePhase
35 cancel context.CancelFunc
36 done chan struct{}
37 recoveryFanout bool // watchdog terminal publication still owns the stores
38 turnID string
39 token uint64
40 lastToken uint64
41 pending []queuedTurn
42 wake bool
43 generation uint64
44 runtime *session.Runtime
45 cancelRequested bool
46 finishingBound turnFinishingBoundary
47 }
48
49 type controllerExecution struct {
50 c *Controller
51 }
52
53 func (e controllerExecution) Snapshot() session.RuntimeSnapshot {
54 if e.c == nil {
55 return session.RuntimeSnapshot{Phase: session.RuntimeIdle}
56 }
57 e.c.mu.Lock()
58 defer e.c.mu.Unlock()
59 if op := e.c.maintenance; op != nil {
60 return session.RuntimeSnapshot{Phase: maintenanceRuntimePhase(op.activity), Activity: session.MaintenanceActivity}
61 }
62 return session.RuntimeSnapshot{Phase: e.c.turns.phase, Activity: e.c.turns.activityNameLocked()}
63 }
64
65 func (e controllerExecution) Cancel() bool {
66 if e.c == nil {
67 return false
68 }
69 if _, present, cancelled := e.c.signalMaintenanceCancel(); present {
70 return cancelled
71 }
72 return e.c.signalTurnCancel()
73 }
74
75 func (t *turnLoop) activityNameLocked() string {
76 switch t.phase {
77 case session.RuntimeCancelling:
78 return "cancelling"
79 case session.RuntimeRecoveryRequired:
80 return "recovery_required"
81 case session.RuntimeRunning, session.RuntimeFinalizing:
82 if t.cancelRequested {
83 return "cancelling"
84 }
85 return "turn"
86 default:
87 return ""
88 }
89 }
90
91 func (c *Controller) bodyActiveLocked() bool {
92 switch c.turns.phase {
93 case session.RuntimeRunning, session.RuntimeCancelling:
94 return true
95 default:
96 return false
97 }
98 }
99
100 func (c *Controller) finalizingLocked() bool {
101 return c.turns.phase == session.RuntimeFinalizing
102 }
103
104 func (c *Controller) cancelRequestedLocked() bool {
105 if c.closed {
106 return false
107 }
108 return c.turns.cancelRequested || c.turns.phase == session.RuntimeCancelling
109 }
110
111 func (c *Controller) recoveryRequiredLocked() bool {
112 return c.turns.phase == session.RuntimeRecoveryRequired
113 }
114
115 func (c *Controller) bindExecutionControl() {
116 _, runtime, exclusive := c.v3Binding()
117 if !exclusive || runtime == nil {
118 return
119 }
120 snap := runtime.StateSnapshot()
121 gen := runtime.BindExecution(controllerExecution{c: c})
122 c.executionGeneration.Store(gen)
123 c.mu.Lock()
124 c.turns.generation = gen
125 c.turns.runtime = runtime
126 if snap.Phase == session.RuntimeRecoveryRequired {
127 c.turns.phase = session.RuntimeRecoveryRequired
128 }
129 c.mu.Unlock()
130 }
131
132 // ExecutionGeneration returns the session-runtime execution generation owned
133 // by this controller. Zero means the controller is a prepared replacement that
134 // has not been published as the execution owner.
135 func (c *Controller) ExecutionGeneration() uint64 {
136 if c == nil {
137 return 0
138 }
139 return c.executionGeneration.Load()
140 }
141
142 // ActivateSessionExecution publishes this controller as the exact execution
143 // owner. expectedGeneration is zero for a previously unbound runtime and the
144 // outgoing controller generation for a fail-atomic replacement. The method is
145 // deliberately callback- and I/O-free so hosts may invoke it in their final
146 // pointer-swap critical section.
147 func (c *Controller) ActivateSessionExecution(expectedGeneration uint64) error {
148 if c == nil {
149 return session.ErrSessionNotRunning
150 }
151 c.turnEvents.commitMu.Lock()
152 defer c.turnEvents.commitMu.Unlock()
153 c.mu.Lock()
154 defer c.mu.Unlock()
155 runtime := c.turns.runtime
156 if runtime == nil {
157 return nil
158 }
159 if generation := c.turns.generation; generation != 0 && runtime.OwnsExecution(generation) {
160 return nil
161 }
162 var generation uint64
163 if expectedGeneration == 0 {
164 generation = runtime.BindExecution(controllerExecution{c: c})
165 } else if pending := c.turnEvents.pendingExecutionCommit; pending != nil {
166 c.turnEvents.pendingExecutionCommit = nil
167 var err error
168 generation, _, err = runtime.ReplaceExecutionAndCommit(expectedGeneration, controllerExecution{c: c}, *pending)
169 if err != nil {
170 return err
171 }
172 } else {
173 generation = runtime.ReplaceExecution(expectedGeneration, controllerExecution{c: c})
174 }
175 if generation == 0 {
176 return session.ErrRuntimeBusy
177 }
178 c.turns.generation = generation
179 c.executionGeneration.Store(generation)
180 return nil
181 }
182
183 // ActivateControllerReplacement transfers session execution ownership when a
184 // host commits a controller pointer swap. Controllers without a shared Runtime
185 // need no additional activation.
186 func ActivateControllerReplacement(old, next *Controller) error {
187 if next == nil {
188 return session.ErrSessionNotRunning
189 }
190 if old != nil && old.background.scope != nil && old.background.scope == next.background.scope {
191 if old.workspaceRoot != next.workspaceRoot {
192 return fmt.Errorf("background ownership cannot cross workspaces")
193 }
194 before, beforeOK := old.SessionRef()
195 after, afterOK := next.SessionRef()
196 if beforeOK && afterOK && before.SessionID != after.SessionID {
197 return fmt.Errorf("background ownership cannot cross sessions")
198 }
199 if ModelReplacementBlocked(old) {
200 return fmt.Errorf("session changed while preparing replacement")
201 }
202 }
203 if old != nil && old.background.scope != nil && old.background.scope == next.background.scope && old.ToolApprovalMode() != next.ToolApprovalMode() && len(old.jobs.Running()) > 0 {
204 return fmt.Errorf("permission changes require stopping background jobs before replacement")
205 }
206 _, nextRuntime, nextExclusive := next.v3Binding()
207 if !nextExclusive || nextRuntime == nil {
208 retireBackgroundCallbacks(old, next)
209 next.PublishBackgroundScope()
210 return nil
211 }
212 expected := uint64(0)
213 if old != nil {
214 _, oldRuntime, oldExclusive := old.v3Binding()
215 if oldExclusive && oldRuntime == nextRuntime {
216 expected = old.ExecutionGeneration()
217 }
218 }
219 if err := next.ActivateSessionExecution(expected); err != nil {
220 return err
221 }
222 retireBackgroundCallbacks(old, next)
223 next.PublishBackgroundScope()
224 return nil
225 }
226
227 func retireBackgroundCallbacks(old, next *Controller) {
228 if old != nil && old != next && old.background.scope != nil && old.background.scope == next.background.scope {
229 old.mu.Lock()
230 old.background.retired = true
231 old.mu.Unlock()
232 }
233 }
234
235 // ActivateSessionAPIReplacement is the host-facing form used at a final
236 // controller pointer swap. Non-Controller implementations have no exclusive
237 // Runtime ownership to transfer and are left unchanged.
238 func ActivateSessionAPIReplacement(old, next SessionAPI) error {
239 concreteNext, ok := next.(*Controller)
240 if !ok || concreteNext == nil {
241 return nil
242 }
243 concreteOld, _ := old.(*Controller)
244 if err := ActivateControllerReplacement(concreteOld, concreteNext); err != nil {
245 return err
246 }
247 if concreteOld != nil && concreteOld.attachmentScope() != "" && concreteOld.attachmentScope() == concreteNext.attachmentScope() && concreteOld.workspaceRoot == concreteNext.workspaceRoot {
248 concreteOld.attachmentService().Drafts().CopyScopeTo(concreteOld.attachmentScope(), concreteNext.attachmentService().Drafts())
249 }
250 return nil
251 }
252
253 func (c *Controller) unbindExecutionControl(runtime *session.Runtime) {
254 if runtime == nil {
255 return
256 }
257 c.mu.Lock()
258 gen := c.turns.generation
259 c.mu.Unlock()
260 runtime.UnbindExecution(gen)
261 }
262
263 func (c *Controller) noteExecutionLocked(phase session.RuntimePhase, activity string) {
264 if c.turns.runtime == nil || c.turns.generation == 0 {
265 return
266 }
267 c.turns.runtime.NoteExecution(c.turns.generation, phase, activity)
268 }
269
270 func (c *Controller) currentTurnToken() (token uint64, turnID string, active bool) {
271 c.mu.Lock()
272 defer c.mu.Unlock()
273 switch c.turns.phase {
274 case session.RuntimeIdle, session.RuntimeClosed:
275 return c.turns.lastToken, "", false
276 default:
277 return c.turns.token, c.turns.turnID, true
278 }
279 }
280
281 func (c *Controller) discardLateTurnEvent(e event.Event) bool {
282 if e.TurnID == "" || !lateBusinessEvent(e.Kind) {
283 return false
284 }
285 _, turnID, active := c.currentTurnToken()
286 if active {
287 return e.TurnID != turnID
288 }
289 return true
290 }
291
292 func (c *Controller) startTurnLocked(parent context.Context, next queuedTurn) (ctx context.Context, cancel context.CancelFunc, admitted bool) {
293 if parent == nil {
294 parent = context.Background()
295 }
296 if c.turns.runtime != nil && !c.turns.runtime.BeginExecution(c.turns.generation, "turn") {
297 return nil, nil, false
298 }
299 ctx, cancel = context.WithCancel(extension.ContextWithRuntimeOwner(c.withAuthentication(parent), c.runtimeOwner))
300 c.turns.cancel = cancel
301 c.turns.done = make(chan struct{})
302 c.turns.finishingBound.beginIdle()
303 c.turns.phase = session.RuntimeRunning
304 c.turns.cancelRequested = false
305 c.turns.token++
306 ctx = context.WithValue(ctx, executionTokenKey{}, c.turns.token)
307 c.turns.turnID = ""
308 return ctx, cancel, true
309 }
310
311 func (c *Controller) popNextPendingLocked() (queuedTurn, bool) {
312 if len(c.turns.pending) == 0 {
313 c.turns.wake = false
314 return queuedTurn{}, false
315 }
316 next := c.turns.pending[0]
317 c.turns.pending = c.turns.pending[1:]
318 c.turns.wake = len(c.turns.pending) > 0
319 return next, true
320 }
321
322 func (c *Controller) queueTurnLocked(item queuedTurn) {
323 // Harness wakeRequested: input that cannot join the current activity is
324 // claimed once when the body converges. Close clears this queue so a
325 // disposed session never starts a latched turn.
326 c.turns.pending = append(c.turns.pending, item)
327 c.turns.wake = true
328 }
329
330 func (c *Controller) signalTurnCancel() bool {
331 _, _, cancelled := c.signalTurnCancelIdentity()
332 return cancelled
333 }
334
335 func (c *Controller) signalTurnCancelIdentity() (uint64, string, bool) {
336 c.mu.Lock()
337 token, turnID := c.turns.token, c.turns.turnID
338 cancel := c.turns.cancel
339 first := cancel != nil && c.turns.phase == session.RuntimeRunning
340 if cancel != nil && (c.turns.phase == session.RuntimeRunning || c.turns.phase == session.RuntimeCancelling) {
341 c.turns.phase = session.RuntimeCancelling
342 c.turns.cancelRequested = true
343 }
344 done := c.turns.done
345 c.mu.Unlock()
346 if cancel == nil {
347 return token, turnID, false
348 }
349 cancel()
350 c.recordLifecycle("cancel_signalled", "turn", turnID, 0, "")
351 if first {
352 c.startCancellationWatchdog(done)
353 }
354 return token, turnID, true
355 }
356
357 func (c *Controller) enterRecoveryLocked(reason string) {
358 c.turns.phase = session.RuntimeRecoveryRequired
359 c.noteExecutionLocked(session.RuntimeRecoveryRequired, reason)
360 if c.turns.runtime != nil {
361 c.turns.runtime.RequireRecovery(reason)
362 }
363 }
364
365 func (c *Controller) spawnGuardedTurn(ctx context.Context, cancel context.CancelFunc, item queuedTurn) {
366 ctx, completion := withGuardedTurnCompletion(ctx)
367 admissionCtx := item.admissionCtx
368 if admissionCtx == nil {
369 admissionCtx = context.Background()
370 }
371 body := c.prepareTurnAdmissionWithGoalRound(admissionCtx, item.body, item.goalRound)
372 if ledger := c.turnEventLedger(); ledger != nil {
373 c.mu.Lock()
374 c.turns.turnID = ledger.ActiveTurnID()
375 c.mu.Unlock()
376 }
377 c.liveness.reset(time.Now())
378 c.autosaveWG.Go(func() {
379 c.autosaveWhileRunning(ctx)
380 })
381 go func() {
382 defer cancel()
383 defer func() {
384 c.finishGoalRoundActivity(item.goalRound)
385 c.kickGoalDriver()
386 }()
387 defer func() {
388 if r := recover(); r != nil {
389 err := fmt.Errorf("internal error: %v", r)
390 item.goalRound.setResult(err, false)
391 c.finishGuardedTurn(err, completion)
392 }
393 }()
394 err := body(ctx)
395 if item.goalRound != nil {
396 item.goalRound.setResult(err, errors.Is(ctx.Err(), context.Canceled) && c.CancelRequested())
397 }
398 c.finishGuardedTurn(explainError(err), completion)
399 }()
400 }
401
402 func (c *Controller) cancellationGrace() time.Duration {
403 if c != nil && c.testCancelGrace > 0 {
404 return c.testCancelGrace
405 }
406 return 15 * time.Second
407 }
408
409 func (c *Controller) finishGuardedTurn(err error, completion *guardedTurnCompletion) {
410 c.authentication.recordFailure(err, c.ModelRef())
411 c.memory.clearAutoRemember()
412 c.mu.Lock()
413 cancelRequested := c.turns.cancelRequested
414 if c.turns.phase == session.RuntimeRecoveryRequired {
415 c.turns.cancel = nil
416 closing := c.closed
417 c.mu.Unlock()
418 // The cancellation watchdog already committed the recovery terminal.
419 // A closing controller must not emit another terminal after its ledger
420 // and session binding have been finalized.
421 if !closing {
422 c.emitTurnDoneEvent(err, cancelRequested, completion)
423 }
424 c.mu.Lock()
425 // Keep the owned turn live through terminal fanout. Close must not
426 // release stores while that fanout can still publish durable events.
427 if c.turns.done != nil {
428 close(c.turns.done)
429 c.turns.done = nil
430 }
431 closing = c.closed && !c.turns.recoveryFanout
432 c.turns.finishingBound.endIdle()
433 c.mu.Unlock()
434 if closing {
435 c.finalizeControllerClose()
436 }
437 c.refreshRuntimeState(event.Event{})
438 return
439 }
440 if c.turns.done != nil {
441 close(c.turns.done)
442 c.turns.done = nil
443 }
444 c.turns.phase = session.RuntimeFinalizing
445 c.turns.finishingBound.begin(true)
446 c.turns.cancel = nil
447 c.noteExecutionLocked(session.RuntimeFinalizing, "turn")
448 c.mu.Unlock()
449
450 c.refreshRuntimeState(event.Event{})
451 defer func() {
452 c.mu.Lock()
453 c.turns.finishingBound.end()
454 c.turns.cancelRequested = false
455 if c.turns.phase == session.RuntimeRecoveryRequired {
456 closing := c.closed
457 c.turns.finishingBound.endIdle()
458 c.mu.Unlock()
459 if closing {
460 c.finalizeControllerClose()
461 }
462 c.refreshRuntimeState(event.Event{})
463 return
464 }
465 if ledger := c.turnEventLedger(); ledger != nil && ledger.CurrentStatus() == event.TurnRecoveryRequired {
466 c.enterRecoveryLocked("terminal")
467 c.turns.finishingBound.endIdle()
468 c.mu.Unlock()
469 c.refreshRuntimeState(event.Event{})
470 return
471 }
472 if c.closed {
473 c.turns.lastToken = c.turns.token
474 c.turns.phase = session.RuntimeClosed
475 c.turns.turnID = ""
476 c.noteExecutionLocked(session.RuntimeIdle, "")
477 c.turns.finishingBound.endIdle()
478 c.mu.Unlock()
479 c.finalizeControllerClose()
480 c.refreshRuntimeState(event.Event{})
481 return
482 }
483 if authErr := c.authentication.admissionError(); authErr != nil {
484 for _, pending := range c.turns.pending {
485 if pending.goalRound != nil {
486 pending.goalRound.setResult(authErr, false)
487 }
488 }
489 c.turns.pending = nil
490 c.turns.wake = false
491 c.turns.lastToken = c.turns.token
492 c.turns.phase = session.RuntimeIdle
493 c.turns.turnID = ""
494 c.noteExecutionLocked(session.RuntimeIdle, "")
495 c.turns.finishingBound.endIdle()
496 c.mu.Unlock()
497 c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Code: "authentication_not_ready", Text: authErr.Error()})
498 c.refreshRuntimeState(event.Event{})
499 return
500 }
501 next, ok := c.popNextPendingLocked()
502 if !ok {
503 c.turns.lastToken = c.turns.token
504 c.turns.phase = session.RuntimeIdle
505 c.turns.turnID = ""
506 c.noteExecutionLocked(session.RuntimeIdle, "")
507 c.turns.finishingBound.endIdle()
508 c.mu.Unlock()
509 c.maybeDispatchInbox()
510 c.refreshRuntimeState(event.Event{})
511 return
512 }
513 ctx, cancel, admitted := c.startTurnLocked(context.Background(), next)
514 if !admitted {
515 c.enterRecoveryLocked("execution_owner_lost")
516 c.turns.finishingBound.endIdle()
517 c.mu.Unlock()
518 c.refreshRuntimeState(event.Event{})
519 return
520 }
521 c.mu.Unlock()
522 if next.onStart != nil {
523 next.onStart()
524 }
525 c.spawnGuardedTurn(ctx, cancel, next)
526 c.refreshRuntimeState(event.Event{})
527 }()
528 c.emitTurnDoneEvent(err, cancelRequested, completion)
529 }
530
531 func (c *Controller) emitTurnDoneEvent(err error, cancelRequested bool, completion *guardedTurnCompletion) {
532 c.inbox.mu.Lock()
533 activeInboxID := ""
534 for id := range c.inbox.activeItemIDs {
535 activeInboxID = id
536 break
537 }
538 c.inbox.mu.Unlock()
539 done := event.Event{
540 Kind: event.TurnDone,
541 Err: err,
542 Cancelled: cancelRequested,
543 Outcome: turnOutcome(err),
544 CheckpointTurn: c.validatedCheckpointTurn(completion),
545 Receipt: c.executor.CompletionReceipt(),
546 ItemID: activeInboxID,
547 }
548 if done.CheckpointTurn != nil {
549 changes := completion.checkpoint.store.FreezeTurnChanges(*done.CheckpointTurn)
550 if done.Receipt == nil && (len(changes.Files) > 0 || len(changes.Reasons) > 0) {
551 done.Receipt = &event.CompletionReceipt{AssessmentKind: "facts", Verdict: "unknown"}
552 }
553 if done.Receipt != nil {
554 receipt := *done.Receipt
555 receipt.Diff = changes.Summary()
556 receipt.Interrupted = cancelRequested
557 done.Receipt = &receipt
558 }
559 }
560 done.Receipt = bindCompletionLogSources(done.Receipt, c.History())
561 done = c.applyTurnDoneProtocol(done, cancelRequested)
562 c.applyToolRecoveryTurnStatus(&done, completion)
563 var readErr *agent.IncompleteReadError
564 if errors.As(err, &readErr) {
565 done.ReadPause = readErr.Pause
566 }
567 if !cancelRequested {
568 done.ProtocolRecovery = c.executor.PendingProtocolRecovery()
569 }
570 var readinessErr *agent.FinalReadinessError
571 if errors.As(err, &readinessErr) {
572 done.Readiness = &event.FinalReadiness{Attempts: readinessErr.Attempts, Missing: append([]string(nil), readinessErr.Missing...)}
573 }
574 c.onInboxTurnDone()
575 c.sink.Emit(done)
576 }
577
578 func (c *Controller) startCancellationWatchdog(done chan struct{}) {
579 if c == nil || done == nil {
580 return
581 }
582 go func() {
583 timer := time.NewTimer(c.cancellationGrace())
584 defer timer.Stop()
585 select {
586 case <-timer.C:
587 case <-done:
588 return
589 }
590
591 c.mu.Lock()
592 stillRunning := c.turns.done == done && (c.turns.phase == session.RuntimeRunning || c.turns.phase == session.RuntimeCancelling)
593 turnID := c.turns.turnID
594 if stillRunning {
595 c.turns.recoveryFanout = true
596 c.enterRecoveryLocked("cancellation_grace_expired")
597 }
598 c.mu.Unlock()
599 if !stillRunning {
600 return
601 }
602 if turnID == "" {
603 if ledger := c.turnEventLedger(); ledger != nil {
604 turnID = ledger.ActiveTurnID()
605 }
606 }
607 recovery := &event.RecoveryStatus{
608 State: "recovery_required",
609 Phase: "cancellation_grace_expired",
610 Reason: "cancellation_grace_expired",
611 RequiresUserDecision: true,
612 }
613 _ = c.emitTurnEventChecked(event.Event{
614 Kind: event.TurnDone,
615 TurnID: turnID,
616 Status: event.TurnRecoveryRequired,
617 Cancelled: true,
618 Outcome: "unknown",
619 Recovery: recovery,
620 })
621 c.mu.Lock()
622 c.turns.recoveryFanout = false
623 closing := c.closed && c.turns.done == nil && !c.finalizingLocked()
624 c.mu.Unlock()
625 if closing {
626 c.finalizeControllerClose()
627 }
628 c.refreshRuntimeState(event.Event{})
629 }()
630 }
631
631 lines GO