| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "sort" |
| 9 | "sync" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "reasonix/internal/event" |
| 14 | "reasonix/internal/sessioninbox" |
| 15 | ) |
| 16 | |
| 17 | const inboxDispatchTestTimeout = 15 * time.Second |
| 18 | |
| 19 | func TestClosedControllerCannotOpenInboxFromLateDispatch(t *testing.T) { |
| 20 | dir := t.TempDir() |
| 21 | c := newOwnedTestController(t, Options{}) |
| 22 | // Model the dispatcher having a persisted path but no opened sidecar yet. |
| 23 | c.mu.Lock() |
| 24 | c.sessionPath = filepath.Join(dir, "session.jsonl") |
| 25 | c.mu.Unlock() |
| 26 | c.SetBeforeInboxDispatch(func(*Controller) (func(), error) { t.Error("closed controller entered admission"); return nil, nil }) |
| 27 | c.Close() |
| 28 | c.NotifyInboxRuntimeReady() |
| 29 | if _, err := c.ensureInbox(); err == nil { |
| 30 | t.Fatal("closed controller opened an inbox") |
| 31 | } |
| 32 | c.rebindInbox() |
| 33 | c.autosaveWG.Wait() |
| 34 | entries, err := os.ReadDir(dir) |
| 35 | if err != nil || len(entries) != 0 { |
| 36 | t.Fatalf("late dispatch created sidecars: %v %v", entries, err) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | type inboxDispatchRunner struct { |
| 41 | inputs chan string |
| 42 | } |
| 43 | |
| 44 | func (r *inboxDispatchRunner) Run(_ context.Context, input string) error { |
| 45 | r.inputs <- input |
| 46 | return nil |
| 47 | } |
| 48 | |
| 49 | func newInboxDispatchController(t *testing.T) (*Controller, *inboxDispatchRunner, <-chan struct{}) { |
| 50 | t.Helper() |
| 51 | dir := t.TempDir() |
| 52 | runner := &inboxDispatchRunner{inputs: make(chan string, 8)} |
| 53 | done := make(chan struct{}, 8) |
| 54 | c := newOwnedTestController(t, Options{ |
| 55 | Runner: runner, |
| 56 | Sink: event.FuncSink(func(e event.Event) { |
| 57 | if e.Kind == event.TurnDone { |
| 58 | done <- struct{}{} |
| 59 | } |
| 60 | }), |
| 61 | SessionDir: dir, |
| 62 | SessionPath: filepath.Join(dir, "session.jsonl"), |
| 63 | }) |
| 64 | t.Cleanup(func() { |
| 65 | c.Close() |
| 66 | c.autosaveWG.Wait() |
| 67 | }) |
| 68 | return c, runner, done |
| 69 | } |
| 70 | |
| 71 | func failInboxDispatchWait(t *testing.T, c *Controller, waitingFor string) { |
| 72 | t.Helper() |
| 73 | c.inbox.mu.Lock() |
| 74 | active := c.inbox.activeIDs() |
| 75 | dispatching := c.inbox.dispatching |
| 76 | dispatchPending := c.inbox.dispatchPending |
| 77 | c.inbox.mu.Unlock() |
| 78 | sort.Strings(active) |
| 79 | t.Fatalf( |
| 80 | "timed out after %s waiting for %s: runtime=%+v inbox=%+v active_items=%v dispatching=%t dispatch_pending=%t", |
| 81 | inboxDispatchTestTimeout, |
| 82 | waitingFor, |
| 83 | c.RuntimeStatus(), |
| 84 | c.InboxSnapshot(), |
| 85 | active, |
| 86 | dispatching, |
| 87 | dispatchPending, |
| 88 | ) |
| 89 | } |
| 90 | |
| 91 | func waitForInboxDispatch(t *testing.T, c *Controller, runner *inboxDispatchRunner) string { |
| 92 | t.Helper() |
| 93 | select { |
| 94 | case input := <-runner.inputs: |
| 95 | return input |
| 96 | case <-time.After(inboxDispatchTestTimeout): |
| 97 | failInboxDispatchWait(t, c, "inbox dispatch") |
| 98 | return "" |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | func waitForInboxTurnDone(t *testing.T, c *Controller, done <-chan struct{}) { |
| 103 | t.Helper() |
| 104 | select { |
| 105 | case <-done: |
| 106 | case <-time.After(inboxDispatchTestTimeout): |
| 107 | failInboxDispatchWait(t, c, "inbox turn completion") |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | func TestEndRotationDispatchesQueuedInboxItem(t *testing.T) { |
| 112 | c, runner, done := newInboxDispatchController(t) |
| 113 | if err := c.beginRotation(); err != nil { |
| 114 | t.Fatal(err) |
| 115 | } |
| 116 | if _, err := c.TryEnqueueFollowup(InboxRequest{ |
| 117 | Intent: sessioninbox.IntentFollowup, |
| 118 | Submit: "queued during rotation", |
| 119 | }); err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | c.endRotation() |
| 123 | |
| 124 | if got := waitForInboxDispatch(t, c, runner); got != "queued during rotation" { |
| 125 | t.Fatalf("dispatched input = %q", got) |
| 126 | } |
| 127 | waitForInboxTurnDone(t, c, done) |
| 128 | } |
| 129 | |
| 130 | func TestRejectedIdleSteerDispatchesAsFollowup(t *testing.T) { |
| 131 | c, runner, done := newInboxDispatchController(t) |
| 132 | rec, err := c.EnqueueInbox(InboxRequest{ |
| 133 | Intent: sessioninbox.IntentSteer, |
| 134 | Submit: "late steer becomes follow-up", |
| 135 | }) |
| 136 | if err != nil { |
| 137 | t.Fatal(err) |
| 138 | } |
| 139 | receipt, err := c.TrySteerInboxItem(rec.ItemID) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | if receipt.Disposition != sessioninbox.DispositionQueuedFollowup { |
| 144 | t.Fatalf("disposition = %q", receipt.Disposition) |
| 145 | } |
| 146 | |
| 147 | if got := waitForInboxDispatch(t, c, runner); got != "late steer becomes follow-up" { |
| 148 | t.Fatalf("dispatched input = %q", got) |
| 149 | } |
| 150 | waitForInboxTurnDone(t, c, done) |
| 151 | } |
| 152 | |
| 153 | func TestInboxDispatchKickDuringEmptyScanIsNotLost(t *testing.T) { |
| 154 | c, runner, done := newInboxDispatchController(t) |
| 155 | scanReached := make(chan struct{}) |
| 156 | releaseScan := make(chan struct{}) |
| 157 | var once sync.Once |
| 158 | c.inbox.mu.Lock() |
| 159 | c.inbox.afterDispatchScan = func(found bool) { |
| 160 | if found { |
| 161 | return |
| 162 | } |
| 163 | once.Do(func() { |
| 164 | close(scanReached) |
| 165 | <-releaseScan |
| 166 | }) |
| 167 | } |
| 168 | c.inbox.mu.Unlock() |
| 169 | |
| 170 | dispatchReturned := make(chan struct{}) |
| 171 | go func() { |
| 172 | c.maybeDispatchInbox() |
| 173 | close(dispatchReturned) |
| 174 | }() |
| 175 | select { |
| 176 | case <-scanReached: |
| 177 | case <-time.After(inboxDispatchTestTimeout): |
| 178 | failInboxDispatchWait(t, c, "dispatcher empty scan") |
| 179 | } |
| 180 | if _, err := c.EnqueueInbox(InboxRequest{Submit: "arrived during empty scan"}); err != nil { |
| 181 | t.Fatal(err) |
| 182 | } |
| 183 | // This kick lands while the first dispatcher still owns the handoff. The |
| 184 | // pending level must make that dispatcher scan again before it exits. |
| 185 | c.maybeDispatchInbox() |
| 186 | close(releaseScan) |
| 187 | |
| 188 | select { |
| 189 | case <-dispatchReturned: |
| 190 | case <-time.After(inboxDispatchTestTimeout): |
| 191 | failInboxDispatchWait(t, c, "dispatcher return") |
| 192 | } |
| 193 | if got := waitForInboxDispatch(t, c, runner); got != "arrived during empty scan" { |
| 194 | t.Fatalf("dispatched input = %q", got) |
| 195 | } |
| 196 | waitForInboxTurnDone(t, c, done) |
| 197 | } |
| 198 | |
| 199 | func TestInboxDispatchRetriesTransientOwnerFailure(t *testing.T) { |
| 200 | c, runner, done := newInboxDispatchController(t) |
| 201 | retryReady := make(chan func(), 1) |
| 202 | failedOnce := false |
| 203 | c.inbox.mu.Lock() |
| 204 | c.inbox.beforeDispatchSubmit = func(string) error { |
| 205 | if failedOnce { |
| 206 | return nil |
| 207 | } |
| 208 | failedOnce = true |
| 209 | return errors.New("temporary dispatch failure") |
| 210 | } |
| 211 | c.inbox.scheduleDispatchRetry = func(_ time.Duration, retry func()) { |
| 212 | retryReady <- retry |
| 213 | } |
| 214 | c.inbox.mu.Unlock() |
| 215 | if _, err := c.EnqueueInbox(InboxRequest{Submit: "retry me"}); err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | c.maybeDispatchInbox() |
| 219 | |
| 220 | var retry func() |
| 221 | select { |
| 222 | case retry = <-retryReady: |
| 223 | case <-time.After(inboxDispatchTestTimeout): |
| 224 | failInboxDispatchWait(t, c, "transient failure retry") |
| 225 | } |
| 226 | select { |
| 227 | case got := <-runner.inputs: |
| 228 | t.Fatalf("item dispatched before scheduled retry: %q", got) |
| 229 | default: |
| 230 | } |
| 231 | retry() |
| 232 | if got := waitForInboxDispatch(t, c, runner); got != "retry me" { |
| 233 | t.Fatalf("retried input = %q", got) |
| 234 | } |
| 235 | waitForInboxTurnDone(t, c, done) |
| 236 | } |
| 237 | |
| 238 | type gatedInboxDispatchRunner struct { |
| 239 | inputs chan string |
| 240 | firstStarted chan struct{} |
| 241 | releaseFirst chan struct{} |
| 242 | once sync.Once |
| 243 | } |
| 244 | |
| 245 | func (r *gatedInboxDispatchRunner) Run(ctx context.Context, input string) error { |
| 246 | r.inputs <- input |
| 247 | blocked := false |
| 248 | r.once.Do(func() { |
| 249 | blocked = true |
| 250 | close(r.firstStarted) |
| 251 | }) |
| 252 | if !blocked { |
| 253 | return nil |
| 254 | } |
| 255 | select { |
| 256 | case <-r.releaseFirst: |
| 257 | return nil |
| 258 | case <-ctx.Done(): |
| 259 | return ctx.Err() |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | func TestNaturalCompletionAutoDispatchesDurableFIFO(t *testing.T) { |
| 264 | dir := t.TempDir() |
| 265 | runner := &gatedInboxDispatchRunner{ |
| 266 | inputs: make(chan string, 8), |
| 267 | firstStarted: make(chan struct{}), |
| 268 | releaseFirst: make(chan struct{}), |
| 269 | } |
| 270 | done := make(chan struct{}, 8) |
| 271 | c := newOwnedTestController(t, Options{ |
| 272 | Runner: runner, |
| 273 | Sink: event.FuncSink(func(e event.Event) { |
| 274 | if e.Kind == event.TurnDone { |
| 275 | done <- struct{}{} |
| 276 | } |
| 277 | }), |
| 278 | SessionDir: dir, |
| 279 | SessionPath: filepath.Join(dir, "session.jsonl"), |
| 280 | }) |
| 281 | t.Cleanup(func() { |
| 282 | c.Close() |
| 283 | c.autosaveWG.Wait() |
| 284 | }) |
| 285 | |
| 286 | c.Submit("active turn") |
| 287 | select { |
| 288 | case <-runner.firstStarted: |
| 289 | case <-time.After(inboxDispatchTestTimeout): |
| 290 | failInboxDispatchWait(t, c, "active turn start") |
| 291 | } |
| 292 | if got := <-runner.inputs; got != "active turn" { |
| 293 | t.Fatalf("initial input = %q", got) |
| 294 | } |
| 295 | for _, input := range []string{"queued one", "queued two"} { |
| 296 | if _, err := c.EnqueueInbox(InboxRequest{Intent: sessioninbox.IntentFollowup, Submit: input}); err != nil { |
| 297 | t.Fatal(err) |
| 298 | } |
| 299 | } |
| 300 | close(runner.releaseFirst) |
| 301 | waitForInboxTurnDone(t, c, done) |
| 302 | for _, want := range []string{"queued one", "queued two"} { |
| 303 | if got := waitForInboxDispatch(t, c, &inboxDispatchRunner{inputs: runner.inputs}); got != want { |
| 304 | t.Fatalf("FIFO input = %q, want %q", got, want) |
| 305 | } |
| 306 | waitForInboxTurnDone(t, c, done) |
| 307 | } |
| 308 | if snap := c.InboxSnapshot(); len(snap.Items) != 0 || snap.Paused { |
| 309 | t.Fatalf("completed FIFO left inbox state: %+v", snap) |
| 310 | } |
| 311 | } |
| 312 |