package thin import ( "context" "database/sql" "encoding/json" "errors" "fmt" "reflect" "slices" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/schedule" "amadan.net/oficina/equipo/internal/wire" ) // The scheduler on the runner (connectors spec 2026-11-12 rev 3.1, §7 // and §8, slice S3). Every Engineering, Review and Research attempt, // failover included, is admitted through schedule.Decide: its readings // refreshed first (outside the call), the admission written in one // thin.db transaction that reads the facts again and calls Decide again // when they changed, a pending Run now consumed in that same transaction // and kept as a grant for the step revision. A held step keeps its hold // with its wake-up, is reported once per hold, and is looked at again at // the wake-up and on any fact change. A question never comes here: it // stays on its step's session and passes S1's metered guard. const scheduleSchema = ` CREATE TABLE IF NOT EXISTS releases (id TEXT PRIMARY KEY, person TEXT NOT NULL, task_id TEXT NOT NULL, step_id TEXT NOT NULL, step_revision INTEGER NOT NULL, state TEXT NOT NULL, at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS grants (step_id TEXT NOT NULL, step_revision INTEGER NOT NULL, release_id TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (step_id, step_revision)); CREATE TABLE IF NOT EXISTS admissions (step_id TEXT NOT NULL, attempt INTEGER NOT NULL, step_revision INTEGER NOT NULL, connection TEXT NOT NULL, reason TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (step_id, attempt)); CREATE TABLE IF NOT EXISTS task_priority (task_id TEXT PRIMARY KEY, person TEXT NOT NULL, priority TEXT NOT NULL, by_at TEXT NOT NULL, revision INTEGER NOT NULL); ` // Release states: written by the release frame, consumed by the // admission it causes, or ignored (stale, or its step revision already // holds a grant). const ( releasePending = "pending" releaseConsumed = "consumed" releaseIgnored = "ignored" ) // staleAfter is how old a reading may be before it is refreshed (§6). const staleAfter = 15 * time.Minute // admitRetries bounds how often an admission whose facts moved under it // decides again before the step is held briefly. const admitRetries = 4 // errAdmitted: the attempt was admitted and launched already; it is // never admitted again (a replay starts nothing). var errAdmitted = errors.New("the attempt was admitted already") // errFactsMoved: the facts Decide read changed before the admission // committed; it decides again. var errFactsMoved = errors.New("the scheduler's facts changed") // priorityRank orders the steps a runner holds (§7, release order): // urgent, then a deadline (earliest first), then normal, then low. func priorityRank(priority string, by *time.Time) int { switch { case priority == wire.PriorityUrgent: return 0 case by != nil: return 1 case priority == wire.PriorityLow: return 3 } return 2 } func byStamp(by *time.Time) string { if by == nil { return "" } return by.UTC().Format(time.RFC3339) } func parseBy(v string) *time.Time { if v == "" { return nil } t, err := time.Parse(time.RFC3339, v) if err != nil { return nil } return &t } // stepFacts are the step's own scheduler facts as the runner holds them. type stepFacts struct { priority string housekeeping bool by *time.Time deadlineNotified bool revision int64 // release is the grant or pending release this step revision has // ("" none); pending: not consumed yet. release string pending bool // pin is the connection the release is pinned to (protocol 29), "" // for leave on any connection. pin string } type querier interface { QueryContext(context.Context, string, ...any) (*sql.Rows, error) QueryRowContext(context.Context, string, ...any) *sql.Row } // readStepFacts reads a step's priority, deadline, revision and leave. func readStepFacts(ctx context.Context, q querier, r stepRow) (stepFacts, error) { var f stepFacts var by string var notified, housekeeping int err := q.QueryRowContext(ctx, "SELECT priority, by_at, deadline_notified, revision, housekeeping FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&f.priority, &by, ¬ified, &f.revision, &housekeeping) if errors.Is(err, sql.ErrNoRows) { // Not held in the table (a test calling a step function directly): // the dispatch's own facts. f.priority, f.by, f.revision, f.housekeeping = r.Priority, r.By, r.Attempt, r.Housekeeping err = nil } f.housekeeping = f.housekeeping || housekeeping == 1 if err != nil { return f, err } if f.by == nil { f.by = parseBy(by) } f.deadlineNotified = notified == 1 if f.revision == 0 { f.revision = r.Attempt } err = q.QueryRowContext(ctx, "SELECT g.release_id, coalesce(r.connection, '') FROM grants g LEFT JOIN releases r ON r.id = g.release_id WHERE g.step_id=? AND g.step_revision=?", r.StepID, f.revision).Scan(&f.release, &f.pin) if errors.Is(err, sql.ErrNoRows) { err = q.QueryRowContext(ctx, "SELECT id, connection FROM releases WHERE step_id=? AND step_revision=? AND state=? ORDER BY at, id LIMIT 1", r.StepID, f.revision, releasePending).Scan(&f.release, &f.pin) f.pending = err == nil if errors.Is(err, sql.ErrNoRows) { err = nil } } return f, err } // readings are one subscription connection's facts from thin.db. type reading struct { state, resets, headroom string updated string validated bool } // scheduleFacts are the person's connections on this runner as Decide // reads them, from q (thin.db, or the admission's transaction), with the // bindings they stand for. Bindings come from the bindings file and the // metered table, facts from thin.db only. func (c *Conns) scheduleFacts(ctx context.Context, q querier, person, role string, now time.Time) ([]schedule.Conn, map[string]runner.AccountBinding, error) { out := []schedule.Conn{} by := map[string]runner.AccountBinding{} for _, b := range c.Mine(person) { var rd reading err := q.QueryRowContext(ctx, "SELECT state, resets_at, headroom, updated_at FROM conn_state WHERE id=?", b.ID).Scan(&rd.state, &rd.resets, &rd.headroom, &rd.updated) if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, nil, err } var at string err = q.QueryRowContext(ctx, "SELECT at FROM conn_validated WHERE id=?", b.ID).Scan(&at) if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, nil, err } rd.validated = at != "" sc := schedule.Conn{ID: b.ID, Provider: b.Provider, Family: b.Family, Account: b.AccountID, Billing: schedule.Subscription, Capable: connect.Capable(b.Provider, role), State: rd.state} if role == "copy" { if m, ok := schedule.CopySubscriptionModel(b.Provider, b.Model); ok { sc.Models = []schedule.Model{m} } } if b.Kind == wire.KindToken && !rd.validated { // Never answered a real request: not a connection yet. sc.State = "" } if t, err := time.Parse(time.RFC3339Nano, rd.resets); err == nil && sc.State == wire.ConnLimited { sc.LimitedUntil = t } if rd.headroom != "" { var h wire.Headroom if json.Unmarshal([]byte(rd.headroom), &h) == nil { sc.Windows = windowsOf(&h) } } out = append(out, sc) by[b.ID] = b } if c.Meter != nil { conns, err := metered.List(ctx, q) if err != nil { return nil, nil, err } for _, m := range conns { if m.Person != person || !m.Validated || m.Retiring || !meteredHarness(m.Provider, m.Harness) { continue } b := meteredBinding(m) spend, err := metered.SpendOf(ctx, q, m, now) if err != nil { return nil, nil, err } models, err := meteredModels(ctx, q, m, now) if err != nil { return nil, nil, err } sc := schedule.Conn{ID: b.ID, Provider: b.Provider, Family: b.Family, Account: b.AccountID, Billing: schedule.Metered, Capable: connect.Capable(m.Harness, role), State: wire.ConnHealthy, Busy: spend.Running, SpendUnknown: spend.Unknown, SpendDay: spend.Day, SpendMonth: spend.Month, BudgetDay: m.Budget.Day, BudgetMonth: m.Budget.Month, Models: models} if m.Refused { sc.State = wire.ConnSignInAgain } var state, resets string if err := q.QueryRowContext(ctx, "SELECT state, resets_at FROM conn_state WHERE id=?", b.ID).Scan(&state, &resets); err == nil && (state == wire.ConnLimited || state == wire.ConnSignInAgain) { sc.State = state if t, err := time.Parse(time.RFC3339Nano, resets); err == nil { sc.LimitedUntil = t } } else if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, nil, err } out = append(out, sc) by[b.ID] = b } } return out, by, nil } // windowsOf are a reading's windows, used from 0 to 1. Claude's one // figure, when it gave no windows, is one window. func windowsOf(h *wire.Headroom) []schedule.Window { var out []schedule.Window for _, w := range h.Windows { out = append(out, schedule.Window{Name: w.Name, Used: w.UsedPercent / 100, Minutes: w.Minutes, ResetsAt: w.ResetsAt}) } if len(out) == 0 && h.Utilization != nil { out = append(out, schedule.Window{Name: "utilization", Used: *h.Utilization, ResetsAt: h.ResetsAt}) } return out } // refreshReadings checks the person's connections before a decision // (outside it): one never checked is checked now, as the choice always // did, and a reading older than fifteen minutes is refreshed by the // connection's reading probe when it has one (at most once per fifteen // minutes each). A reading that cannot be refreshed stays as it was // read; a window past its reset counts as not reported in Decide. func (c *Conns) refreshReadings(ctx context.Context, person, role string) { if err := c.load(ctx); err != nil { return } now := c.clock() for _, b := range c.Mine(person) { if !connect.Capable(b.Provider, role) { continue } c.mu.Lock() cs, known := c.live[b.ID] unknown := cs.State == "" c.mu.Unlock() if unknown { c.checkOne(ctx, b) continue } if c.Reading == nil || !known { continue } // A reading's age is its own time (CheckedAt); a row from before // readings were stamped falls back to when the row was written. var updated string _ = c.State.db.QueryRowContext(ctx, "SELECT updated_at FROM conn_state WHERE id=?", b.ID).Scan(&updated) at, err := time.Parse(time.RFC3339Nano, updated) if cs.Headroom != nil && cs.Headroom.CheckedAt != nil { at, err = *cs.Headroom.CheckedAt, nil } if err == nil && now.Sub(at) < staleAfter { continue } c.mu.Lock() if c.probed == nil { c.probed = map[string]time.Time{} } last := c.probed[b.ID] due := last.IsZero() || now.Sub(last) >= staleAfter if due { c.probed[b.ID] = now } c.mu.Unlock() if !due { continue } l, err := c.Reading(ctx, b) if err != nil || l == nil { continue } c.Observe(b.ID, *l, "") } } // decision is one scheduling decision: what Decide read and said, and // the binding it chose (a run) or names (a hold). type decision struct { in schedule.Input d schedule.Decision step stepFacts binding runner.AccountBinding by map[string]runner.AccountBinding } // hold is the decision's hold as the step reports it. func (d decision) hold() *wire.StepHold { if d.d.Run { return nil } h := &wire.StepHold{Reason: d.d.Reason, Connection: d.d.Connection, ResetsAt: d.d.ResetsAt, WakeAt: d.d.WakeAt, NeedsPerson: d.d.NeedsPerson, StepRevision: d.step.revision} if b, ok := d.by[d.d.Connection]; ok { h.Provider = b.Provider } return h } // stepInput is a step's Decide input from the facts. func (c *Conns) stepInput(ctx context.Context, q querier, r stepRow, role string, kept keptRef, avoid []string, eng *schedule.Engineer, now time.Time) (decision, error) { f, err := readStepFacts(ctx, q, r) if err != nil { return decision{}, err } cs, by, err := c.scheduleFacts(ctx, q, r.Person, role, now) if err != nil { return decision{}, err } pref, err := c.preferenceIn(ctx, q, r.Person) if err != nil { return decision{}, err } in := schedule.Input{Version: schedule.Version, Now: now, Conns: cs, Preference: schedule.Preference{Provider: pref.Provider, Until: pref.Until}, Step: schedule.Step{Role: role, Priority: f.priority, Housekeeping: f.housekeeping, By: f.by, DeadlineNotified: f.deadlineNotified, Kept: kept.Conn, KeptModel: kept.Model, Avoid: slices.Clone(avoid), Release: f.release}} if eng != nil { e := *eng in.Step.Engineer = &e } return decision{in: in, step: f, by: by}, nil } // decide refreshes the person's readings, then decides the step. func (c *Conns) decide(ctx context.Context, r stepRow, role string, kept keptRef, avoid []string, eng *schedule.Engineer) (decision, error) { if err := c.load(ctx); err != nil { return decision{}, err } c.refreshReadings(ctx, r.Person, role) d, err := c.stepInput(ctx, c.State.db, r, role, kept, avoid, eng, c.clock()) if err != nil { return d, err } d.d = decidePinned(d.in, d.step.pin) if d.d.Run { // A metered connection runs the pair's model (§16.3). d.binding = withModel(d.by[d.d.Connection], d.d.Model, d.d.Family) } return d, nil } // admitTx writes the admission in t (the caller's transaction: thin.db's // for a subscription, the metered guard's for a metered connection): the // facts read again and compared with what Decide read, the step's // pending release consumed and kept as a grant for its revision, the // admission row, and the step's hold cleared. errFactsMoved: decide // again. func (c *Conns) admitTx(ctx context.Context, t *sql.Tx, r stepRow, d decision) error { again, err := c.stepInput(ctx, t, r, d.in.Step.Role, keptRef{d.in.Step.Kept, d.in.Step.KeptModel}, d.in.Step.Avoid, nil, d.in.Now) if err != nil { return err } if !sameFacts(again.in.Conns, d.in.Conns, d.d.Connection) || again.step.release != d.step.release || again.step.priority != d.step.priority || !reflect.DeepEqual(again.in.Preference, d.in.Preference) { return errFactsMoved } if d.step.release != "" && d.step.pending { res, err := t.ExecContext(ctx, "UPDATE releases SET state=? WHERE id=? AND state=?", releaseConsumed, d.step.release, releasePending) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return errFactsMoved } // The grant: one per step revision, so a replayed release finds it // and starts nothing. if _, err := t.ExecContext(ctx, "INSERT INTO grants(step_id, step_revision, release_id, at) VALUES(?,?,?,?)", r.StepID, d.step.revision, d.step.release, now()); err != nil { return err } } rec := admissionRecord(ctx, t, d) // One execution per admission: an attempt admitted and launched (its // namespace recorded) is never admitted again. The one exception is // explicit: an attempt admitted that launched nothing (a kept // transcript that could not be put in place, a guard that then held // it) may be admitted again. var prior, ns string err = t.QueryRowContext(ctx, "SELECT connection FROM admissions WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&prior) switch { case err == nil: if err := t.QueryRowContext(ctx, "SELECT ns_id FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&ns); err != nil && !errors.Is(err, sql.ErrNoRows) { return err } if ns != "" { return errAdmitted } // Admitted before but launched nothing (a first-use probe ran in // its admission, or a guard held it): the record follows the // admission that launches; from the launch it is immutable. if _, err := t.ExecContext(ctx, "UPDATE admissions SET connection=?, reason=?, at=?, model=?, family=?, tier=?, price_version=?, tier_version=? WHERE step_id=? AND attempt=?", d.d.Connection, d.d.Reason, now(), rec.model, rec.family, rec.tier, rec.priceVersion, rec.tierVersion, r.StepID, r.Attempt); err != nil { return err } case errors.Is(err, sql.ErrNoRows): if _, err := t.ExecContext(ctx, "INSERT INTO admissions(step_id, attempt, step_revision, connection, reason, at, model, family, tier, price_version, tier_version) VALUES(?,?,?,?,?,?,?,?,?,?,?)", r.StepID, r.Attempt, d.step.revision, d.d.Connection, d.d.Reason, now(), rec.model, rec.family, rec.tier, rec.priceVersion, rec.tierVersion); err != nil { return err } default: return err } _, err = t.ExecContext(ctx, "UPDATE steps SET hold='', not_before='' WHERE step_id=? AND attempt=? AND state=?", r.StepID, r.Attempt, runRunning) return err } // sameFacts compares two readings of the connections. A metered // connection's slot is the guard's to recheck (the admitting attempt's // own claim is in it by then), so Busy is not compared. func sameFacts(a, b []schedule.Conn, _ string) bool { if len(a) != len(b) { return false } for i := range a { x, y := a[i], b[i] x.Busy, y.Busy = false, false if !reflect.DeepEqual(x, y) { return false } } return true } // admitFunc is an admission to write in the metered guard's // transaction (nil: nothing to write). type admitFunc func(context.Context, *sql.Tx) error // admit decides the step and, for a subscription, writes its admission; // for a metered connection it returns the admission for runPi to write in // the guard's transaction. A held step returns its hold. Decided again // while the facts move under it, at most admitRetries times. func (c *Conns) admit(ctx context.Context, r stepRow, role string, kept keptRef, avoid []string, eng *schedule.Engineer) (runner.AccountBinding, *wire.StepHold, admitFunc, error) { probes := 0 for range admitRetries + maxProbes { d, err := c.decide(ctx, r, role, kept, avoid, eng) if err != nil { return runner.AccountBinding{}, nil, nil, err } if !d.d.Run { return runner.AccountBinding{}, d.hold(), nil, nil } if Metered(d.binding) { if !d.d.Unprobed { return d.binding, nil, func(ctx context.Context, t *sql.Tx) error { return c.admitTx(ctx, t, r, d) }, nil } // Its model was never answered: probed inside the step's own // admission, then decided again from fresh facts (§16.4). if probes == maxProbes { break } probes++ hold, err := c.probeFirst(ctx, r, d) if err != nil || hold != nil { return runner.AccountBinding{}, hold, nil, err } continue } err = c.State.tx(ctx, func(t *sql.Tx) error { return c.admitTx(ctx, t, r, d) }) if errors.Is(err, errFactsMoved) { continue } return d.binding, nil, nil, err } // The facts kept moving: held briefly, then looked at again. wake := c.clock().Add(heldRetry) return runner.AccountBinding{}, &wire.StepHold{Reason: wire.HoldBusy, WakeAt: &wake}, nil, nil } // admitted is what an admission records of its pair (§16.5). type admitted struct { model, family, tier, priceVersion, tierVersion string } // admissionRecord is the decision's pair as the admission records it: // a metered connection's model with its family, tier, price version // and tier version; a subscription's own model and family. func admissionRecord(ctx context.Context, q querier, d decision) admitted { b := d.binding rec := admitted{model: b.Model, family: firstNonEmpty(d.d.Family, b.Family)} if Metered(b) { rec.tier, rec.tierVersion = d.d.Tier, metered.CurrentTiers if m, ok, err := metered.Get(ctx, q, b.LocalID); err == nil && ok { rec.priceVersion = m.PriceVersion } } return rec } // heldReport is a step's held report: running (the instance keeps it // queued until it starts), with its hold, and the state that tells // runOne to keep it held. func heldReport(rep wire.StepReport, h *wire.StepHold) wire.StepReport { rep.State, rep.Hold = stepDeferred, h return rep } // heldGuard is a step the metered guard held at its admission: held // with the guard's reason on that connection (deferred, as before, when // it gave none). func heldGuard(rep wire.StepReport, res stepResult) wire.StepReport { if res.hold == nil { rep.State = stepDeferred return rep } h := *res.hold return heldReport(rep, &h) } // holdStep keeps a held step's hold and its wake-up (until a fact // changes when it has none), recording that the deadline check fired. // It reports whether the hold is not the one the step had (said once per // hold, not at every look). func (s *State) holdStep(ctx context.Context, r stepRow, h *wire.StepHold) (bool, error) { at := heldUntilChange if h.WakeAt != nil { at = stamp(*h.WakeAt) } changed := false err := s.tx(ctx, func(t *sql.Tx) error { if h.StepRevision == 0 { // The guard's hold: the step revision a Run now names. if err := t.QueryRowContext(ctx, "SELECT revision FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&h.StepRevision); err != nil { return err } } raw, err := json.Marshal(h) if err != nil { return err } var was string if err := t.QueryRowContext(ctx, "SELECT hold FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&was); err != nil { return err } // Said again only when what it says moved: its wake-up alone is // the runner's to keep. var prev wire.StepHold _ = json.Unmarshal([]byte(was), &prev) prev.WakeAt, h.WakeAt = nil, nil a, _ := json.Marshal(prev) b, _ := json.Marshal(h) changed = was == "" || string(a) != string(b) h.WakeAt = parseWake(at) notified := 0 if h.NeedsPerson == wire.HoldNeedsDeadline { notified = 1 } _, err = t.ExecContext(ctx, "UPDATE steps SET hold=?, not_before=?, deadline_notified=MAX(deadline_notified, ?), deferred_since=CASE WHEN deferred_since='' THEN ? ELSE deferred_since END WHERE step_id=? AND attempt=? AND state=?", string(raw), at, notified, stamp(time.Now()), r.StepID, r.Attempt, runRunning) return err }) return changed, err } // parseWake is a not_before stamp as a time (nil: until a change). func parseWake(at string) *time.Time { if at == heldUntilChange { return nil } var ms int64 if _, err := fmt.Sscanf(at, "%d", &ms); err != nil { return nil } t := time.UnixMilli(ms).UTC() return &t } // Release applies a Run now (the durable release frame, once): kept as a // pending release for a step this runner holds at that step revision, // for that person; acked and ignored when the step is not held at that // revision any more, or its revision already holds a grant (a replay). func (s *State) Release(ctx context.Context, frameID string, cmd wire.ReleaseCommand) (bool, error) { kept := false err := s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } state := releaseIgnored var n int if err := t.QueryRowContext(ctx, "SELECT count(*) FROM steps WHERE step_id=? AND task_id=? AND person=? AND revision=? AND state=?", cmd.StepID, cmd.TaskID, cmd.Person, cmd.StepRevision, runRunning).Scan(&n); err != nil { return err } var granted int if err := t.QueryRowContext(ctx, "SELECT count(*) FROM grants WHERE step_id=? AND step_revision=?", cmd.StepID, cmd.StepRevision).Scan(&granted); err != nil { return err } if n > 0 && granted == 0 { state, kept = releasePending, true } _, err = t.ExecContext(ctx, "INSERT INTO releases(id, person, task_id, step_id, step_revision, state, at, connection) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING", cmd.ID, cmd.Person, cmd.TaskID, cmd.StepID, cmd.StepRevision, state, now(), cmd.Connection) return err }) return kept, err } // SetPriority applies a task's priority change (the durable priority // frame, once) to the steps of the task this runner holds, above the // revision held. func (s *State) SetPriority(ctx context.Context, frameID string, cmd wire.PriorityCommand) (bool, error) { if !wire.ValidPriority(cmd.Priority) { return false, nil } applied := false err := s.tx(ctx, func(t *sql.Tx) error { fresh, err := seen(t, frameID) if err != nil || !fresh { return err } var held int64 err = t.QueryRowContext(ctx, "SELECT revision FROM task_priority WHERE task_id=? AND person=?", cmd.TaskID, cmd.Person).Scan(&held) if err != nil && !errors.Is(err, sql.ErrNoRows) { return err } if cmd.Revision <= held { return nil } if _, err = t.ExecContext(ctx, "INSERT INTO task_priority(task_id, person, priority, by_at, revision) VALUES(?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET priority=excluded.priority, by_at=excluded.by_at, revision=excluded.revision", cmd.TaskID, cmd.Person, cmd.Priority, byStamp(cmd.By), cmd.Revision); err != nil { return err } _, err = t.ExecContext(ctx, "UPDATE steps SET priority=?, by_at=?, rank=?, deadline_notified=CASE WHEN by_at=? THEN deadline_notified ELSE 0 END, not_before=CASE WHEN hold<>'' THEN '' ELSE not_before END WHERE task_id=? AND person=? AND state=?", cmd.Priority, byStamp(cmd.By), priorityRank(cmd.Priority, cmd.By), byStamp(cmd.By), cmd.TaskID, cmd.Person, runRunning) applied = err == nil return err }) return applied, err } // acceptScheduled records a dispatch's scheduler facts in t: its step // revision (the attempt the instance sent), priority, deadline and rank, // a later priority change the runner already holds for the task, and a // release it carries. func acceptScheduled(t *sql.Tx, d wire.DispatchCommand) error { // The newest priority wins: a priority frame's value only while no // dispatch carries a newer revision; a newer dispatch's value is kept // as the task's, so an older frame cannot bring it back. priority, by := d.Priority, d.By var held, heldBy string var heldRevision int64 err := t.QueryRow("SELECT priority, by_at, revision FROM task_priority WHERE task_id=? AND person=?", d.TaskID, d.Person).Scan(&held, &heldBy, &heldRevision) switch { case err == nil && heldRevision > d.PriorityRevision: priority, by = held, parseBy(heldBy) case err != nil && !errors.Is(err, sql.ErrNoRows): return err case d.PriorityRevision > 0: if _, err := t.Exec("INSERT INTO task_priority(task_id, person, priority, by_at, revision) VALUES(?,?,?,?,?) ON CONFLICT(task_id) DO UPDATE SET priority=excluded.priority, by_at=excluded.by_at, revision=excluded.revision WHERE excluded.revision > task_priority.revision", d.TaskID, d.Person, d.Priority, byStamp(d.By), d.PriorityRevision); err != nil { return err } } housekeeping := 0 if d.Housekeeping { housekeeping = 1 } if _, err := t.Exec("UPDATE steps SET revision=?, priority=?, by_at=?, rank=?, housekeeping=? WHERE step_id=? AND attempt=? AND revision=0", d.Attempt, priority, byStamp(by), priorityRank(priority, by), housekeeping, d.StepID, d.Attempt); err != nil { return err } if d.Release == "" { return nil } var granted int if err := t.QueryRow("SELECT count(*) FROM grants WHERE step_id=? AND step_revision=?", d.StepID, d.Attempt).Scan(&granted); err != nil { return err } state := releasePending if granted > 0 { state = releaseIgnored } _, err = t.Exec("INSERT INTO releases(id, person, task_id, step_id, step_revision, state, at, connection) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING", d.Release, d.Person, d.TaskID, d.StepID, d.Attempt, state, now(), d.ReleaseConnection) return err } // wakeHeld makes every held step due now (a fact changed). func (s *State) wakeHeld(ctx context.Context) error { _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before='' WHERE hold<>'' AND state=?", runRunning) return err } // preferenceIn is the person's preference read from q; one whose end // has passed is Automatic. func (c *Conns) preferenceIn(ctx context.Context, q querier, person string) (wire.Preferences, error) { var p wire.Preferences var raw string err := q.QueryRowContext(ctx, "SELECT value FROM meta WHERE key=?", "prefer:"+person).Scan(&raw) if errors.Is(err, sql.ErrNoRows) || err == nil && raw == "" { return p, nil } if err != nil { return p, err } if err := json.Unmarshal([]byte(raw), &p); err != nil { return p, fmt.Errorf("preference: %w", err) } return p, nil } // decidePinned is Decide for a step whose Run now is pinned (protocol // 29): what the step would do without the leave first; if that holds, // the leave on the pinned connection alone (schedule.DecidePinned); if // that holds too, the step keeps the hold it would have had, so it still // waits for its own connection's reset and the person's other plans are // never billed in its place. A release with no pin is leave anywhere, as // before. func decidePinned(in schedule.Input, pin string) schedule.Decision { if pin == "" || in.Step.Release == "" { return schedule.Decide(in) } without := in without.Step.Release = "" held := schedule.Decide(without) if held.Run { return held } if d := schedule.DecidePinned(in, pin); d.Run { return d } return held }