| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | // The Assistant's files (assistant attachments spec 2026-11-26, A1 to A6), |
| 16 | // at the store: its send takes files only with a primary seen at protocol |
| 17 | // 32, the snapshot says so, and its frames carry the files of the |
| 18 | // conversation. |
| 19 | |
| 20 | // filesRig is a hkRig whose primary was last seen at protocol (none: no |
| 21 | // session row). |
| 22 | func filesRig(t *testing.T, protocol int) *hkRig { |
| 23 | t.Helper() |
| 24 | r := newHKRig(t) |
| 25 | if protocol > 0 { |
| 26 | r.must(r.s.db.G.Create(&runnerSessionRecord{RunnerID: "RUNNER1", Generation: 1, Connected: true, Protocol: protocol, SeenAt: r.now}).Error) |
| 27 | } |
| 28 | return r |
| 29 | } |
| 30 | |
| 31 | // upload keeps a small text file for person. |
| 32 | func (r *hkRig) upload(person, name, body string) string { |
| 33 | r.t.Helper() |
| 34 | a, err := r.s.Upload(r.ctx, person, name, "text/markdown", []byte(body)) |
| 35 | r.must(err) |
| 36 | return a.ID |
| 37 | } |
| 38 | |
| 39 | func ids(files []wire.MessageAttachment) []string { |
| 40 | out := make([]string, 0, len(files)) |
| 41 | for _, f := range files { |
| 42 | out = append(out, f.ID) |
| 43 | } |
| 44 | return out |
| 45 | } |
| 46 | |
| 47 | // unsent counts the person's uploads on no message. |
| 48 | func (r *hkRig) unsent(person string) int64 { |
| 49 | return r.count("SELECT count(*) FROM chat_attachments WHERE person = ? AND message_id = ''", person) |
| 50 | } |
| 51 | |
| 52 | // TestAssistantSendTakesFiles (A1): with a primary at 33 the Assistant's |
| 53 | // send takes up to five of the person's own unsent uploads, in order, as |
| 54 | // the Coordinator's does, and every view of the message carries them. |
| 55 | func TestAssistantSendTakesFiles(t *testing.T) { |
| 56 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 57 | lane := r.s.Lane(wire.LaneAssistant) |
| 58 | a, b := r.upload(hkOwner, "a.md", "# a"), r.upload(hkOwner, "b.md", "# b") |
| 59 | sent, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, b}, IdempotencyKey: "k1"}) |
| 60 | if err != nil || !created { |
| 61 | t.Fatalf("send %v %v", created, err) |
| 62 | } |
| 63 | want := []string{a, b} |
| 64 | if !slices.Equal(ids(sent.Message.Attachments), want) { |
| 65 | t.Fatalf("sent with %v", ids(sent.Message.Attachments)) |
| 66 | } |
| 67 | snap, err := lane.Snapshot(r.ctx, hkOwner) |
| 68 | if err != nil || len(snap.Messages) != 1 || !slices.Equal(ids(snap.Messages[0].Attachments), want) { |
| 69 | t.Fatalf("snapshot %+v %v", snap.Messages, err) |
| 70 | } |
| 71 | page, err := lane.Messages(r.ctx, hkOwner, "", 10) |
| 72 | if err != nil || len(page.Items) != 1 || !slices.Equal(ids(page.Items[0].Attachments), want) { |
| 73 | t.Fatalf("page %+v %v", page.Items, err) |
| 74 | } |
| 75 | events, err := lane.Events(r.ctx, hkOwner, 0, 50) |
| 76 | r.must(err) |
| 77 | found := false |
| 78 | for _, e := range events { |
| 79 | if e.Type == wire.EventMessage && strings.Contains(string(e.Data), a) && strings.Contains(string(e.Data), b) { |
| 80 | found = true |
| 81 | } |
| 82 | } |
| 83 | if !found { |
| 84 | t.Fatalf("no message event with both files: %+v", events) |
| 85 | } |
| 86 | |
| 87 | // Files with no words. |
| 88 | c := r.upload(hkOwner, "c.md", "# c") |
| 89 | if _, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{c}, IdempotencyKey: "k2"}); err != nil || !created { |
| 90 | t.Fatalf("files only %v %v", created, err) |
| 91 | } |
| 92 | // The same key and files again is the same message; other files are |
| 93 | // a conflict. |
| 94 | again, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, b}, IdempotencyKey: "k1"}) |
| 95 | if err != nil || created || again.Message.ID != sent.Message.ID { |
| 96 | t.Fatalf("replay %v %v", created, err) |
| 97 | } |
| 98 | d := r.upload(hkOwner, "d.md", "# d") |
| 99 | if _, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, d}, IdempotencyKey: "k1"}); !errors.Is(err, ErrConflict) { |
| 100 | t.Fatalf("replay with other files: %v", err) |
| 101 | } |
| 102 | |
| 103 | // Refused as invalid: six files, another person's upload, a file |
| 104 | // already sent, an upload past its day, a project. |
| 105 | six := []string{} |
| 106 | for i := range 6 { |
| 107 | six = append(six, r.upload(hkOwner, "s"+string(rune('a'+i))+".md", "x")) |
| 108 | } |
| 109 | theirs := r.upload(hkMember, "theirs.md", "# theirs") |
| 110 | stale := r.upload(hkOwner, "stale.md", "# stale") |
| 111 | for name, in := range map[string]wire.SendMessage{ |
| 112 | "six": {Text: "x", Attachments: six, IdempotencyKey: "k3"}, |
| 113 | "theirs": {Text: "x", Attachments: []string{theirs}, IdempotencyKey: "k4"}, |
| 114 | "sent": {Text: "x", Attachments: []string{a}, IdempotencyKey: "k5"}, |
| 115 | "project": {Text: "x", ProjectID: "p1", IdempotencyKey: "k6"}, |
| 116 | } { |
| 117 | if _, _, err := lane.Send(r.ctx, hkOwner, in); !errors.Is(err, ErrInvalid) { |
| 118 | t.Fatalf("%s: %v", name, err) |
| 119 | } |
| 120 | } |
| 121 | r.now = r.now.Add(unsentFor + time.Minute) |
| 122 | if _, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "x", Attachments: []string{stale}, IdempotencyKey: "k7"}); !errors.Is(err, ErrInvalid) { |
| 123 | t.Fatalf("an upload past its day: %v", err) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // TestAssistantSendFilesNeedProtocol33 (A1, A6): files need a primary |
| 128 | // last seen at 33; one at 32 (unfinished work, no files) is too old. One older, or never seen, refuses the send with files |
| 129 | // and stores nothing; the same words alone pass. No primary is no_runner. |
| 130 | func TestAssistantSendFilesNeedProtocol33(t *testing.T) { |
| 131 | for name, protocol := range map[string]int{"at 32": wire.Protocol32, "at 31": wire.Protocol31, "never seen": 0} { |
| 132 | t.Run(name, func(t *testing.T) { |
| 133 | r := filesRig(t, protocol) |
| 134 | lane := r.s.Lane(wire.LaneAssistant) |
| 135 | a, b := r.upload(hkOwner, "a.md", "# a"), r.upload(hkOwner, "b.md", "# b") |
| 136 | if _, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", Attachments: []string{a, b}, IdempotencyKey: "k1"}); !errors.Is(err, ErrAttachmentsUnavailable) { |
| 137 | t.Fatalf("send with files: %v", err) |
| 138 | } |
| 139 | if n := r.count("SELECT count(*) FROM chat_messages"); n != 0 || r.count("SELECT count(*) FROM chat_turns") != 0 || r.unsent(hkOwner) != 2 { |
| 140 | t.Fatalf("a refused send stored something: %d messages, %d unsent", n, r.unsent(hkOwner)) |
| 141 | } |
| 142 | if _, created, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "Read these", IdempotencyKey: "k1"}); err != nil || !created { |
| 143 | t.Fatalf("words alone: %v %v", created, err) |
| 144 | } |
| 145 | }) |
| 146 | } |
| 147 | r := filesRig(t, 0) |
| 148 | r.s.authority.PrimaryRunner = func(*gorm.DB, string) (string, error) { return "", nil } |
| 149 | a := r.upload(hkOwner, "a.md", "# a") |
| 150 | if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "x", Attachments: []string{a}, IdempotencyKey: "k1"}); !errors.Is(err, ErrNoRunner) { |
| 151 | t.Fatalf("no primary: %v", err) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // TestAssistantSnapshotCanAttach (A1): can_attach is exactly the answer |
| 156 | // the send with files gets. |
| 157 | func TestAssistantSnapshotCanAttach(t *testing.T) { |
| 158 | for name, tc := range map[string]struct { |
| 159 | protocol int |
| 160 | primary bool |
| 161 | want bool |
| 162 | }{ |
| 163 | "at 33": {wire.ProtocolAssistantFiles, true, true}, |
| 164 | "at 32": {wire.Protocol32, true, false}, |
| 165 | "never seen": {0, true, false}, |
| 166 | "no runner": {0, false, false}, |
| 167 | } { |
| 168 | t.Run(name, func(t *testing.T) { |
| 169 | r := filesRig(t, tc.protocol) |
| 170 | if !tc.primary { |
| 171 | r.s.authority.PrimaryRunner = func(*gorm.DB, string) (string, error) { return "", nil } |
| 172 | } |
| 173 | snap, err := r.s.Lane(wire.LaneAssistant).Snapshot(r.ctx, hkOwner) |
| 174 | if err != nil || snap.CanAttach != tc.want { |
| 175 | t.Fatalf("can_attach %v, want %v: %v", snap.CanAttach, tc.want, err) |
| 176 | } |
| 177 | var check error |
| 178 | r.must(r.tx(func(t *txn) error { check = t.filesRunner(hkOwner); return nil })) |
| 179 | if (check == nil) != snap.CanAttach { |
| 180 | t.Fatalf("snapshot %v, send check %v", snap.CanAttach, check) |
| 181 | } |
| 182 | }) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // TestDeleteUnsent (A2): the person deletes their own unsent upload, its |
| 187 | // row and bytes, audited by id, and its slot is free again. Gone, or |
| 188 | // another person's, is not found; one already sent stays. |
| 189 | func TestDeleteUnsent(t *testing.T) { |
| 190 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 191 | var audits []string |
| 192 | r.s.authority.Audit = func(_ *gorm.DB, actor, kind, record string) error { |
| 193 | audits = append(audits, actor+" "+kind+" "+record) |
| 194 | return nil |
| 195 | } |
| 196 | held := []string{} |
| 197 | for i := range maxUnsent { |
| 198 | held = append(held, r.upload(hkOwner, "f"+string(rune('a'+i))+".md", "x")) |
| 199 | } |
| 200 | if _, err := r.s.Upload(r.ctx, hkOwner, "more.md", "text/markdown", []byte("x")); !errors.Is(err, ErrAttachmentLimit) { |
| 201 | t.Fatalf("the 21st upload: %v", err) |
| 202 | } |
| 203 | gone := held[0] |
| 204 | if err := r.s.DeleteUnsent(r.ctx, hkOwner, gone); err != nil { |
| 205 | t.Fatal(err) |
| 206 | } |
| 207 | if n := r.count("SELECT count(*) FROM chat_attachments WHERE id = ?", gone) + r.count("SELECT count(*) FROM chat_attachment_data WHERE id = ?", gone); n != 0 { |
| 208 | t.Fatalf("%d rows left", n) |
| 209 | } |
| 210 | if !slices.Contains(audits, hkOwner+" "+auditAttachmentDelete+" "+gone) { |
| 211 | t.Fatalf("audits %q", audits) |
| 212 | } |
| 213 | if _, err := r.s.Upload(r.ctx, hkOwner, "more.md", "text/markdown", []byte("x")); err != nil { |
| 214 | t.Fatalf("the 21st upload after a delete: %v", err) |
| 215 | } |
| 216 | if err := r.s.DeleteUnsent(r.ctx, hkOwner, gone); !errors.Is(err, ErrNotFound) { |
| 217 | t.Fatalf("second delete: %v", err) |
| 218 | } |
| 219 | if err := r.s.DeleteUnsent(r.ctx, hkMember, held[1]); !errors.Is(err, ErrNotFound) || r.unsent(hkOwner) != maxUnsent { |
| 220 | t.Fatalf("another person's: %v", err) |
| 221 | } |
| 222 | if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{held[1]}, IdempotencyKey: "k1"}); err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | if err := r.s.DeleteUnsent(r.ctx, hkOwner, held[1]); !errors.Is(err, ErrAttachmentSent) || r.count("SELECT count(*) FROM chat_attachment_data WHERE id = ?", held[1]) != 1 { |
| 226 | t.Fatalf("a sent upload: %v", err) |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // past records a person message in lane at, in a turn that was dispatched |
| 231 | // and replied, carrying newly uploaded files (by name). |
| 232 | func (r *hkRig) past(lane, text string, at time.Time, names ...string) []string { |
| 233 | r.t.Helper() |
| 234 | turn := turnRecord{ID: newID("t_"), Person: hkOwner, State: wire.TurnReplied, Attempt: 1, Dispatched: true, DispatchedAt: &at, Revision: 1, CreatedAt: at, UpdatedAt: at, Lane: lane} |
| 235 | r.must(r.s.db.G.Create(&turn).Error) |
| 236 | m := messageRecord{ID: newID("m_"), Person: hkOwner, IdempotencyKey: newID("k_"), Role: wire.RolePerson, Text: text, TurnID: turn.ID, Revision: 1, CreatedAt: at, Lane: lane, Origin: originComposer} |
| 237 | r.must(r.s.db.G.Create(&m).Error) |
| 238 | var ids []string |
| 239 | for i, name := range names { |
| 240 | id := r.upload(hkOwner, name, "# "+name) |
| 241 | r.must(r.s.db.G.Model(&fileRecord{}).Where("id = ?", id).Updates(map[string]any{"message_id": m.ID, "position": i + 1}).Error) |
| 242 | ids = append(ids, id) |
| 243 | } |
| 244 | return ids |
| 245 | } |
| 246 | |
| 247 | // lastFrame is the newest message command queued for the runner. |
| 248 | func (r *hkRig) lastFrame() wire.MessageCommand { |
| 249 | r.t.Helper() |
| 250 | var c commandRecord |
| 251 | r.must(r.s.db.G.Where("kind = ?", wire.FrameMessage).Order("seq DESC").First(&c).Error) |
| 252 | var m wire.MessageCommand |
| 253 | r.must(json.Unmarshal([]byte(c.Body), &m)) |
| 254 | return m |
| 255 | } |
| 256 | |
| 257 | func refIDs(refs []wire.AttachmentRef) []string { |
| 258 | out := []string{} |
| 259 | for _, f := range refs { |
| 260 | out = append(out, f.ID) |
| 261 | } |
| 262 | return out |
| 263 | } |
| 264 | |
| 265 | // TestAssistantFrameEarlier (A4): an Assistant person turn's frame lists |
| 266 | // the files of the person's own Assistant messages from the last 14 days, |
| 267 | // newest first, without this turn's own; never the Coordinator's, never |
| 268 | // older. A files-only message in the tail names its files. |
| 269 | func TestAssistantFrameEarlier(t *testing.T) { |
| 270 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 271 | day := 24 * time.Hour |
| 272 | r.past(wire.LaneAssistant, "an old one", r.now.Add(-15*day), "old.md") |
| 273 | two := r.past(wire.LaneAssistant, "see these", r.now.Add(-3*day), "a.md", "b.md") |
| 274 | one := r.past(wire.LaneAssistant, "", r.now.Add(-day), "c.md") |
| 275 | r.past(wire.LaneCoordinator, "the coordinator's", r.now.Add(-day), "coord.md") |
| 276 | mine := r.upload(hkOwner, "now.md", "# now") |
| 277 | if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", Attachments: []string{mine}, IdempotencyKey: "k1"}); err != nil { |
| 278 | t.Fatal(err) |
| 279 | } |
| 280 | m := r.lastFrame() |
| 281 | if want := []string{one[0], two[0], two[1]}; !slices.Equal(refIDs(m.Earlier), want) || m.EarlierMore != 0 { |
| 282 | t.Fatalf("earlier %v (+%d), want %v", refIDs(m.Earlier), m.EarlierMore, want) |
| 283 | } |
| 284 | if !slices.Equal(refIDs(m.Attachments), []string{mine}) || m.Earlier[0].Name != "c.md" || m.Earlier[0].SHA256 == "" || m.Earlier[0].Size == 0 { |
| 285 | t.Fatalf("frame %+v", m) |
| 286 | } |
| 287 | var tail []string |
| 288 | for _, x := range m.Tail { |
| 289 | tail = append(tail, x.Text) |
| 290 | } |
| 291 | if !slices.Contains(tail, "(sent files: c.md)") || !slices.Contains(tail, "see these") || slices.Contains(tail, "") { |
| 292 | t.Fatalf("tail %q", tail) |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // TestAssistantFrameEarlierCap: at most 20, newest first; earlier_more |
| 297 | // counts the rest. |
| 298 | func TestAssistantFrameEarlierCap(t *testing.T) { |
| 299 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 300 | var all []string |
| 301 | for i := range 5 { |
| 302 | ids := r.past(wire.LaneAssistant, "batch", r.now.Add(-time.Duration(5-i)*time.Hour), "1.md", "2.md", "3.md", "4.md", "5.md") |
| 303 | all = append(ids, all...) |
| 304 | } |
| 305 | // all is newest message first; each message's files in their order. |
| 306 | want := []string{} |
| 307 | for i := 0; i < 25; i += 5 { |
| 308 | want = append(want, all[i:i+5]...) |
| 309 | } |
| 310 | if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", IdempotencyKey: "k1"}); err != nil { |
| 311 | t.Fatal(err) |
| 312 | } |
| 313 | m := r.lastFrame() |
| 314 | if !slices.Equal(refIDs(m.Earlier), want[:wire.MaxEarlierFiles]) || m.EarlierMore != 5 { |
| 315 | t.Fatalf("earlier %d (+%d)", len(m.Earlier), m.EarlierMore) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // TestFrameEarlierOnlyAssistantPersonTurns: a team_update turn and a |
| 320 | // Coordinator turn carry no earlier files. |
| 321 | func TestFrameEarlierOnlyAssistantPersonTurns(t *testing.T) { |
| 322 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 323 | r.past(wire.LaneAssistant, "see this", r.now.Add(-time.Hour), "a.md") |
| 324 | r.past(wire.LaneCoordinator, "and this", r.now.Add(-time.Hour), "b.md") |
| 325 | update := turnRecord{ID: newID("t_"), Person: hkOwner, State: wire.TurnQueued, Attempt: 1, Kind: wire.TurnTeamUpdate, Note: "The team finished.", Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Lane: wire.LaneAssistant} |
| 326 | r.must(r.s.db.G.Create(&update).Error) |
| 327 | r.must(r.tx(func(t *txn) error { return t.dispatch(&update) })) |
| 328 | if m := r.lastFrame(); m.Kind != wire.TurnTeamUpdate || m.Earlier != nil || m.EarlierMore != 0 { |
| 329 | t.Fatalf("team_update frame %+v", m) |
| 330 | } |
| 331 | if _, _, err := r.s.Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", IdempotencyKey: "k1"}); err != nil { |
| 332 | t.Fatal(err) |
| 333 | } |
| 334 | if m := r.lastFrame(); m.Lane != wire.LaneCoordinator || m.Earlier != nil { |
| 335 | t.Fatalf("coordinator frame %+v", m) |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | // TestFilesOnlyText: one files-only message reaches the model as |
| 340 | // "(files only, no words)", as it already did among several messages. It |
| 341 | // is so in every lane: the Coordinator's single files-only message went as |
| 342 | // empty text before. |
| 343 | func TestFilesOnlyText(t *testing.T) { |
| 344 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 345 | a := r.upload(hkOwner, "a.md", "# a") |
| 346 | if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{a}, IdempotencyKey: "k1"}); err != nil { |
| 347 | t.Fatal(err) |
| 348 | } |
| 349 | if m := r.lastFrame(); !strings.HasPrefix(m.Text, filesOnly) || len(m.PersonText) != 1 || m.PersonText[0] != "" { |
| 350 | t.Fatalf("assistant text %q, person %q", m.Text, m.PersonText) |
| 351 | } |
| 352 | b := r.upload(hkOwner, "b.md", "# b") |
| 353 | if _, _, err := r.s.Send(r.ctx, hkOwner, wire.SendMessage{Attachments: []string{b}, IdempotencyKey: "k2"}); err != nil { |
| 354 | t.Fatal(err) |
| 355 | } |
| 356 | if m := r.lastFrame(); m.Lane != wire.LaneCoordinator || !strings.HasPrefix(m.Text, filesOnly+"\n\n") { |
| 357 | t.Fatalf("coordinator text %q", m.Text) |
| 358 | } |
| 359 | if got := turnText([]string{"hi"}, [][]string{{"a.md"}}); got != "hi" { |
| 360 | t.Fatalf("words with files %q", got) |
| 361 | } |
| 362 | if got := turnText([]string{""}, [][]string{nil}); got != "" { |
| 363 | t.Fatalf("no words and no files %q", got) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // TestFrameTailGivesWayBeforeEarlier (review S1): in a long conversation |
| 368 | // whose tail is far over a frame, the tail is shortened and every earlier |
| 369 | // file stays, with their paths; nothing is counted as left out. (They |
| 370 | // give way only to the turn's own messages, which batchRoom keeps well |
| 371 | // inside a frame.) |
| 372 | func TestFrameTailGivesWayBeforeEarlier(t *testing.T) { |
| 373 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 374 | var files []string |
| 375 | for i := range 4 { |
| 376 | ids := r.past(wire.LaneAssistant, "the files", r.now.Add(-time.Duration(48-i)*time.Hour), "1.md", "2.md", "3.md", "4.md", "5.md") |
| 377 | files = append(ids, files...) |
| 378 | } |
| 379 | long := strings.Repeat("word ", (wire.MaxMessageBytes-64)/5) |
| 380 | for i := range wire.MaxTailMessages { |
| 381 | r.past(wire.LaneAssistant, long, r.now.Add(-time.Hour+time.Duration(i)*time.Second)) |
| 382 | } |
| 383 | if _, _, err := r.s.Lane(wire.LaneAssistant).Send(r.ctx, hkOwner, wire.SendMessage{Text: "hello", IdempotencyKey: "k1"}); err != nil { |
| 384 | t.Fatal(err) |
| 385 | } |
| 386 | m := r.lastFrame() |
| 387 | raw, _ := json.Marshal(m) |
| 388 | if len(m.Earlier) != wire.MaxEarlierFiles || m.EarlierMore != 0 || len(raw) > frameRoom || len(m.Tail) == 0 || len(m.Tail) >= wire.MaxTailMessages { |
| 389 | t.Fatalf("earlier %d (+%d), tail %d, %d bytes", len(m.Earlier), m.EarlierMore, len(m.Tail), len(raw)) |
| 390 | } |
| 391 | if len(files) != wire.MaxEarlierFiles { |
| 392 | t.Fatalf("%d files made", len(files)) |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | // TestFenceAssistantFiles (A6): a primary connecting below 32 fails its |
| 397 | // person's Assistant turns in flight that carry files (runner_too_old), |
| 398 | // and acks their message and attachment commands, so the older runner |
| 399 | // gets neither. Other turns go on. At 32, or from a worker, nothing |
| 400 | // changes. |
| 401 | func TestFenceAssistantFiles(t *testing.T) { |
| 402 | setup := func(t *testing.T) (*hkRig, wire.Sent, wire.Sent) { |
| 403 | r := filesRig(t, wire.ProtocolAssistantFiles) |
| 404 | lane := r.s.Lane(wire.LaneAssistant) |
| 405 | a, b := r.upload(hkOwner, "a.md", "# a"), r.upload(hkOwner, "b.md", "# b") |
| 406 | withFiles, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "read these", Attachments: []string{a, b}, IdempotencyKey: "k1"}) |
| 407 | r.must(err) |
| 408 | words, _, err := lane.Send(r.ctx, hkOwner, wire.SendMessage{Text: "and hello", IdempotencyKey: "k2"}) |
| 409 | r.must(err) |
| 410 | return r, withFiles, words |
| 411 | } |
| 412 | unacked := func(r *hkRig, kind string) int64 { |
| 413 | return r.count("SELECT count(*) FROM runner_commands WHERE kind = ? AND acked_at IS NULL", kind) |
| 414 | } |
| 415 | connect := func(r *hkRig, protocol int, role string) { |
| 416 | r.must(r.tx(func(t *txn) error { |
| 417 | return t.fenceLanes(Lease{Runner: RunnerPrincipal{Person: hkOwner, RunnerID: "RUNNER1"}, Protocol: protocol, Role: role}) |
| 418 | })) |
| 419 | } |
| 420 | state := func(r *hkRig, id string) turnRecord { |
| 421 | var k turnRecord |
| 422 | r.must(r.s.db.G.Where("id = ?", id).First(&k).Error) |
| 423 | return k |
| 424 | } |
| 425 | |
| 426 | r, withFiles, words := setup(t) |
| 427 | if unacked(r, wire.FrameAttachment) != 2 || unacked(r, wire.FrameMessage) != 1 { |
| 428 | t.Fatalf("before: %d chunks, %d messages", unacked(r, wire.FrameAttachment), unacked(r, wire.FrameMessage)) |
| 429 | } |
| 430 | connect(r, wire.Protocol32, wire.RolePrimary) |
| 431 | if k := state(r, withFiles.Turn.ID); k.State != wire.TurnFailed || k.Reason != reasonRunnerTooOld { |
| 432 | t.Fatalf("the turn with files %s %s", k.State, k.Reason) |
| 433 | } |
| 434 | if n := unacked(r, wire.FrameAttachment); n != 0 { |
| 435 | t.Fatalf("%d attachment commands still waiting", n) |
| 436 | } |
| 437 | if k := state(r, words.Turn.ID); !slices.Contains(wire.InFlight, k.State) || !k.Dispatched { |
| 438 | t.Fatalf("the turn with words %s dispatched %v", k.State, k.Dispatched) |
| 439 | } |
| 440 | if m := r.lastFrame(); m.TurnID != words.Turn.ID || unacked(r, wire.FrameMessage) != 1 { |
| 441 | t.Fatalf("waiting message %+v", m) |
| 442 | } |
| 443 | |
| 444 | for name, tc := range map[string]struct { |
| 445 | protocol int |
| 446 | role string |
| 447 | }{"at 33": {wire.ProtocolAssistantFiles, wire.RolePrimary}, "a worker at 32": {wire.Protocol32, wire.RoleWorker}} { |
| 448 | t.Run(name, func(t *testing.T) { |
| 449 | r, withFiles, words := setup(t) |
| 450 | connect(r, tc.protocol, tc.role) |
| 451 | if state(r, withFiles.Turn.ID).State == wire.TurnFailed || state(r, words.Turn.ID).State == wire.TurnFailed || unacked(r, wire.FrameAttachment) != 2 { |
| 452 | t.Fatal("a turn was fenced") |
| 453 | } |
| 454 | }) |
| 455 | } |
| 456 | } |
| 457 | |