Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions internal/coord/analyse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
58 changes: 58 additions & 0 deletions internal/coord/connections_test.go
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 10 additions & 4 deletions internal/coord/jobs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -102,25 +107,26 @@ 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)
}
}

// 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.
Expand Down
28 changes: 28 additions & 0 deletions internal/coord/jobs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions internal/coord/notes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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:]
}
Expand Down
Loading