| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "reflect" |
| 10 | "slices" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner" |
| 14 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 15 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 16 | "amadan.net/oficina/equipo/internal/schedule" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // The scheduler on the runner (connectors spec 2026-11-12 rev 3.1, §7 |
| 21 | // and §8, slice S3). Every Engineering, Review and Research attempt, |
| 22 | // failover included, is admitted through schedule.Decide: its readings |
| 23 | // refreshed first (outside the call), the admission written in one |
| 24 | // thin.db transaction that reads the facts again and calls Decide again |
| 25 | // when they changed, a pending Run now consumed in that same transaction |
| 26 | // and kept as a grant for the step revision. A held step keeps its hold |
| 27 | // with its wake-up, is reported once per hold, and is looked at again at |
| 28 | // the wake-up and on any fact change. A question never comes here: it |
| 29 | // stays on its step's session and passes S1's metered guard. |
| 30 | |
| 31 | const scheduleSchema = ` |
| 32 | 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); |
| 33 | 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)); |
| 34 | 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)); |
| 35 | 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); |
| 36 | ` |
| 37 | |
| 38 | // Release states: written by the release frame, consumed by the |
| 39 | // admission it causes, or ignored (stale, or its step revision already |
| 40 | // holds a grant). |
| 41 | const ( |
| 42 | releasePending = "pending" |
| 43 | releaseConsumed = "consumed" |
| 44 | releaseIgnored = "ignored" |
| 45 | ) |
| 46 | |
| 47 | // staleAfter is how old a reading may be before it is refreshed (§6). |
| 48 | const staleAfter = 15 * time.Minute |
| 49 | |
| 50 | // admitRetries bounds how often an admission whose facts moved under it |
| 51 | // decides again before the step is held briefly. |
| 52 | const admitRetries = 4 |
| 53 | |
| 54 | // errAdmitted: the attempt was admitted and launched already; it is |
| 55 | // never admitted again (a replay starts nothing). |
| 56 | var errAdmitted = errors.New("the attempt was admitted already") |
| 57 | |
| 58 | // errFactsMoved: the facts Decide read changed before the admission |
| 59 | // committed; it decides again. |
| 60 | var errFactsMoved = errors.New("the scheduler's facts changed") |
| 61 | |
| 62 | // priorityRank orders the steps a runner holds (§7, release order): |
| 63 | // urgent, then a deadline (earliest first), then normal, then low. |
| 64 | func priorityRank(priority string, by *time.Time) int { |
| 65 | switch { |
| 66 | case priority == wire.PriorityUrgent: |
| 67 | return 0 |
| 68 | case by != nil: |
| 69 | return 1 |
| 70 | case priority == wire.PriorityLow: |
| 71 | return 3 |
| 72 | } |
| 73 | return 2 |
| 74 | } |
| 75 | |
| 76 | func byStamp(by *time.Time) string { |
| 77 | if by == nil { |
| 78 | return "" |
| 79 | } |
| 80 | return by.UTC().Format(time.RFC3339) |
| 81 | } |
| 82 | |
| 83 | func parseBy(v string) *time.Time { |
| 84 | if v == "" { |
| 85 | return nil |
| 86 | } |
| 87 | t, err := time.Parse(time.RFC3339, v) |
| 88 | if err != nil { |
| 89 | return nil |
| 90 | } |
| 91 | return &t |
| 92 | } |
| 93 | |
| 94 | // stepFacts are the step's own scheduler facts as the runner holds them. |
| 95 | type stepFacts struct { |
| 96 | priority string |
| 97 | housekeeping bool |
| 98 | by *time.Time |
| 99 | deadlineNotified bool |
| 100 | revision int64 |
| 101 | // release is the grant or pending release this step revision has |
| 102 | // ("" none); pending: not consumed yet. |
| 103 | release string |
| 104 | pending bool |
| 105 | // pin is the connection the release is pinned to (protocol 29), "" |
| 106 | // for leave on any connection. |
| 107 | pin string |
| 108 | } |
| 109 | |
| 110 | type querier interface { |
| 111 | QueryContext(context.Context, string, ...any) (*sql.Rows, error) |
| 112 | QueryRowContext(context.Context, string, ...any) *sql.Row |
| 113 | } |
| 114 | |
| 115 | // readStepFacts reads a step's priority, deadline, revision and leave. |
| 116 | func readStepFacts(ctx context.Context, q querier, r stepRow) (stepFacts, error) { |
| 117 | var f stepFacts |
| 118 | var by string |
| 119 | var notified, housekeeping int |
| 120 | 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) |
| 121 | if errors.Is(err, sql.ErrNoRows) { |
| 122 | // Not held in the table (a test calling a step function directly): |
| 123 | // the dispatch's own facts. |
| 124 | f.priority, f.by, f.revision, f.housekeeping = r.Priority, r.By, r.Attempt, r.Housekeeping |
| 125 | err = nil |
| 126 | } |
| 127 | f.housekeeping = f.housekeeping || housekeeping == 1 |
| 128 | if err != nil { |
| 129 | return f, err |
| 130 | } |
| 131 | if f.by == nil { |
| 132 | f.by = parseBy(by) |
| 133 | } |
| 134 | f.deadlineNotified = notified == 1 |
| 135 | if f.revision == 0 { |
| 136 | f.revision = r.Attempt |
| 137 | } |
| 138 | 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) |
| 139 | if errors.Is(err, sql.ErrNoRows) { |
| 140 | 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) |
| 141 | f.pending = err == nil |
| 142 | if errors.Is(err, sql.ErrNoRows) { |
| 143 | err = nil |
| 144 | } |
| 145 | } |
| 146 | return f, err |
| 147 | } |
| 148 | |
| 149 | // readings are one subscription connection's facts from thin.db. |
| 150 | type reading struct { |
| 151 | state, resets, headroom string |
| 152 | updated string |
| 153 | validated bool |
| 154 | } |
| 155 | |
| 156 | // scheduleFacts are the person's connections on this runner as Decide |
| 157 | // reads them, from q (thin.db, or the admission's transaction), with the |
| 158 | // bindings they stand for. Bindings come from the bindings file and the |
| 159 | // metered table, facts from thin.db only. |
| 160 | func (c *Conns) scheduleFacts(ctx context.Context, q querier, person, role string, now time.Time) ([]schedule.Conn, map[string]runner.AccountBinding, error) { |
| 161 | out := []schedule.Conn{} |
| 162 | by := map[string]runner.AccountBinding{} |
| 163 | for _, b := range c.Mine(person) { |
| 164 | var rd reading |
| 165 | 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) |
| 166 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 167 | return nil, nil, err |
| 168 | } |
| 169 | var at string |
| 170 | err = q.QueryRowContext(ctx, "SELECT at FROM conn_validated WHERE id=?", b.ID).Scan(&at) |
| 171 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 172 | return nil, nil, err |
| 173 | } |
| 174 | rd.validated = at != "" |
| 175 | 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} |
| 176 | if role == "copy" { |
| 177 | if m, ok := schedule.CopySubscriptionModel(b.Provider, b.Model); ok { |
| 178 | sc.Models = []schedule.Model{m} |
| 179 | } |
| 180 | } |
| 181 | if b.Kind == wire.KindToken && !rd.validated { |
| 182 | // Never answered a real request: not a connection yet. |
| 183 | sc.State = "" |
| 184 | } |
| 185 | if t, err := time.Parse(time.RFC3339Nano, rd.resets); err == nil && sc.State == wire.ConnLimited { |
| 186 | sc.LimitedUntil = t |
| 187 | } |
| 188 | if rd.headroom != "" { |
| 189 | var h wire.Headroom |
| 190 | if json.Unmarshal([]byte(rd.headroom), &h) == nil { |
| 191 | sc.Windows = windowsOf(&h) |
| 192 | } |
| 193 | } |
| 194 | out = append(out, sc) |
| 195 | by[b.ID] = b |
| 196 | } |
| 197 | if c.Meter != nil { |
| 198 | conns, err := metered.List(ctx, q) |
| 199 | if err != nil { |
| 200 | return nil, nil, err |
| 201 | } |
| 202 | for _, m := range conns { |
| 203 | if m.Person != person || !m.Validated || m.Retiring || !meteredHarness(m.Provider, m.Harness) { |
| 204 | continue |
| 205 | } |
| 206 | b := meteredBinding(m) |
| 207 | spend, err := metered.SpendOf(ctx, q, m, now) |
| 208 | if err != nil { |
| 209 | return nil, nil, err |
| 210 | } |
| 211 | models, err := meteredModels(ctx, q, m, now) |
| 212 | if err != nil { |
| 213 | return nil, nil, err |
| 214 | } |
| 215 | 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} |
| 216 | if m.Refused { |
| 217 | sc.State = wire.ConnSignInAgain |
| 218 | } |
| 219 | var state, resets string |
| 220 | 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) { |
| 221 | sc.State = state |
| 222 | if t, err := time.Parse(time.RFC3339Nano, resets); err == nil { |
| 223 | sc.LimitedUntil = t |
| 224 | } |
| 225 | } else if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 226 | return nil, nil, err |
| 227 | } |
| 228 | out = append(out, sc) |
| 229 | by[b.ID] = b |
| 230 | } |
| 231 | } |
| 232 | return out, by, nil |
| 233 | } |
| 234 | |
| 235 | // windowsOf are a reading's windows, used from 0 to 1. Claude's one |
| 236 | // figure, when it gave no windows, is one window. |
| 237 | func windowsOf(h *wire.Headroom) []schedule.Window { |
| 238 | var out []schedule.Window |
| 239 | for _, w := range h.Windows { |
| 240 | out = append(out, schedule.Window{Name: w.Name, Used: w.UsedPercent / 100, Minutes: w.Minutes, ResetsAt: w.ResetsAt}) |
| 241 | } |
| 242 | if len(out) == 0 && h.Utilization != nil { |
| 243 | out = append(out, schedule.Window{Name: "utilization", Used: *h.Utilization, ResetsAt: h.ResetsAt}) |
| 244 | } |
| 245 | return out |
| 246 | } |
| 247 | |
| 248 | // refreshReadings checks the person's connections before a decision |
| 249 | // (outside it): one never checked is checked now, as the choice always |
| 250 | // did, and a reading older than fifteen minutes is refreshed by the |
| 251 | // connection's reading probe when it has one (at most once per fifteen |
| 252 | // minutes each). A reading that cannot be refreshed stays as it was |
| 253 | // read; a window past its reset counts as not reported in Decide. |
| 254 | func (c *Conns) refreshReadings(ctx context.Context, person, role string) { |
| 255 | if err := c.load(ctx); err != nil { |
| 256 | return |
| 257 | } |
| 258 | now := c.clock() |
| 259 | for _, b := range c.Mine(person) { |
| 260 | if !connect.Capable(b.Provider, role) { |
| 261 | continue |
| 262 | } |
| 263 | c.mu.Lock() |
| 264 | cs, known := c.live[b.ID] |
| 265 | unknown := cs.State == "" |
| 266 | c.mu.Unlock() |
| 267 | if unknown { |
| 268 | c.checkOne(ctx, b) |
| 269 | continue |
| 270 | } |
| 271 | if c.Reading == nil || !known { |
| 272 | continue |
| 273 | } |
| 274 | // A reading's age is its own time (CheckedAt); a row from before |
| 275 | // readings were stamped falls back to when the row was written. |
| 276 | var updated string |
| 277 | _ = c.State.db.QueryRowContext(ctx, "SELECT updated_at FROM conn_state WHERE id=?", b.ID).Scan(&updated) |
| 278 | at, err := time.Parse(time.RFC3339Nano, updated) |
| 279 | if cs.Headroom != nil && cs.Headroom.CheckedAt != nil { |
| 280 | at, err = *cs.Headroom.CheckedAt, nil |
| 281 | } |
| 282 | if err == nil && now.Sub(at) < staleAfter { |
| 283 | continue |
| 284 | } |
| 285 | c.mu.Lock() |
| 286 | if c.probed == nil { |
| 287 | c.probed = map[string]time.Time{} |
| 288 | } |
| 289 | last := c.probed[b.ID] |
| 290 | due := last.IsZero() || now.Sub(last) >= staleAfter |
| 291 | if due { |
| 292 | c.probed[b.ID] = now |
| 293 | } |
| 294 | c.mu.Unlock() |
| 295 | if !due { |
| 296 | continue |
| 297 | } |
| 298 | l, err := c.Reading(ctx, b) |
| 299 | if err != nil || l == nil { |
| 300 | continue |
| 301 | } |
| 302 | c.Observe(b.ID, *l, "") |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | // decision is one scheduling decision: what Decide read and said, and |
| 307 | // the binding it chose (a run) or names (a hold). |
| 308 | type decision struct { |
| 309 | in schedule.Input |
| 310 | d schedule.Decision |
| 311 | step stepFacts |
| 312 | binding runner.AccountBinding |
| 313 | by map[string]runner.AccountBinding |
| 314 | } |
| 315 | |
| 316 | // hold is the decision's hold as the step reports it. |
| 317 | func (d decision) hold() *wire.StepHold { |
| 318 | if d.d.Run { |
| 319 | return nil |
| 320 | } |
| 321 | 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} |
| 322 | if b, ok := d.by[d.d.Connection]; ok { |
| 323 | h.Provider = b.Provider |
| 324 | } |
| 325 | return h |
| 326 | } |
| 327 | |
| 328 | // stepInput is a step's Decide input from the facts. |
| 329 | 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) { |
| 330 | f, err := readStepFacts(ctx, q, r) |
| 331 | if err != nil { |
| 332 | return decision{}, err |
| 333 | } |
| 334 | cs, by, err := c.scheduleFacts(ctx, q, r.Person, role, now) |
| 335 | if err != nil { |
| 336 | return decision{}, err |
| 337 | } |
| 338 | pref, err := c.preferenceIn(ctx, q, r.Person) |
| 339 | if err != nil { |
| 340 | return decision{}, err |
| 341 | } |
| 342 | 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}} |
| 343 | if eng != nil { |
| 344 | e := *eng |
| 345 | in.Step.Engineer = &e |
| 346 | } |
| 347 | return decision{in: in, step: f, by: by}, nil |
| 348 | } |
| 349 | |
| 350 | // decide refreshes the person's readings, then decides the step. |
| 351 | func (c *Conns) decide(ctx context.Context, r stepRow, role string, kept keptRef, avoid []string, eng *schedule.Engineer) (decision, error) { |
| 352 | if err := c.load(ctx); err != nil { |
| 353 | return decision{}, err |
| 354 | } |
| 355 | c.refreshReadings(ctx, r.Person, role) |
| 356 | d, err := c.stepInput(ctx, c.State.db, r, role, kept, avoid, eng, c.clock()) |
| 357 | if err != nil { |
| 358 | return d, err |
| 359 | } |
| 360 | d.d = decidePinned(d.in, d.step.pin) |
| 361 | if d.d.Run { |
| 362 | // A metered connection runs the pair's model (§16.3). |
| 363 | d.binding = withModel(d.by[d.d.Connection], d.d.Model, d.d.Family) |
| 364 | } |
| 365 | return d, nil |
| 366 | } |
| 367 | |
| 368 | // admitTx writes the admission in t (the caller's transaction: thin.db's |
| 369 | // for a subscription, the metered guard's for a metered connection): the |
| 370 | // facts read again and compared with what Decide read, the step's |
| 371 | // pending release consumed and kept as a grant for its revision, the |
| 372 | // admission row, and the step's hold cleared. errFactsMoved: decide |
| 373 | // again. |
| 374 | func (c *Conns) admitTx(ctx context.Context, t *sql.Tx, r stepRow, d decision) error { |
| 375 | 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) |
| 376 | if err != nil { |
| 377 | return err |
| 378 | } |
| 379 | 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) { |
| 380 | return errFactsMoved |
| 381 | } |
| 382 | if d.step.release != "" && d.step.pending { |
| 383 | res, err := t.ExecContext(ctx, "UPDATE releases SET state=? WHERE id=? AND state=?", releaseConsumed, d.step.release, releasePending) |
| 384 | if err != nil { |
| 385 | return err |
| 386 | } |
| 387 | if n, _ := res.RowsAffected(); n != 1 { |
| 388 | return errFactsMoved |
| 389 | } |
| 390 | // The grant: one per step revision, so a replayed release finds it |
| 391 | // and starts nothing. |
| 392 | 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 { |
| 393 | return err |
| 394 | } |
| 395 | } |
| 396 | rec := admissionRecord(ctx, t, d) |
| 397 | // One execution per admission: an attempt admitted and launched (its |
| 398 | // namespace recorded) is never admitted again. The one exception is |
| 399 | // explicit: an attempt admitted that launched nothing (a kept |
| 400 | // transcript that could not be put in place, a guard that then held |
| 401 | // it) may be admitted again. |
| 402 | var prior, ns string |
| 403 | err = t.QueryRowContext(ctx, "SELECT connection FROM admissions WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&prior) |
| 404 | switch { |
| 405 | case err == nil: |
| 406 | 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) { |
| 407 | return err |
| 408 | } |
| 409 | if ns != "" { |
| 410 | return errAdmitted |
| 411 | } |
| 412 | // Admitted before but launched nothing (a first-use probe ran in |
| 413 | // its admission, or a guard held it): the record follows the |
| 414 | // admission that launches; from the launch it is immutable. |
| 415 | 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 { |
| 416 | return err |
| 417 | } |
| 418 | case errors.Is(err, sql.ErrNoRows): |
| 419 | 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 { |
| 420 | return err |
| 421 | } |
| 422 | default: |
| 423 | return err |
| 424 | } |
| 425 | _, err = t.ExecContext(ctx, "UPDATE steps SET hold='', not_before='' WHERE step_id=? AND attempt=? AND state=?", r.StepID, r.Attempt, runRunning) |
| 426 | return err |
| 427 | } |
| 428 | |
| 429 | // sameFacts compares two readings of the connections. A metered |
| 430 | // connection's slot is the guard's to recheck (the admitting attempt's |
| 431 | // own claim is in it by then), so Busy is not compared. |
| 432 | func sameFacts(a, b []schedule.Conn, _ string) bool { |
| 433 | if len(a) != len(b) { |
| 434 | return false |
| 435 | } |
| 436 | for i := range a { |
| 437 | x, y := a[i], b[i] |
| 438 | x.Busy, y.Busy = false, false |
| 439 | if !reflect.DeepEqual(x, y) { |
| 440 | return false |
| 441 | } |
| 442 | } |
| 443 | return true |
| 444 | } |
| 445 | |
| 446 | // admitFunc is an admission to write in the metered guard's |
| 447 | // transaction (nil: nothing to write). |
| 448 | type admitFunc func(context.Context, *sql.Tx) error |
| 449 | |
| 450 | // admit decides the step and, for a subscription, writes its admission; |
| 451 | // for a metered connection it returns the admission for runPi to write in |
| 452 | // the guard's transaction. A held step returns its hold. Decided again |
| 453 | // while the facts move under it, at most admitRetries times. |
| 454 | func (c *Conns) admit(ctx context.Context, r stepRow, role string, kept keptRef, avoid []string, eng *schedule.Engineer) (runner.AccountBinding, *wire.StepHold, admitFunc, error) { |
| 455 | probes := 0 |
| 456 | for range admitRetries + maxProbes { |
| 457 | d, err := c.decide(ctx, r, role, kept, avoid, eng) |
| 458 | if err != nil { |
| 459 | return runner.AccountBinding{}, nil, nil, err |
| 460 | } |
| 461 | if !d.d.Run { |
| 462 | return runner.AccountBinding{}, d.hold(), nil, nil |
| 463 | } |
| 464 | if Metered(d.binding) { |
| 465 | if !d.d.Unprobed { |
| 466 | return d.binding, nil, func(ctx context.Context, t *sql.Tx) error { return c.admitTx(ctx, t, r, d) }, nil |
| 467 | } |
| 468 | // Its model was never answered: probed inside the step's own |
| 469 | // admission, then decided again from fresh facts (§16.4). |
| 470 | if probes == maxProbes { |
| 471 | break |
| 472 | } |
| 473 | probes++ |
| 474 | hold, err := c.probeFirst(ctx, r, d) |
| 475 | if err != nil || hold != nil { |
| 476 | return runner.AccountBinding{}, hold, nil, err |
| 477 | } |
| 478 | continue |
| 479 | } |
| 480 | err = c.State.tx(ctx, func(t *sql.Tx) error { return c.admitTx(ctx, t, r, d) }) |
| 481 | if errors.Is(err, errFactsMoved) { |
| 482 | continue |
| 483 | } |
| 484 | return d.binding, nil, nil, err |
| 485 | } |
| 486 | // The facts kept moving: held briefly, then looked at again. |
| 487 | wake := c.clock().Add(heldRetry) |
| 488 | return runner.AccountBinding{}, &wire.StepHold{Reason: wire.HoldBusy, WakeAt: &wake}, nil, nil |
| 489 | } |
| 490 | |
| 491 | // admitted is what an admission records of its pair (§16.5). |
| 492 | type admitted struct { |
| 493 | model, family, tier, priceVersion, tierVersion string |
| 494 | } |
| 495 | |
| 496 | // admissionRecord is the decision's pair as the admission records it: |
| 497 | // a metered connection's model with its family, tier, price version |
| 498 | // and tier version; a subscription's own model and family. |
| 499 | func admissionRecord(ctx context.Context, q querier, d decision) admitted { |
| 500 | b := d.binding |
| 501 | rec := admitted{model: b.Model, family: firstNonEmpty(d.d.Family, b.Family)} |
| 502 | if Metered(b) { |
| 503 | rec.tier, rec.tierVersion = d.d.Tier, metered.CurrentTiers |
| 504 | if m, ok, err := metered.Get(ctx, q, b.LocalID); err == nil && ok { |
| 505 | rec.priceVersion = m.PriceVersion |
| 506 | } |
| 507 | } |
| 508 | return rec |
| 509 | } |
| 510 | |
| 511 | // heldReport is a step's held report: running (the instance keeps it |
| 512 | // queued until it starts), with its hold, and the state that tells |
| 513 | // runOne to keep it held. |
| 514 | func heldReport(rep wire.StepReport, h *wire.StepHold) wire.StepReport { |
| 515 | rep.State, rep.Hold = stepDeferred, h |
| 516 | return rep |
| 517 | } |
| 518 | |
| 519 | // heldGuard is a step the metered guard held at its admission: held |
| 520 | // with the guard's reason on that connection (deferred, as before, when |
| 521 | // it gave none). |
| 522 | func heldGuard(rep wire.StepReport, res stepResult) wire.StepReport { |
| 523 | if res.hold == nil { |
| 524 | rep.State = stepDeferred |
| 525 | return rep |
| 526 | } |
| 527 | h := *res.hold |
| 528 | return heldReport(rep, &h) |
| 529 | } |
| 530 | |
| 531 | // holdStep keeps a held step's hold and its wake-up (until a fact |
| 532 | // changes when it has none), recording that the deadline check fired. |
| 533 | // It reports whether the hold is not the one the step had (said once per |
| 534 | // hold, not at every look). |
| 535 | func (s *State) holdStep(ctx context.Context, r stepRow, h *wire.StepHold) (bool, error) { |
| 536 | at := heldUntilChange |
| 537 | if h.WakeAt != nil { |
| 538 | at = stamp(*h.WakeAt) |
| 539 | } |
| 540 | changed := false |
| 541 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 542 | if h.StepRevision == 0 { |
| 543 | // The guard's hold: the step revision a Run now names. |
| 544 | if err := t.QueryRowContext(ctx, "SELECT revision FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&h.StepRevision); err != nil { |
| 545 | return err |
| 546 | } |
| 547 | } |
| 548 | raw, err := json.Marshal(h) |
| 549 | if err != nil { |
| 550 | return err |
| 551 | } |
| 552 | var was string |
| 553 | if err := t.QueryRowContext(ctx, "SELECT hold FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&was); err != nil { |
| 554 | return err |
| 555 | } |
| 556 | // Said again only when what it says moved: its wake-up alone is |
| 557 | // the runner's to keep. |
| 558 | var prev wire.StepHold |
| 559 | _ = json.Unmarshal([]byte(was), &prev) |
| 560 | prev.WakeAt, h.WakeAt = nil, nil |
| 561 | a, _ := json.Marshal(prev) |
| 562 | b, _ := json.Marshal(h) |
| 563 | changed = was == "" || string(a) != string(b) |
| 564 | h.WakeAt = parseWake(at) |
| 565 | notified := 0 |
| 566 | if h.NeedsPerson == wire.HoldNeedsDeadline { |
| 567 | notified = 1 |
| 568 | } |
| 569 | _, 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) |
| 570 | return err |
| 571 | }) |
| 572 | return changed, err |
| 573 | } |
| 574 | |
| 575 | // parseWake is a not_before stamp as a time (nil: until a change). |
| 576 | func parseWake(at string) *time.Time { |
| 577 | if at == heldUntilChange { |
| 578 | return nil |
| 579 | } |
| 580 | var ms int64 |
| 581 | if _, err := fmt.Sscanf(at, "%d", &ms); err != nil { |
| 582 | return nil |
| 583 | } |
| 584 | t := time.UnixMilli(ms).UTC() |
| 585 | return &t |
| 586 | } |
| 587 | |
| 588 | // Release applies a Run now (the durable release frame, once): kept as a |
| 589 | // pending release for a step this runner holds at that step revision, |
| 590 | // for that person; acked and ignored when the step is not held at that |
| 591 | // revision any more, or its revision already holds a grant (a replay). |
| 592 | func (s *State) Release(ctx context.Context, frameID string, cmd wire.ReleaseCommand) (bool, error) { |
| 593 | kept := false |
| 594 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 595 | fresh, err := seen(t, frameID) |
| 596 | if err != nil || !fresh { |
| 597 | return err |
| 598 | } |
| 599 | state := releaseIgnored |
| 600 | var n int |
| 601 | 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 { |
| 602 | return err |
| 603 | } |
| 604 | var granted int |
| 605 | if err := t.QueryRowContext(ctx, "SELECT count(*) FROM grants WHERE step_id=? AND step_revision=?", cmd.StepID, cmd.StepRevision).Scan(&granted); err != nil { |
| 606 | return err |
| 607 | } |
| 608 | if n > 0 && granted == 0 { |
| 609 | state, kept = releasePending, true |
| 610 | } |
| 611 | _, 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) |
| 612 | return err |
| 613 | }) |
| 614 | return kept, err |
| 615 | } |
| 616 | |
| 617 | // SetPriority applies a task's priority change (the durable priority |
| 618 | // frame, once) to the steps of the task this runner holds, above the |
| 619 | // revision held. |
| 620 | func (s *State) SetPriority(ctx context.Context, frameID string, cmd wire.PriorityCommand) (bool, error) { |
| 621 | if !wire.ValidPriority(cmd.Priority) { |
| 622 | return false, nil |
| 623 | } |
| 624 | applied := false |
| 625 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 626 | fresh, err := seen(t, frameID) |
| 627 | if err != nil || !fresh { |
| 628 | return err |
| 629 | } |
| 630 | var held int64 |
| 631 | err = t.QueryRowContext(ctx, "SELECT revision FROM task_priority WHERE task_id=? AND person=?", cmd.TaskID, cmd.Person).Scan(&held) |
| 632 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 633 | return err |
| 634 | } |
| 635 | if cmd.Revision <= held { |
| 636 | return nil |
| 637 | } |
| 638 | 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 { |
| 639 | return err |
| 640 | } |
| 641 | _, 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) |
| 642 | applied = err == nil |
| 643 | return err |
| 644 | }) |
| 645 | return applied, err |
| 646 | } |
| 647 | |
| 648 | // acceptScheduled records a dispatch's scheduler facts in t: its step |
| 649 | // revision (the attempt the instance sent), priority, deadline and rank, |
| 650 | // a later priority change the runner already holds for the task, and a |
| 651 | // release it carries. |
| 652 | func acceptScheduled(t *sql.Tx, d wire.DispatchCommand) error { |
| 653 | // The newest priority wins: a priority frame's value only while no |
| 654 | // dispatch carries a newer revision; a newer dispatch's value is kept |
| 655 | // as the task's, so an older frame cannot bring it back. |
| 656 | priority, by := d.Priority, d.By |
| 657 | var held, heldBy string |
| 658 | var heldRevision int64 |
| 659 | err := t.QueryRow("SELECT priority, by_at, revision FROM task_priority WHERE task_id=? AND person=?", d.TaskID, d.Person).Scan(&held, &heldBy, &heldRevision) |
| 660 | switch { |
| 661 | case err == nil && heldRevision > d.PriorityRevision: |
| 662 | priority, by = held, parseBy(heldBy) |
| 663 | case err != nil && !errors.Is(err, sql.ErrNoRows): |
| 664 | return err |
| 665 | case d.PriorityRevision > 0: |
| 666 | 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 { |
| 667 | return err |
| 668 | } |
| 669 | } |
| 670 | housekeeping := 0 |
| 671 | if d.Housekeeping { |
| 672 | housekeeping = 1 |
| 673 | } |
| 674 | 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 { |
| 675 | return err |
| 676 | } |
| 677 | if d.Release == "" { |
| 678 | return nil |
| 679 | } |
| 680 | var granted int |
| 681 | if err := t.QueryRow("SELECT count(*) FROM grants WHERE step_id=? AND step_revision=?", d.StepID, d.Attempt).Scan(&granted); err != nil { |
| 682 | return err |
| 683 | } |
| 684 | state := releasePending |
| 685 | if granted > 0 { |
| 686 | state = releaseIgnored |
| 687 | } |
| 688 | _, 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) |
| 689 | return err |
| 690 | } |
| 691 | |
| 692 | // wakeHeld makes every held step due now (a fact changed). |
| 693 | func (s *State) wakeHeld(ctx context.Context) error { |
| 694 | _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before='' WHERE hold<>'' AND state=?", runRunning) |
| 695 | return err |
| 696 | } |
| 697 | |
| 698 | // preferenceIn is the person's preference read from q; one whose end |
| 699 | // has passed is Automatic. |
| 700 | func (c *Conns) preferenceIn(ctx context.Context, q querier, person string) (wire.Preferences, error) { |
| 701 | var p wire.Preferences |
| 702 | var raw string |
| 703 | err := q.QueryRowContext(ctx, "SELECT value FROM meta WHERE key=?", "prefer:"+person).Scan(&raw) |
| 704 | if errors.Is(err, sql.ErrNoRows) || err == nil && raw == "" { |
| 705 | return p, nil |
| 706 | } |
| 707 | if err != nil { |
| 708 | return p, err |
| 709 | } |
| 710 | if err := json.Unmarshal([]byte(raw), &p); err != nil { |
| 711 | return p, fmt.Errorf("preference: %w", err) |
| 712 | } |
| 713 | return p, nil |
| 714 | } |
| 715 | |
| 716 | // decidePinned is Decide for a step whose Run now is pinned (protocol |
| 717 | // 29): what the step would do without the leave first; if that holds, |
| 718 | // the leave on the pinned connection alone (schedule.DecidePinned); if |
| 719 | // that holds too, the step keeps the hold it would have had, so it still |
| 720 | // waits for its own connection's reset and the person's other plans are |
| 721 | // never billed in its place. A release with no pin is leave anywhere, as |
| 722 | // before. |
| 723 | func decidePinned(in schedule.Input, pin string) schedule.Decision { |
| 724 | if pin == "" || in.Step.Release == "" { |
| 725 | return schedule.Decide(in) |
| 726 | } |
| 727 | without := in |
| 728 | without.Step.Release = "" |
| 729 | held := schedule.Decide(without) |
| 730 | if held.Run { |
| 731 | return held |
| 732 | } |
| 733 | if d := schedule.DecidePinned(in, pin); d.Run { |
| 734 | return d |
| 735 | } |
| 736 | return held |
| 737 | } |
| 738 | |