diff --git a/internal/coord/analyse.go b/internal/coord/analyse.go index f5c132a..9b61aaa 100644 --- a/internal/coord/analyse.go +++ b/internal/coord/analyse.go @@ -68,9 +68,10 @@ func (c *Coordinator) Analyse(sessionID, target, question string) (*Job, error) prompt := fmt.Sprintf(reviewPrompt, found.Name, found.Title, from, w.Base, w.Stat, w.Patch, question) + id, seq := newJobID() job := &Job{ - ID: newJobID(), From: sessionID, Subject: found.Name, - State: JobRunning, Started: time.Now(), + ID: id, From: sessionID, Subject: found.Name, + State: JobRunning, Started: time.Now(), seq: seq, } c.mu.Lock() c.jobs[job.ID] = job diff --git a/internal/coord/connections_test.go b/internal/coord/connections_test.go index 7d7c192..9803759 100644 --- a/internal/coord/connections_test.go +++ b/internal/coord/connections_test.go @@ -1,10 +1,13 @@ package coord import ( + "encoding/json" + "fmt" "os" "path/filepath" "strings" "testing" + "time" ) // connectedPair registers one session on each of two projects and links them. @@ -198,6 +201,61 @@ func TestNotesFromAConnectedSessionAreVisible(t *testing.T) { } } +// TestNotesWithOneTimeKeepTheOrderWritten: when a connected log is merged in, +// a log's notes that read the same clock value still come back in the order +// they were written. Two back-to-back time.Now calls can return the same time, +// and an unstable sort of the merged notes by At shuffled such notes. +func TestNotesWithOneTimeKeepTheOrderWritten(t *testing.T) { + dir, head := worktreeSession(t) + c := start(t) + connectedPair(t, c, dir, head) + + at := time.Now() + writeLog := func(projectID, session string, notes []Note) { + t.Helper() + var log []byte + for _, n := range notes { + n.Session = session + line, err := json.Marshal(n) + if err != nil { + t.Fatal(err) + } + log = append(append(log, line...), '\n') + } + if err := os.WriteFile(c.notesPath(projectID), log, 0o644); err != nil { + t.Fatal(err) + } + } + var mine, theirs []Note + for i := range maxNotes - 10 { + mine = append(mine, Note{At: at, Text: fmt.Sprint(i)}) + } + // Theirs fall either side of mine, so the merged notes arrive unsorted. + for i := range 10 { + theirs = append(theirs, Note{At: at.Add(time.Duration(i%2*2-1) * time.Second), Text: "theirs"}) + } + writeLog("p1", "scheming-hawk-jhgk", mine) + writeLog("p2", "wily-crane-bbbb", theirs) + + notes, err := c.Notes("me") + if err != nil { + t.Fatal(err) + } + next := 0 + for _, n := range notes { + if n.Text == "theirs" { + continue + } + if n.Text != fmt.Sprint(next) { + t.Fatalf("got note %q where %d was due: notes with one time came back out of order", n.Text, next) + } + next++ + } + if next != len(mine) { + t.Errorf("read %d of my %d notes", next, len(mine)) + } +} + func TestNotesOfAStrangerOnThatProjectStayHidden(t *testing.T) { dir, head := worktreeSession(t) c := start(t) diff --git a/internal/coord/jobs.go b/internal/coord/jobs.go index b6ca392..8774610 100644 --- a/internal/coord/jobs.go +++ b/internal/coord/jobs.go @@ -57,6 +57,11 @@ type Job struct { Cost float64 Tokens agent.Tokens Err string + + // seq is the number the ID was made from, and orders a session's jobs for + // trimJobs. Started cannot: two jobs started back to back can read the + // same clock value. + seq int } // Analysis returns a job the caller started. Jobs are private to the session @@ -102,7 +107,7 @@ func (c *Coordinator) trimJobs(sessionID string) { if len(mine) <= maxJobs { return } - sort.Slice(mine, func(i, j int) bool { return mine[i].Started.Before(mine[j].Started) }) + sort.Slice(mine, func(i, j int) bool { return mine[i].seq < mine[j].seq }) for _, j := range mine[:len(mine)-maxJobs] { delete(c.jobs, j.ID) } @@ -110,17 +115,18 @@ func (c *Coordinator) trimJobs(sessionID string) { // jobSeq numbers analyses. Sequential rather than random: an agent reads an id // back to us, and a short one it can retype is worth more than an unguessable -// one for something scoped to a single session anyway. +// one for something scoped to a single session anyway. The number also orders +// a session's jobs (Job.seq). var jobSeq struct { sync.Mutex n int } -func newJobID() string { +func newJobID() (id string, seq int) { jobSeq.Lock() defer jobSeq.Unlock() jobSeq.n++ - return fmt.Sprintf("a%d", jobSeq.n) + return fmt.Sprintf("a%d", jobSeq.n), jobSeq.n } // Badge is what the sidebar needs to draw a session's analyses. diff --git a/internal/coord/jobs_test.go b/internal/coord/jobs_test.go index 91a6b90..24fdba2 100644 --- a/internal/coord/jobs_test.go +++ b/internal/coord/jobs_test.go @@ -6,6 +6,7 @@ import ( "errors" "os" "path/filepath" + "slices" "strings" "sync" "testing" @@ -202,6 +203,33 @@ func TestJobsAreBounded(t *testing.T) { } } +// TestJobsAreTrimmedInTheOrderStarted: jobs that read the same clock value are +// still trimmed oldest first. Two back-to-back time.Now calls can return the +// same time, so ordering by Started left the survivors to the map's iteration +// order. +func TestJobsAreTrimmedInTheOrderStarted(t *testing.T) { + c := analysable(t, agent.ClaudeRun{}, nil) + at := time.Now() + var made []string + c.mu.Lock() + for range maxJobs + 5 { + id, seq := newJobID() + made = append(made, id) + c.jobs[id] = &Job{ID: id, From: "me", Started: at, seq: seq} + c.trimJobs("me") + } + var kept []string + for _, id := range made { + if c.jobs[id] != nil { + kept = append(kept, id) + } + } + c.mu.Unlock() + if want := made[len(made)-maxJobs:]; !slices.Equal(kept, want) { + t.Errorf("kept %v, want the newest %d: %v", kept, maxJobs, want) + } +} + // TestUnregisterDropsJobsAndSpend matches how claims and the inbox behave: a // session's record goes with the session. func TestUnregisterDropsJobsAndSpend(t *testing.T) { diff --git a/internal/coord/notes.go b/internal/coord/notes.go index ccee118..2a0127f 100644 --- a/internal/coord/notes.go +++ b/internal/coord/notes.go @@ -142,7 +142,7 @@ const maxNotes = 50 // // A note is still written to one log — the writer's own project's — so there is // one write path and a project's log means what it always meant. Only the read -// widens. See connectedNotes for what a connection contributes. +// widens, as connectedNotes shows. Notes of one time keep their log's order. func (c *Coordinator) Notes(sessionID string) ([]Note, error) { c.mu.Lock() me, ok := c.sessions[sessionID] @@ -164,7 +164,7 @@ func (c *Coordinator) Notes(sessionID string) ([]Note, error) { return nil, err } out = append(out, shared...) - sort.Slice(out, func(i, j int) bool { return out[i].At.Before(out[j].At) }) + sort.SliceStable(out, func(i, j int) bool { return out[i].At.Before(out[j].At) }) if len(out) > maxNotes { out = out[len(out)-maxNotes:] }