From db5e9c19bb18486aabbd0893334887fef7f8b425 Mon Sep 17 00:00:00 2001 From: tdwd <111124579+tdwd@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:05:21 +0200 Subject: [PATCH 1/2] Trim a session's analyses by the order they started, not their clock trimJobs sorted a session's jobs by Started to drop the oldest. Two time.Now calls back to back can return the same time, and when two jobs did, the sort left which one survived to the map's iteration order. TestJobsAreBounded then failed now and then, finding the oldest job still there. Each job now keeps the number its ID is made from, and trimJobs sorts by that. The new test gives every job the same Started and checks that the newest maxJobs survive. --- internal/coord/analyse.go | 5 +++-- internal/coord/jobs.go | 14 ++++++++++---- internal/coord/jobs_test.go | 28 ++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) 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/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) { From 4b280c32c99537ad420f6501eec51d5f0ac8e505 Mon Sep 17 00:00:00 2001 From: tdwd <111124579+tdwd@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:05:21 +0200 Subject: [PATCH 2/2] Keep a log's order for notes that share a time Notes merges the session's log with its connected sessions' logs and sorts by At. sort.Slice is not stable, so a log's notes that read the same clock value could come back in a different order from the one they were written in, once a connected log was merged in. sort.SliceStable keeps each log's own order for those. --- internal/coord/connections_test.go | 58 ++++++++++++++++++++++++++++++ internal/coord/notes.go | 4 +-- 2 files changed, 60 insertions(+), 2 deletions(-) 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/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:] }