| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "strings" |
| 7 | "sync/atomic" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | access "amadan.net/oficina/agent-access.git" |
| 12 | "github.com/google/uuid" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | func TestAgentNoteConcurrentRetryWaitsForIndexAcknowledgement(t *testing.T) { |
| 17 | f, p := linkedAgentFixture(t) |
| 18 | active := true |
| 19 | mountAgentFixture(t, f, &p, &active) |
| 20 | id, err := f.app.store.Ingest(t.Context(), IngestSpec{Source: "paste", Key: "ack", Title: "before", Body: "before"}) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | paused := make(chan struct{}) |
| 25 | release := make(chan struct{}) |
| 26 | var once atomic.Bool |
| 27 | if err := f.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:index-ack", func(tx *gorm.DB) { |
| 28 | if strings.HasPrefix(tx.Statement.SQL.String(), "UPDATE memoria_agent_note_updates SET indexed=1") && once.CompareAndSwap(false, true) { |
| 29 | close(paused) |
| 30 | <-release |
| 31 | } |
| 32 | }); err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | defer f.app.db.G.Callback().Raw().Remove("test:index-ack") |
| 36 | replayAdmitted := make(chan struct{}) |
| 37 | var calls atomic.Int32 |
| 38 | h := http.NewServeMux() |
| 39 | if err := f.app.mountAgentAccess(h, f.app.agentIssuer, "acme", access.VerifyFunc(func(context.Context, string) (access.Principal, error) { |
| 40 | if calls.Add(1) == 4 { |
| 41 | close(replayAdmitted) |
| 42 | } |
| 43 | return p, nil |
| 44 | })); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | input := noteUpdateJSON(id, 1, uuid.NewString(), "after", "after") |
| 48 | result := make(chan string, 2) |
| 49 | run := func() { |
| 50 | w := agentCall(h, "notes_update", input) |
| 51 | if w.Code != 200 { |
| 52 | t.Errorf("update %d: %s", w.Code, w.Body.String()) |
| 53 | } |
| 54 | result <- w.Body.String() |
| 55 | } |
| 56 | go run() |
| 57 | select { |
| 58 | case <-paused: |
| 59 | case <-time.After(3 * time.Second): |
| 60 | t.Fatal("index acknowledgement not reached") |
| 61 | } |
| 62 | go run() |
| 63 | select { |
| 64 | case <-replayAdmitted: |
| 65 | case <-time.After(3 * time.Second): |
| 66 | close(release) |
| 67 | t.Fatal("replay not admitted") |
| 68 | } |
| 69 | select { |
| 70 | case body := <-result: |
| 71 | close(release) |
| 72 | <-result |
| 73 | t.Fatal("replay observed unfinished acknowledgement", body) |
| 74 | case <-time.After(250 * time.Millisecond): |
| 75 | } |
| 76 | close(release) |
| 77 | first, second := <-result, <-result |
| 78 | if first != second || !strings.Contains(first, `"indexed":true`) { |
| 79 | t.Fatal("acknowledgement changed", first, second) |
| 80 | } |
| 81 | } |
| 82 | |