oficina / equipo Public

perf: bound runner polling and task view notifications

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 53b4c57ed706f85c9dc42264c5fef9c32fc4b767 parent 8633834
12 files changed, +406 −215
  • internal/equipo/copy.go +2 −0
  • internal/equipo/execution.go +1 −0
  • internal/equipo/live.go +82 −182
  • internal/equipo/live_changes.go +98 −0
  • internal/equipo/runner_execution.go +38 −22
  • internal/equipo/store.go +10 −2
  • internal/equipo/task_counts.go +66 −0
  • internal/equipo/task_page_handlers.go +2 −5
  • internal/equipo/task_views.go +2 −2
  • internal/equipo/team/final_observer_test.go +28 −0
  • internal/equipo/team/store.go +11 −2
  • internal/equipotest/final_read_cost_test.go +66 −0
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index f9c17214..522ccdda 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -7,6 +7,8 @@ import "amadan.net/oficina/equipo/internal/runner"
// COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules).
// App-owned runtime strings belong here, including boot diagnostics.
const (
+ // COPY REVIEW REQUIRED
+ copyObserverFailure = "The live update could not be sent. The change was saved."
copyDecisionOwnerAssigned = "Reassign this person's project decisions before removing them."
copyBindingInUse = "Another project uses this repository and app. Choose a different pair."
copyLastOwner = "Add another owner before changing or removing the last owner."
diff --git a/internal/equipo/execution.go b/internal/equipo/execution.go
index 94bbcc7b..64a0685b 100644
--- a/internal/equipo/execution.go
+++ b/internal/equipo/execution.go
@@ -27,6 +27,7 @@ func (s *Store) AttachExecution(ctx context.Context, path string, options team.O
return nil, ErrConflict
}
options.ObserveWrite = s.observeWrite
+ options.ObserverFailed = observerFailed
original := options.Provenance
options.Provenance = s.runnerProvenance(original)
core, err := team.OpenShared(ctx, s.db.Writer(), path, options)
diff --git a/internal/equipo/live.go b/internal/equipo/live.go
index 4eafc507..e214bf27 100644
--- a/internal/equipo/live.go
+++ b/internal/equipo/live.go
@@ -8,12 +8,12 @@ import (
"fmt"
"net/http"
"sort"
- "strings"
"time"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/rastrillo/rastrillo/auth"
"amadan.net/rastrillo/rastrillo/live"
+ "gorm.io/gorm"
)
type JobNotifier interface {
@@ -73,47 +73,55 @@ func CloseLive(h http.Handler) {
}
}
-type liveState struct {
- values map[string][32]byte
- deadlines map[string][]time.Time
-}
+type liveState struct{ deadlines map[string][]time.Time }
-// Snapshot inside the write transaction. This also covers core writes made
-// directly by supervision, including recovery and evidence registration.
func (s *Store) observeWrite(ctx context.Context, tx *sql.Tx) (team.CommitObserver, error) {
if s.notifier == nil {
return nil, nil
}
- before, err := s.liveState(ctx, tx)
- if err != nil {
+ if err := installLiveChanges(ctx, tx); err != nil {
return nil, err
}
return func(ctx context.Context, tx *sql.Tx) (func(), error) {
- after, err := s.liveState(ctx, tx)
+ rows, err := tx.QueryContext(ctx, `SELECT c.team,c.job FROM equipo_live_changes c JOIN teams t ON t.id=c.team WHERE c.job=0 OR EXISTS(SELECT 1 FROM jobs j WHERE j.id=c.job AND j.account=c.team)`)
if err != nil {
return nil, err
}
- changed := map[string]bool{}
- for k, v := range after.values {
- if old, ok := before.values[k]; !ok || old != v {
- changed[k] = true
+ touched := map[string][]JobID{}
+ topics := map[string]bool{}
+ for rows.Next() {
+ var teamID string
+ var job JobID
+ if err = rows.Scan(&teamID, &job); err != nil {
+ break
}
+ touched[teamID] = append(touched[teamID], job)
+ topics[jobTopic(teamID, job)] = true
+ topics[jobTopic(teamID, 0)] = true
+ }
+ if err == nil {
+ err = rows.Err()
+ }
+ rows.Close()
+ if err != nil {
+ return nil, err
}
- for k := range before.values {
- if _, ok := after.values[k]; !ok {
- changed[k] = true
+ st := liveState{deadlines: map[string][]time.Time{}}
+ for teamID, ids := range touched {
+ if err := s.liveDeadlines(ctx, tx, &st, teamID, ids); err != nil {
+ return nil, err
}
}
- topics := make([]string, 0, len(changed))
- for k := range changed {
- topics = append(topics, k)
+ keys := make([]string, 0, len(topics))
+ for topic := range topics {
+ keys = append(keys, topic)
}
- sort.Strings(topics)
+ sort.Strings(keys)
return func() {
- if len(topics) > 0 {
- s.notifier.Notify(topics...)
+ if len(keys) > 0 {
+ s.notifier.Notify(keys...)
}
- s.scheduleState(after)
+ s.scheduleState(st)
}, nil
}, nil
}
@@ -127,197 +135,89 @@ func (s *Store) scheduleState(st liveState) {
}
}
func (s *Store) restoreLiveSchedules(ctx context.Context) error {
- tx, err := s.db.Writer().BeginTx(ctx, nil)
- if err != nil {
- return err
- }
- defer tx.Rollback()
- st, err := s.liveState(ctx, tx)
- if err != nil {
- return err
- }
- s.scheduleState(st)
- return nil
-}
-
-func snapshotRows(ctx context.Context, tx *sql.Tx, query string, args ...any) ([]byte, error) {
- rows, err := tx.QueryContext(ctx, query, args...)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- cols, err := rows.Columns()
- if err != nil {
- return nil, err
- }
- out := [][]any{}
- for rows.Next() {
- values := make([]any, len(cols))
- ptr := make([]any, len(cols))
- for i := range values {
- ptr[i] = &values[i]
+ return s.db.G.WithContext(ctx).Transaction(func(g *gorm.DB) error {
+ tx, err := executionTx(g)
+ if err != nil {
+ return err
}
- if err = rows.Scan(ptr...); err != nil {
- return nil, err
+ var teamID string
+ if err := tx.QueryRowContext(ctx, "SELECT id FROM teams ORDER BY id LIMIT 1").Scan(&teamID); err == sql.ErrNoRows {
+ return nil
+ } else if err != nil {
+ return err
}
- out = append(out, values)
- }
- if err = rows.Err(); err != nil {
- return nil, err
- }
- return json.Marshal(out)
-}
-func (s *Store) liveState(ctx context.Context, tx *sql.Tx) (liveState, error) {
- st := liveState{values: map[string][32]byte{}, deadlines: map[string][]time.Time{}}
- var teamID string
- if err := tx.QueryRowContext(ctx, "SELECT id FROM teams ORDER BY id LIMIT 1").Scan(&teamID); err == sql.ErrNoRows {
- return st, nil
- } else if err != nil {
- return st, err
- }
- // These records are instance-wide inputs to job eligibility. Their changes
- // can affect every job, but never a job stored under another team's ID.
- common := []byte{}
- for _, query := range []string{"SELECT * FROM members ORDER BY address", "SELECT * FROM projects ORDER BY id", "SELECT * FROM decision_owners ORDER BY project_id,decision", "SELECT * FROM connections WHERE runner_id IN (SELECT id FROM runners WHERE instance_id=?) ORDER BY id", "SELECT * FROM connection_choices ORDER BY person,project_id", "SELECT * FROM isolation_acknowledgements WHERE connection_id IN (SELECT connections.id FROM connections JOIN runners ON runners.id=connections.runner_id WHERE runners.instance_id=?) ORDER BY id", "SELECT * FROM runners WHERE instance_id=? ORDER BY id", "SELECT id,runner_id,expires_at,rotated_at,revoked_at FROM runner_credentials WHERE instance_id=? ORDER BY id", "SELECT runner_rotations.* FROM runner_rotations JOIN runners ON runners.id=runner_rotations.runner_id WHERE runners.instance_id=? ORDER BY runner_rotations.runner_id", "SELECT * FROM budget_records WHERE team_id=? ORDER BY team_id", "SELECT * FROM specialists ORDER BY key", "SELECT admission_paused,quarantine,quarantine_why,recovery_revision,release_required FROM service ORDER BY id"} {
- var args []any
- if strings.Contains(query, "?") {
- args = []any{teamID}
+ st := liveState{deadlines: map[string][]time.Time{}}
+ if err := s.liveDeadlines(ctx, tx, &st, teamID, nil); err != nil {
+ return err
}
- b, err := snapshotRows(ctx, tx, query, args...)
+ s.scheduleState(st)
+ return nil
+ })
+}
+func (s *Store) liveDeadlines(ctx context.Context, tx *sql.Tx, st *liveState, teamID string, ids []JobID) error {
+ if ids == nil {
+ rows, err := tx.QueryContext(ctx, "SELECT id FROM jobs WHERE account=? AND state NOT IN ('succeeded','failed','cancelled')", teamID)
if err != nil {
- return st, err
- }
- common = append(common, b...)
- }
- collection := append([]byte{}, common...)
- rows, err := tx.QueryContext(ctx, "SELECT id,job_id FROM tasks WHERE team_id=? ORDER BY id", teamID)
- if err != nil {
- return st, err
- }
- type pair struct {
- id string
- job JobID
- }
- var tasks []pair
- for rows.Next() {
- var p pair
- if err = rows.Scan(&p.id, &p.job); err != nil {
- rows.Close()
- return st, err
+ return err
}
- tasks = append(tasks, p)
- }
- err = rows.Err()
- rows.Close()
- if err != nil {
- return st, err
- }
- for _, p := range tasks {
- data := append([]byte{}, common...)
- for _, query := range []string{"SELECT * FROM tasks WHERE id=?", "SELECT * FROM task_outboxes WHERE task_id=?", "SELECT * FROM questions WHERE task_id=? ORDER BY id", "SELECT * FROM runner_assignments WHERE task_id=? ORDER BY id", "SELECT runner_cleanups.* FROM runner_cleanups JOIN runner_assignments ON runner_assignments.id=runner_cleanups.assignment_id WHERE runner_assignments.task_id=? ORDER BY runner_cleanups.id", "SELECT o.* FROM runner_observations o JOIN runner_assignments a ON a.id=o.assignment_id WHERE a.task_id=? ORDER BY o.assignment_id,o.request_id", "SELECT e.* FROM runner_events e JOIN runner_assignments a ON a.id=e.assignment_id WHERE a.task_id=? ORDER BY e.assignment_id,e.sequence"} {
- b, err := snapshotRows(ctx, tx, query, p.id)
- if err != nil {
- return st, err
+ for rows.Next() {
+ var id JobID
+ if err = rows.Scan(&id); err != nil {
+ break
}
- data = append(data, b...)
+ ids = append(ids, id)
}
- if p.job != 0 {
- var account string
- if err = tx.QueryRowContext(ctx, "SELECT account FROM jobs WHERE id=?", p.job).Scan(&account); err != nil {
- return st, err
- }
- if account != teamID {
- return st, ErrForbidden
- }
- for _, query := range []string{"SELECT * FROM jobs WHERE id=?", "SELECT * FROM steps WHERE job_id=? ORDER BY id", "SELECT * FROM attempts WHERE job_id=? ORDER BY id", "SELECT * FROM events WHERE job_id=? ORDER BY seq", "SELECT id,job_id,step_id,attempt_id,fence,role,hash,provenance FROM artifacts WHERE job_id=? ORDER BY id", "SELECT * FROM reservations WHERE job_id=? ORDER BY id", "SELECT * FROM time_reservations WHERE job_id=? ORDER BY attempt_id", "SELECT * FROM actions WHERE job_id=? ORDER BY id"} {
- b, err := snapshotRows(ctx, tx, query, p.job)
- if err != nil {
- return st, err
- }
- data = append(data, b...)
- }
- st.values[jobTopic(teamID, p.job)] = sha256.Sum256(data)
+ if err == nil {
+ err = rows.Err()
}
- collection = append(collection, data...)
- }
-
- // A job can commit before its task link (the preparation outbox retry boundary).
- rows, err = tx.QueryContext(ctx, "SELECT id FROM jobs WHERE account=? AND id NOT IN (SELECT job_id FROM tasks WHERE team_id=?) ORDER BY id", teamID, teamID)
- if err != nil {
- return st, err
- }
- var orphans []JobID
- for rows.Next() {
- var id JobID
- if err = rows.Scan(&id); err != nil {
- rows.Close()
- return st, err
- }
- orphans = append(orphans, id)
- }
- err = rows.Err()
- rows.Close()
- if err != nil {
- return st, err
- }
- for _, id := range orphans {
- data := append([]byte{}, common...)
- for _, query := range []string{"SELECT * FROM jobs WHERE id=?", "SELECT * FROM steps WHERE job_id=? ORDER BY id", "SELECT * FROM attempts WHERE job_id=? ORDER BY id", "SELECT * FROM events WHERE job_id=? ORDER BY seq", "SELECT id,job_id,step_id,attempt_id,fence,role,hash,provenance FROM artifacts WHERE job_id=? ORDER BY id", "SELECT * FROM reservations WHERE job_id=? ORDER BY id", "SELECT * FROM time_reservations WHERE job_id=? ORDER BY attempt_id", "SELECT * FROM actions WHERE job_id=? ORDER BY id"} {
- b, e := snapshotRows(ctx, tx, query, id)
- if e != nil {
- return st, e
- }
- data = append(data, b...)
+ rows.Close()
+ if err != nil {
+ return err
}
- st.values[jobTopic(teamID, id)] = sha256.Sum256(data)
- collection = append(collection, data...)
}
- st.values[jobTopic(teamID, 0)] = sha256.Sum256(collection)
- now := time.Now().UTC()
- st.deadlines[jobTopic(teamID, 0)] = []time.Time{weekStart(now).AddDate(0, 0, 7)}
-
+ collection := jobTopic(teamID, 0)
+ st.deadlines[collection] = append(st.deadlines[collection], weekStart(time.Now()).AddDate(0, 0, 7))
for _, schedule := range []struct {
query string
shift time.Duration
- all bool
}{
- {"SELECT tasks.job_id,questions.expires_at FROM questions JOIN tasks ON tasks.id=questions.task_id WHERE questions.state='pending' AND tasks.team_id=?", 0, false},
- {"SELECT 0,connections.last_seen FROM connections JOIN runners ON runners.id=connections.runner_id WHERE runners.instance_id=?", 90 * time.Second, true},
- {"SELECT job_id,lease_deadline FROM runner_assignments WHERE state='claimed' AND team_id=?", 0, false},
- {"SELECT attempts.job_id,attempts.lease_deadline FROM attempts JOIN jobs ON jobs.id=attempts.job_id WHERE attempts.containment='pending' AND jobs.account=?", 0, false},
+ {"SELECT t.job_id,q.expires_at FROM questions q JOIN tasks t ON t.id=q.task_id WHERE q.state='pending' AND t.team_id=?", 0},
+ {"SELECT 0,c.last_seen FROM connections c JOIN runners r ON r.id=c.runner_id WHERE r.instance_id=?", 90 * time.Second},
+ {"SELECT job_id,lease_deadline FROM runner_assignments WHERE state='claimed' AND team_id=?", 0},
+ {"SELECT a.job_id,a.lease_deadline FROM attempts a JOIN jobs j ON j.id=a.job_id WHERE a.containment='pending' AND j.account=?", 0},
} {
rows, err := tx.QueryContext(ctx, schedule.query, teamID)
if err != nil {
- return st, err
+ return err
}
for rows.Next() {
var id JobID
var raw any
if err = rows.Scan(&id, &raw); err != nil {
- rows.Close()
- return st, err
+ break
}
at := readTime(raw).Add(schedule.shift)
- st.deadlines[jobTopic(teamID, 0)] = append(st.deadlines[jobTopic(teamID, 0)], at)
- if schedule.all {
- for topic := range st.values {
- if topic != jobTopic(teamID, 0) {
+ st.deadlines[collection] = append(st.deadlines[collection], at)
+ if id != 0 {
+ st.deadlines[jobTopic(teamID, id)] = append(st.deadlines[jobTopic(teamID, id)], at)
+ } else {
+ for _, job := range ids {
+ if job != 0 {
+ topic := jobTopic(teamID, job)
st.deadlines[topic] = append(st.deadlines[topic], at)
}
}
- } else if id != 0 {
- topic := jobTopic(teamID, id)
- st.deadlines[topic] = append(st.deadlines[topic], at)
}
}
- err = rows.Err()
+ if err == nil {
+ err = rows.Err()
+ }
rows.Close()
if err != nil {
- return st, err
+ return err
}
}
-
- return st, nil
+ return nil
}
func readTime(v any) time.Time {
if t, ok := v.(time.Time); ok {
diff --git a/internal/equipo/live_changes.go b/internal/equipo/live_changes.go
new file mode 100644
index 00000000..e20cbeee
--- /dev/null
+++ b/internal/equipo/live_changes.go
@@ -0,0 +1,98 @@
+package equipo
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "strings"
+)
+
+// Temporary triggers collect changed associations on the writer connection.
+// They are transactional and never become part of the application schema.
+func installLiveChanges(ctx context.Context, tx *sql.Tx) error {
+ var installed int
+ if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_temp_master WHERE name='equipo_live_changes'`).Scan(&installed); err != nil {
+ return err
+ }
+ if installed != 0 {
+ _, err := tx.ExecContext(ctx, `DELETE FROM equipo_live_changes`)
+ return err
+ }
+ if _, err := tx.ExecContext(ctx, `CREATE TEMP TABLE equipo_live_changes(team TEXT NOT NULL,job INTEGER NOT NULL,PRIMARY KEY(team,job))`); err != nil {
+ return err
+ }
+ tables := map[string]string{
+ "tasks": "SELECT $team_id,$job_id",
+ "task_outboxes": "SELECT team_id,job_id FROM tasks WHERE id=$task_id",
+ "questions": "SELECT team_id,job_id FROM tasks WHERE id=$task_id",
+ "runner_assignments": "SELECT $team_id,$job_id",
+ "runner_cleanups": "SELECT team_id,job_id FROM runner_assignments WHERE id=$assignment_id",
+ "runner_observations": "SELECT team_id,job_id FROM runner_assignments WHERE id=$assignment_id",
+ "runner_events": "SELECT team_id,job_id FROM runner_assignments WHERE id=$assignment_id",
+ "runner_rotations": "SELECT team_id,job_id FROM runner_assignments WHERE runner_id=$runner_id AND (state!='contained' OR id=$assignment_id)",
+ "jobs": "SELECT $account,$id",
+ "steps": "SELECT account,id FROM jobs WHERE id=$job_id",
+ "attempts": "SELECT account,id FROM jobs WHERE id=$job_id",
+ "events": "SELECT account,id FROM jobs WHERE id=$job_id",
+ "actions": "SELECT account,id FROM jobs WHERE id=$job_id",
+ "artifacts": "SELECT account,id FROM jobs WHERE id=$job_id",
+ "reservations": "SELECT $account,$job_id",
+ "time_reservations": "SELECT $account,$job_id",
+ "connections": "SELECT team_id,job_id FROM runner_assignments WHERE runner_id=$runner_id AND state!='contained' UNION SELECT instance_id,0 FROM runners WHERE id=$runner_id",
+ "isolation_acknowledgements": "SELECT a.team_id,a.job_id FROM runner_assignments a JOIN connections c ON c.runner_id=a.runner_id WHERE c.id=$connection_id AND a.state!='contained' UNION SELECT r.instance_id,0 FROM connections c JOIN runners r ON r.id=c.runner_id WHERE c.id=$connection_id",
+ "runners": "SELECT team_id,job_id FROM runner_assignments WHERE runner_id=$id AND state!='contained' UNION SELECT $instance_id,0",
+ "runner_credentials": "SELECT team_id,job_id FROM runner_assignments WHERE runner_id=$runner_id AND state!='contained' UNION SELECT $instance_id,0",
+ }
+ active := `SELECT id,0 FROM teams UNION SELECT account,id FROM jobs WHERE state NOT IN ('succeeded','failed','cancelled')`
+ for _, table := range []string{"members", "projects", "decision_owners", "connection_choices", "budget_records", "specialists", "service"} {
+ tables[table] = active
+ }
+ for table, selection := range tables {
+ rows, err := tx.QueryContext(ctx, "PRAGMA main.table_info("+table+")")
+ if err != nil {
+ return err
+ }
+ var cols []string
+ for rows.Next() {
+ var cid, notnull, pk int
+ var name, kind string
+ var def any
+ if err = rows.Scan(&cid, &name, &kind, &notnull, &def, &pk); err != nil {
+ break
+ }
+ cols = append(cols, name)
+ }
+ if err == nil {
+ err = rows.Err()
+ }
+ rows.Close()
+ if err != nil {
+ return err
+ }
+ if table == "service" {
+ cols = []string{"admission_paused", "quarantine", "quarantine_why", "recovery_revision", "release_required"}
+ }
+ var changes []string
+ for _, c := range cols {
+ changes = append(changes, "OLD."+c+" IS NOT NEW."+c)
+ }
+ for _, op := range []string{"INSERT", "UPDATE", "DELETE"} {
+ source := "NEW."
+ when := ""
+ if op == "DELETE" {
+ source = "OLD."
+ }
+ if op == "UPDATE" {
+ when = " WHEN " + strings.Join(changes, " OR ")
+ }
+ var statement string
+ // A SELECT without a WHERE needs one to disambiguate SQLite's UPSERT grammar.
+ statement = "INSERT INTO equipo_live_changes SELECT * FROM (" + strings.ReplaceAll(selection, "$", source) + ") WHERE true ON CONFLICT DO NOTHING;"
+ query := fmt.Sprintf("CREATE TEMP TRIGGER equipo_live_%s_%s AFTER %s ON main.%s%s BEGIN %s END", table, op, op, table, when, statement)
+ if _, err := tx.ExecContext(ctx, query); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go
index 570fe372..c917edf9 100644
--- a/internal/equipo/runner_execution.go
+++ b/internal/equipo/runner_execution.go
@@ -360,35 +360,51 @@ func (e *Execution) Poll(ctx context.Context, p RunnerPrincipal, after string) (
defer tick.Stop()
for {
var values []Assignment
- err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ var candidates int64
+ err := e.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(func(tx *gorm.DB) error {
if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
return err
}
- if err := e.Core.AdmissionAvailable(ctx); err != nil {
- return err
- }
- var rows []runnerAssignment
- if err := tx.Where("runner_id=? AND person=? AND state=? AND id>?", p.RunnerID, p.Person, "pending", after).Order("id").Find(&rows).Error; err != nil {
+ var paused, quarantine int
+ if err := tx.Raw("SELECT admission_paused,quarantine FROM service WHERE id=1").Row().Scan(&paused, &quarantine); err != nil {
return storeError(err)
}
- for _, a := range rows {
- value, err := e.assignmentCurrent(ctx, tx, p, a)
- if err != nil {
- if !taskRefusal(err) {
- return err
- }
- if err := taskWait(tx, a.TaskID, "task.wait.setup"); err != nil {
- return err
- }
- if err := tx.Model(&runnerAssignment{}).Where("id=? AND state='pending'", a.ID).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error; err != nil {
- return storeError(err)
+ if paused != 0 || quarantine != 0 {
+ return team.ErrAdmissionPaused
+ }
+ return storeError(tx.Model(&runnerAssignment{}).Where("runner_id=? AND person=? AND state=? AND id>?", p.RunnerID, p.Person, "pending", after).Limit(1).Count(&candidates).Error)
+ }, &sql.TxOptions{ReadOnly: true})
+ if err == nil && candidates > 0 {
+ err = e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ if err := e.Core.AdmissionAvailable(ctx); err != nil {
+ return err
+ }
+ var rows []runnerAssignment
+ if err := tx.Where("runner_id=? AND person=? AND state=? AND id>?", p.RunnerID, p.Person, "pending", after).Order("id").Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ for _, a := range rows {
+ value, err := e.assignmentCurrent(ctx, tx, p, a)
+ if err != nil {
+ if !taskRefusal(err) {
+ return err
+ }
+ if err := taskWait(tx, a.TaskID, "task.wait.setup"); err != nil {
+ return err
+ }
+ if err := tx.Model(&runnerAssignment{}).Where("id=? AND state='pending'", a.ID).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error; err != nil {
+ return storeError(err)
+ }
+ continue
}
- continue
+ values = append(values, value)
}
- values = append(values, value)
- }
- return nil
- })
+ return nil
+ })
+ }
if err != nil {
if errors.Is(err, context.DeadlineExceeded) && parent.Err() == nil {
return []Assignment{}, nil
diff --git a/internal/equipo/store.go b/internal/equipo/store.go
index 457485c7..98d6b394 100644
--- a/internal/equipo/store.go
+++ b/internal/equipo/store.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "log/slog"
"time"
"gorm.io/gorm"
@@ -94,15 +95,20 @@ func (s *Store) write(ctx context.Context, fn func(*gorm.DB) error) error {
}
observer, e := s.observeWrite(ctx, raw)
if e != nil {
- return e
+ observer = nil
+ observerFailed()
}
if e = fn(tx); e != nil {
return e
}
if observer != nil {
notify, e = observer(ctx, raw)
+ if e != nil {
+ notify = nil
+ observerFailed()
+ }
}
- return e
+ return nil
})
if err == nil && notify != nil {
notify()
@@ -117,3 +123,5 @@ func (s *Store) write(ctx context.Context, fn func(*gorm.DB) error) error {
func appendAudit(tx *gorm.DB, actor Actor, kind, recordID string) error {
return storeError(tx.Create(&AuditEvent{Actor: normalizeAddress(actor.Address), Kind: kind, RecordID: recordID, At: time.Now().UTC()}).Error)
}
+
+func observerFailed() { slog.Warn(copyObserverFailure) }
diff --git a/internal/equipo/task_counts.go b/internal/equipo/task_counts.go
new file mode 100644
index 00000000..3c13bec5
--- /dev/null
+++ b/internal/equipo/task_counts.go
@@ -0,0 +1,66 @@
+package equipo
+
+import (
+ "context"
+ "gorm.io/gorm"
+ "time"
+)
+
+func visibleTasks(tx *gorm.DB, teamID string, since time.Time) *gorm.DB {
+ // Unknown finish dates remain visible. Both job and person transitions matter.
+ return tx.Model(&Task{}).Joins("LEFT JOIN jobs visible_job ON visible_job.id=tasks.job_id AND visible_job.account=tasks.team_id").Where("tasks.team_id=?", teamID).Where(`
+ (tasks.state NOT IN ('failed','cancelled','merged') AND COALESCE(visible_job.state,'') NOT IN ('failed','cancelled'))
+ OR MAX(COALESCE(julianday(visible_job.updated_at),0),COALESCE((SELECT MAX(julianday(at)) FROM audit_events WHERE record_id=tasks.id AND kind IN ('task.cancel','task.merge')),0)) IN (0)
+ OR MAX(COALESCE(julianday(visible_job.updated_at),0),COALESCE((SELECT MAX(julianday(at)) FROM audit_events WHERE record_id=tasks.id AND kind IN ('task.cancel','task.merge')),0))>=julianday(?)`, since).Select("tasks.*")
+}
+
+func (s *Store) SpecialistCounts(ctx context.Context, actor Actor) (map[string]SpecialistWorkView, error) {
+ out := map[string]SpecialistWorkView{}
+ err := s.readTeam(ctx, actor, func(tx *gorm.DB, instance Team) error {
+ for _, key := range specialistKeys {
+ v := SpecialistWorkView{CountsKnown: true, UsageKnown: true}
+ if key != "engineering" && key != "review" {
+ out[key] = v
+ continue
+ }
+ caps := []string{"reproduce", "implement"}
+ if key == "review" {
+ caps = []string{"review", "verify"}
+ }
+ var counts struct {
+ Working, Queued, Finished, Waiting int
+ Unknown int64
+ Calls, Input, Output int64
+ }
+ // One row per task before aggregation avoids multiplying usage by attempts.
+ err := tx.Raw(`WITH visible AS (?), classified AS (
+ SELECT t.id,t.job_id,
+ CASE WHEN t.state IN ('failed','cancelled','merged') OR j.state IN ('failed','cancelled') THEN 'finished'
+ WHEN (SELECT count(*) FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='succeeded')=2 THEN 'finished'
+ WHEN EXISTS(SELECT 1 FROM questions q JOIN runner_assignments a ON a.id=q.assignment_id JOIN attempts att ON att.id=a.attempt_id WHERE q.task_id=t.id AND q.state='pending' AND a.state='claimed' AND att.state='active' AND a.fence=att.fence AND a.step_key IN ? AND julianday(a.lease_deadline)>julianday(?) AND julianday(att.lease_deadline)>julianday(?)) THEN 'waiting'
+ WHEN EXISTS(SELECT 1 FROM steps WHERE job_id=t.job_id AND capability IN ? AND state='running') THEN 'working'
+ ELSE 'queued' END bucket
+ FROM visible t LEFT JOIN jobs j ON j.id=t.job_id
+ ) SELECT COALESCE(SUM(bucket='working'),0) working,COALESCE(SUM(bucket='queued'),0) queued,
+ COALESCE(SUM(bucket='finished'),0) finished,COALESCE(SUM(bucket='waiting'),0) waiting
+ FROM classified`, visibleTasks(tx, instance.ID, weekStart(s.runnerClock.Now())), caps, caps, s.runnerClock.Now(), s.runnerClock.Now(), caps).Scan(&counts).Error
+ if err != nil {
+ return storeError(err)
+ }
+ v.Working, v.Queued, v.Finished, v.Waiting = counts.Working, counts.Queued, counts.Finished, counts.Waiting
+ err = tx.Raw(`SELECT COALESCE(SUM(CASE WHEN r.state='open' THEN r.r_calls ELSE r.s_calls END),0) calls,
+ COALESCE(SUM(r.s_input),0) input, COALESCE(SUM(r.s_output),0) output,
+ COALESCE(SUM(r.state='open' OR r.settled_by='unknown'),0) unknown
+ FROM reservations r JOIN steps st ON st.id=r.step_id JOIN (?) t ON t.job_id=r.job_id
+ WHERE st.capability IN ? AND julianday(r.created_at)>=julianday(?)`, visibleTasks(tx, instance.ID, weekStart(s.runnerClock.Now())), caps, weekStart(s.runnerClock.Now())).Scan(&counts).Error
+ if err != nil {
+ return storeError(err)
+ }
+ v.CountedTurns, v.InputTokens, v.OutputTokens = counts.Calls, counts.Input, counts.Output
+ v.UsageKnown = counts.Unknown == 0
+ out[key] = v
+ }
+ return nil
+ })
+ return out, err
+}
diff --git a/internal/equipo/task_page_handlers.go b/internal/equipo/task_page_handlers.go
index b8b12420..28ee7e11 100644
--- a/internal/equipo/task_page_handlers.go
+++ b/internal/equipo/task_page_handlers.go
@@ -19,14 +19,11 @@ func (a *application) fillCounts(r *http.Request, data *pageData) error {
if data.Counts != nil {
return nil
}
- views, err := a.store.Journey(r.Context(), Actor{Address: data.Address})
+ counts, err := a.store.SpecialistCounts(r.Context(), Actor{Address: data.Address})
if err != nil {
return err
}
- data.Counts = map[string]SpecialistWorkView{}
- for _, key := range specialistKeys {
- data.Counts[key] = specialistWork(views, key, a.store.runnerClock.Now())
- }
+ data.Counts = counts
return nil
}
func (a *application) taskList(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go
index 93412103..878201c7 100644
--- a/internal/equipo/task_views.go
+++ b/internal/equipo/task_views.go
@@ -58,7 +58,7 @@ type SpecialistWorkView struct {
}
func (s *Store) readTeam(ctx context.Context, actor Actor, fn func(*gorm.DB, Team) error) error {
- return storeErrorRead(s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(func(tx *gorm.DB) error {
+ return storeErrorRead(s.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(func(tx *gorm.DB) error {
if _, err := currentRunnerMember(tx, actor.Address); err != nil {
return err
}
@@ -101,7 +101,7 @@ func (s *Store) Journey(ctx context.Context, actor Actor) ([]TaskViewData, error
var views []TaskViewData
err := s.readTeam(ctx, actor, func(tx *gorm.DB, instance Team) error {
var tasks []Task
- if err := tx.Where("team_id=?", instance.ID).Order("id").Find(&tasks).Error; err != nil {
+ if err := visibleTasks(tx, instance.ID, weekStart(s.runnerClock.Now())).Order("tasks.id").Find(&tasks).Error; err != nil {
return storeError(err)
}
for _, task := range tasks {
diff --git a/internal/equipo/team/final_observer_test.go b/internal/equipo/team/final_observer_test.go
new file mode 100644
index 00000000..f9e1ae0f
--- /dev/null
+++ b/internal/equipo/team/final_observer_test.go
@@ -0,0 +1,28 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "testing"
+)
+
+func TestObserverFailureDoesNotAbortWrite(t *testing.T) {
+ for _, phase := range []string{"before", "after"} {
+ t.Run(phase, func(t *testing.T) {
+ e := newEnv(t)
+ e.store.observeWrite = func(context.Context, *sql.Tx) (CommitObserver, error) {
+ if phase == "before" {
+ return nil, errors.New("observer broken")
+ }
+ return func(context.Context, *sql.Tx) (func(), error) { return nil, errors.New("observer broken") }, nil
+ }
+ must(t, e.store.Pause(e.ctx, "test"))
+ var paused int
+ must(t, e.store.db.QueryRow("SELECT admission_paused FROM service").Scan(&paused))
+ if paused != 1 {
+ t.Fatal("observer prevented core write")
+ }
+ })
+ }
+}
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go
index a5b3ff50..497c1bce 100644
--- a/internal/equipo/team/store.go
+++ b/internal/equipo/team/store.go
@@ -42,6 +42,7 @@ type CommitObserver func(context.Context, *sql.Tx) (func(), error)
// the incarnation marker kept outside the database; it defaults to the
// database path plus ".incarnation".
type Options struct {
+ ObserverFailed func()
ObserveWrite func(context.Context, *sql.Tx) (CommitObserver, error)
ExecutorEvidence ExecutorEvidenceValidator
Provenance ProvenanceResolver
@@ -56,6 +57,7 @@ type Options struct {
// commit with its external witness. Open launches no goroutine or network
// connection. The database, witness and lock live in trusted local storage.
type Store struct {
+ observerFailed func()
observeWrite func(context.Context, *sql.Tx) (CommitObserver, error)
executorEvidence ExecutorEvidenceValidator
provenance ProvenanceResolver
@@ -110,6 +112,7 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) {
}
s.commitHook = o.commitHook
s.observeWrite = o.ObserveWrite
+ s.observerFailed = o.ObserverFailed
if err := s.start(ctx); err != nil {
db.Close()
return nil, err
@@ -587,7 +590,10 @@ func (s *Store) transaction(ctx context.Context, clean, witnessed bool, fn func(
if s.observeWrite != nil {
observer, err = s.observeWrite(ctx, tx)
if err != nil {
- return err
+ observer = nil
+ if s.observerFailed != nil {
+ s.observerFailed()
+ }
}
}
if err := fn(tx); err != nil {
@@ -597,7 +603,10 @@ func (s *Store) transaction(ctx context.Context, clean, witnessed bool, fn func(
if observer != nil {
notify, err = observer(ctx, tx)
if err != nil {
- return err
+ notify = nil
+ if s.observerFailed != nil {
+ s.observerFailed()
+ }
}
}
var inc, revision int64
diff --git a/internal/equipotest/final_read_cost_test.go b/internal/equipotest/final_read_cost_test.go
new file mode 100644
index 00000000..398837d6
--- /dev/null
+++ b/internal/equipotest/final_read_cost_test.go
@@ -0,0 +1,66 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "context"
+ "gorm.io/gorm"
+ "testing"
+ "time"
+)
+
+func TestIdlePollDoesNotWrite(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ before := scalar(t, f.d, "SELECT revision FROM service")
+ ctx, cancel := context.WithTimeout(connectionContext, 350*time.Millisecond)
+ defer cancel()
+ _, _ = f.x.Poll(ctx, f.principal, f.a.ID)
+ if after := scalar(t, f.d, "SELECT revision FROM service"); after != before {
+ t.Fatalf("idle poll committed %d write transactions", after-before)
+ }
+}
+func TestJourneySkipsOldFinishedBeforeLoading(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ mustSQL(t, f.d, "UPDATE jobs SET state='failed',updated_at=? WHERE id=?", f.clock.Now().AddDate(0, 0, -14).Format(time.RFC3339Nano), f.a.Scope.Job)
+ mustSQL(t, f.d, "UPDATE task_outboxes SET engineering='not-json' WHERE task_id=?", f.a.TaskID)
+ views, err := f.s.Journey(connectionContext, ownerActor)
+ executionMust(t, err)
+ if len(views) != 0 {
+ t.Fatal("loaded old finished task", views)
+ }
+}
+func TestWriteNotifiesOnlyTouchedJob(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "second", "second")
+ executionMust(t, err)
+ task, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f.connectionFixture))
+ executionMust(t, err)
+ _, err = f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
+ executionMust(t, err)
+ n := &taskNotices{}
+ f.s.SetJobNotifier(n)
+ view, err := f.s.TaskView(connectionContext, ownerActor, f.a.TaskID)
+ executionMust(t, err)
+ executionMust(t, f.x.Write(connectionContext, func(tx *gorm.DB) error {
+ return tx.Model(&equipo.Task{}).Where("id=?", f.a.TaskID).Update("description", "changed").Error
+ }))
+ if len(n.topics) != 2 {
+ t.Fatal("write notified unrelated jobs", n.topics)
+ }
+ found := false
+ for _, topic := range n.topics {
+ found = found || topic == view.Topic
+ }
+ if !found {
+ t.Fatal("touched job not notified", n.topics)
+ }
+}
+
+func TestRailCountsUseAggregates(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ mustSQL(t, f.d, "UPDATE task_outboxes SET engineering='not-json' WHERE task_id=?", f.a.TaskID)
+ counts, err := f.s.SpecialistCounts(connectionContext, ownerActor)
+ executionMust(t, err)
+ if counts["engineering"].Working != 1 || counts["review"].Queued != 1 {
+ t.Fatal("incorrect aggregate counts", counts)
+ }
+}