package thintest import ( "context" "fmt" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // Turn batching: messages sent while a turn runs wait in one queued turn // and go to the coordinator together when it ends, exactly once, however // it ends and whatever crashes between. The runner here speaks protocol // 1, the oldest the instance serves. // busyWithThree starts a turn, has the runner take it, and queues three // messages behind it. func (r *rig) busyWithThree(runner *FakeRunner) (wire.Sent, []wire.Sent) { r.t.Helper() busy, err := r.client.Send(r.ctx, "one", "k0") if err != nil { r.t.Fatal(err) } f, _, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { r.t.Fatal(err) } runner.Send(r.ctx, "a0", wire.FrameAck, wire.Ack{ID: f.ID}) r.turnIs(busy.Turn.ID, wire.TurnRunning) var queued []wire.Sent for i, text := range []string{"alpha", "bravo", "charlie"} { s, err := r.client.Send(r.ctx, text, "kq"+string(rune('1'+i))) if err != nil || s.Turn.ID == busy.Turn.ID || s.Turn.State != wire.TurnQueued || len(queued) > 0 && s.Turn.ID != queued[0].Turn.ID { r.t.Fatalf("message %d: %+v %v", i+1, s.Turn, err) } queued = append(queued, s) } return busy, queued } // acked waits for the instance's ack of one of the runner's frames. func (r *rig) acked(runner *FakeRunner, id string) { r.t.Helper() for { _, body, err := runner.Expect(r.ctx, wire.FrameAck) if err != nil { r.t.Fatalf("no ack for %s: %v", id, err) } if body.(*wire.Ack).ID == id { return } } } // turnIs waits until the API reads a turn in state. func (r *rig) turnIs(id, state string) wire.Turn { r.t.Helper() var got wire.Turn for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { var err error if got, err = r.client.Turn(r.ctx, id); err == nil && got.State == state { return got } } r.t.Fatalf("turn %s is %s (%s), not %s", id, got.State, got.Reason, state) return got } // batchFrame expects the next message frame to be the batch: the three // messages apart and in order, and nothing else. func (r *rig) batchFrame(runner *FakeRunner, batch string, texts ...string) wire.Frame { r.t.Helper() return r.batchFrameCarrying(runner, batch, nil, texts...) } // batchFrameCarrying is batchFrame for a batch after failed turns: their // person's words (carried) come first in PersonText, marked unanswered // in Text before the batch. func (r *rig) batchFrameCarrying(runner *FakeRunner, batch string, carried []string, texts ...string) wire.Frame { r.t.Helper() ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second) defer cancel() f, body, err := runner.Expect(ctx, wire.FrameMessage) if err != nil { r.t.Fatalf("no next turn: %v", err) } cmd := body.(*wire.MessageCommand) if cmd.TurnID != batch || len(cmd.PersonText) != len(carried)+len(texts) { r.t.Fatalf("next turn %s carries %q, not the batch %s", cmd.TurnID, cmd.PersonText, batch) } at := -1 for i, text := range carried { n := strings.Index(cmd.Text, "Not yet answered, the person's words: "+strconv.Quote(text)) if n <= at || cmd.PersonText[i] != text { r.t.Fatalf("batch lacks unanswered %q in place:\n%s", text, cmd.Text) } at = n } for i, text := range texts { n := strings.Index(cmd.Text, "Message "+string(rune('1'+i))+" of "+string(rune('0'+len(texts)))+":\n"+text) if n <= at || cmd.PersonText[len(carried)+i] != text { r.t.Fatalf("batch lacks %q in place:\n%s", text, cmd.Text) } at = n } shape(r.t, "frames/message.json", runner.Received[len(runner.Received)-1]) return f } // exactlyOnce checks a batch went to the runner in one message frame, // that the conversation has turns turns, and that no turn has two replies. func (r *rig) exactlyOnce(batch string, turns int) { r.t.Helper() var frames, all, replies int db := r.inst.DB.Writer() if err := db.QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameMessage, `%"turn_id":"`+batch+`"%`).Scan(&frames); err != nil { r.t.Fatal(err) } if err := db.QueryRow("SELECT count(*) FROM chat_turns").Scan(&all); err != nil { r.t.Fatal(err) } if err := db.QueryRow("SELECT coalesce(max(n), 0) FROM (SELECT count(*) AS n FROM chat_messages WHERE role = ? GROUP BY turn_id)", wire.RoleCoordinator).Scan(&replies); err != nil { r.t.Fatal(err) } if frames != 1 || all != turns { r.t.Fatalf("batch %s went out %d times; %d turns, want %d", batch, frames, all, turns) } if replies > 1 { r.t.Fatalf("a turn has %d replies", replies) } } // A crash between the end of a turn and the start of the next leaves // neither: the instance commits both in one transaction, so the runner's // reply comes again after the restart and starts exactly one next turn. func TestBatchCrashBetweenTurns(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID db := r.inst.DB.Writer() if _, err := db.Exec(`CREATE TRIGGER batch_crash BEFORE INSERT ON runner_commands WHEN NEW.kind = 'message' BEGIN SELECT RAISE(ABORT, 'crash'); END`); err != nil { t.Fatal(err) } reply := wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"} runner.Send(r.ctx, "rep1", wire.FrameReply, reply) for { _, body, err := runner.Next(r.ctx) if err != nil { break } if a, ok := body.(*wire.Ack); ok && a.ID == "rep1" { t.Fatal("the reply was acked with the next turn refused") } } if st, _ := r.client.Turn(r.ctx, busy.Turn.ID); st.State != wire.TurnRunning { t.Fatalf("turn ended without its successor: %s", st.State) } if st, _ := r.client.Turn(r.ctx, batch); st.State != wire.TurnQueued || len(st.MessageIDs) != 3 { t.Fatalf("batch %+v", st) } if _, err := db.Exec(`DROP TRIGGER batch_crash`); err != nil { t.Fatal(err) } r.inst.Restart(t) again := r.dial(runner.Welcome.Generation) again.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnRunning}}}) // Frames apply in order: once a no-op report is acked, the sync is in. again.Send(r.ctx, "s1b", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnRunning}) r.acked(again, "s1b") // The runner still holds the turn: the batch waits for it. var early int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameMessage, `%"turn_id":"`+batch+`"%`).Scan(&early); err != nil || early != 0 { t.Fatalf("batch went out beside the running turn: %d %v", early, err) } again.Send(r.ctx, "rep1", wire.FrameReply, reply) f := r.batchFrame(again, batch, "alpha", "bravo", "charlie") // The same reply once more, and a reconnect that resends the unacked // frame: still the one batch. again.Send(r.ctx, "rep1", wire.FrameReply, reply) again.Close() back := r.dial(runner.Welcome.Generation) if f2 := r.batchFrame(back, batch, "alpha", "bravo", "charlie"); f2.ID != f.ID { t.Fatalf("reconnect wrote a new frame %s, not %s", f2.ID, f.ID) } back.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID}) r.turnIs(batch, wire.TurnRunning) back.Send(r.ctx, "rep2", wire.FrameReply, wire.Reply{TurnID: batch, Attempt: 1, Text: "all three"}) r.turnIs(batch, wire.TurnReplied) r.exactlyOnce(batch, 2) } // A turn whose end committed without its successor (an older instance, or // a failure this one does not have) recovers on the runner's next sync: // exactly one next turn, the waiting messages in it. func TestBatchStrandedRecovers(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID if _, err := r.inst.DB.Writer().Exec("UPDATE chat_turns SET state = ? WHERE id = ?", wire.TurnFailed, busy.Turn.ID); err != nil { t.Fatal(err) } runner.Close() r.inst.Restart(t) again := r.dial(runner.Welcome.Generation) again.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}}) f := r.batchFrameCarrying(again, batch, []string{"one"}, "alpha", "bravo", "charlie") again.Send(r.ctx, "s2", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}}) again.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID}) r.turnIs(batch, wire.TurnRunning) r.exactlyOnce(batch, 2) } // However the running turn ends (failed, cancelled, or lost across a // runner reconnect), the batch goes next, once, and the ended turn keeps // its own message. A failed turn's words ride before the batch, marked // unanswered; a cancelled turn's do not (the person stopped it). func TestBatchAfterTurnEnds(t *testing.T) { for _, end := range []string{"failed", "cancelled", "interrupted"} { t.Run(end, func(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID switch end { case "failed": runner.Send(r.ctx, "e1", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"}) case "cancelled": if _, err := r.client.Cancel(r.ctx, busy.Turn.ID); err != nil { t.Fatal(err) } if _, _, err := runner.Expect(r.ctx, wire.FrameCancel); err != nil { t.Fatal(err) } runner.Send(r.ctx, "e1", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) case "interrupted": // A new runner process no longer holds the turn. runner.Close() runner = r.dial(0) runner.Send(r.ctx, "e1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}}) } var carried []string if end != "cancelled" { carried = []string{"one"} } r.batchFrameCarrying(runner, batch, carried, "alpha", "bravo", "charlie") if st, _ := r.client.Turn(r.ctx, busy.Turn.ID); !wire.Terminal(st.State) || len(st.MessageIDs) != 1 { t.Fatalf("ended turn %+v", st) } r.exactlyOnce(batch, 2) }) } } // A turn the runner retries (a new attempt on another connection) keeps // the batch waiting: a message sent meanwhile joins it, and the batch // goes once, after the retried attempt's reply. A late reply from the // abandoned attempt changes nothing. func TestBatchWaitsForRetriedTurn(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID runner.Send(r.ctx, "r2", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 2, State: wire.TurnRunning}) for got := r.turnIs(busy.Turn.ID, wire.TurnRunning); got.Attempt != 2; got = r.turnIs(busy.Turn.ID, wire.TurnRunning) { time.Sleep(20 * time.Millisecond) } fourth, err := r.client.Send(r.ctx, "delta", "kq4") if err != nil || fourth.Turn.ID != batch || len(fourth.Turn.MessageIDs) != 4 { t.Fatalf("message during the retry: %+v %v", fourth.Turn, err) } runner.Send(r.ctx, "late", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "stale"}) runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 2, Text: "first"}) r.batchFrame(runner, batch, "alpha", "bravo", "charlie", "delta") if got := r.turnIs(busy.Turn.ID, wire.TurnReplied); got.Attempt != 2 { t.Fatalf("replied on attempt %d", got.Attempt) } r.exactlyOnce(batch, 2) } // Cancelling the waiting batch ends all its messages together, unsent; // the next message starts a turn of its own without them. func TestBatchCancelledWhileWaiting(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID if _, err := r.client.Cancel(r.ctx, batch); err != nil { t.Fatal(err) } if got := r.turnIs(batch, wire.TurnCancelled); len(got.MessageIDs) != 3 { t.Fatalf("cancelled batch %+v", got) } later, err := r.client.Send(r.ctx, "echo", "kq5") if err != nil || later.Turn.ID == batch || len(later.Turn.MessageIDs) != 1 { t.Fatalf("later message %+v %v", later.Turn, err) } runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"}) _, body, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatal(err) } if cmd := body.(*wire.MessageCommand); cmd.TurnID != later.Turn.ID || withoutProjectContext(t, cmd.Text) != "echo" { t.Fatalf("after a cancelled batch the runner got %s %q", cmd.TurnID, cmd.Text) } } // Each waiting message keeps its own bubble in the queued turn, with the // one quiet note under the latest. The note goes for all of them together // the moment the turn picks them up (its frame is out), before the runner // acks it, and the bubbles stay. func TestBatchMarkerClearsTogether(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID const note = "
" bubbles := func(page string) int { at := -1 for i, m := range queued { n := strings.Index(page, `data-message="`+m.Message.ID+`" data-turn-id="`+batch+`"`) if n <= at { t.Fatalf("bubble %d missing or out of order", i+1) } at = n } return at } page := r.inst.Get(t, "/conversation") if last := bubbles(page); strings.Count(page, note) != 1 || strings.Index(page, note) < last { t.Fatal("waiting messages lack the one note under the latest") } runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"}) f := r.batchFrame(runner, batch, "alpha", "bravo", "charlie") if page = r.inst.Get(t, "/conversation"); strings.Contains(page, note) { t.Fatal("the note stayed after the turn picked the messages up") } bubbles(page) runner.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID}) r.turnIs(batch, wire.TurnRunning) if page = r.inst.Get(t, "/conversation"); strings.Contains(page, note) { t.Fatal("the note came back while the turn runs") } bubbles(page) } // Messages that would not fit one frame together go as several batches, // one turn after another, in order. Each frame fits (the runner reads at // most wire.MaxFrameBytes): the oldest tail goes first, and a later // batch's messages are never in an earlier one's tail. func TestBatchSplitsToFitTheFrame(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, err := r.client.Send(r.ctx, "one", "k0") if err != nil { t.Fatal(err) } f, _, _ := runner.Expect(r.ctx, wire.FrameMessage) runner.Send(r.ctx, "a0", wire.FrameAck, wire.Ack{ID: f.ID}) r.turnIs(busy.Turn.ID, wire.TurnRunning) var texts []string turns := map[string][]string{} var order []string for i := range 12 { // Near the largest message, with characters JSON escapes (the // person API reads at most twice the limit). text := fmt.Sprintf("m%02d %s%s", i+1, strings.Repeat("x", wire.MaxMessageBytes-2008), strings.Repeat("<", 2000)) s, err := r.client.Send(r.ctx, text, fmt.Sprintf("kb%d", i)) if err != nil { t.Fatal(err) } if _, ok := turns[s.Turn.ID]; !ok { order = append(order, s.Turn.ID) } turns[s.Turn.ID] = append(turns[s.Turn.ID], text) texts = append(texts, text) } if len(order) < 2 || len(turns[order[0]]) < 2 { t.Fatalf("12 large messages made batches of %v", order) } end := wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"} var got []string for i, batch := range order { runner.Send(r.ctx, fmt.Sprintf("rep%d", i), wire.FrameReply, end) mf, body, err := runner.Expect(r.ctx, wire.FrameMessage) if err != nil { t.Fatalf("batch %d: %v", i+1, err) } cmd := body.(*wire.MessageCommand) if cmd.TurnID != batch || len(cmd.PersonText) != len(turns[batch]) { t.Fatalf("batch %d is %s with %d messages", i+1, cmd.TurnID, len(cmd.PersonText)) } for _, m := range cmd.Tail { for _, later := range order[i+1:] { for _, text := range turns[later] { if m.Text == text { t.Fatalf("batch %d's tail holds a message still waiting", i+1) } } } } if len(cmd.Tail) == 0 || cmd.Tail[len(cmd.Tail)-1].Text != end.Text { t.Fatalf("batch %d's tail lost the newest reply", i+1) } got = append(got, cmd.PersonText...) runner.Send(r.ctx, fmt.Sprintf("ab%d", i), wire.FrameAck, wire.Ack{ID: mf.ID}) r.turnIs(batch, wire.TurnRunning) end = wire.Reply{TurnID: batch, Attempt: 1, Text: fmt.Sprintf("reply %d", i+1)} } if len(got) != len(texts) { t.Fatalf("%d of %d messages reached the coordinator", len(got), len(texts)) } for i := range texts { if got[i] != texts[i] { t.Fatalf("message %d out of place", i+1) } } } // A failed batch says the coordinator could not answer these messages; a // failed turn of one message still says this message. (A reason with // words of its own says those: chat_failed.go.) func TestBatchFailedSaysThemAll(t *testing.T) { r := newRig(t) runner := r.dial(0) busy, queued := r.busyWithThree(runner) batch := queued[0].Turn.ID runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"}) f := r.batchFrame(runner, batch, "alpha", "bravo", "charlie") runner.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID}) runner.Send(r.ctx, "fb", wire.FrameTurn, wire.TurnReport{TurnID: batch, Attempt: 1, State: wire.TurnFailed, Reason: ""}) r.turnIs(batch, wire.TurnFailed) if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+batch+`">
The coordinator could not answer these messages.
`) { t.Fatal("a failed batch lacks the note for its messages") } one, err := r.client.Send(r.ctx, "delta", "kq6") if err != nil { t.Fatal(err) } of, _, _ := runner.Expect(r.ctx, wire.FrameMessage) runner.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: of.ID}) runner.Send(r.ctx, "f1", wire.FrameTurn, wire.TurnReport{TurnID: one.Turn.ID, Attempt: 1, State: wire.TurnFailed, Reason: ""}) r.turnIs(one.Turn.ID, wire.TurnFailed) if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+one.Turn.ID+`">The coordinator could not answer this message.
`) { t.Fatal("a failed single message lacks its note") } }