| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "database/sql" |
| 7 | "encoding/hex" |
| 8 | "errors" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner" |
| 14 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 15 | "amadan.net/oficina/equipo/internal/schedule" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // Models chosen per step on the runner (connectors spec rev 3.3, §16, |
| 20 | // slice S5b). A metered connection allows a set of models; Decide picks |
| 21 | // one (connection, model) pair per step. A model never answered yet is |
| 22 | // probed first, inside the step's own admission, and the step is then |
| 23 | // decided again from fresh facts. Every admission records the model, |
| 24 | // family, tier and table versions it chose, and every kept session the |
| 25 | // model and family it was created on. |
| 26 | |
| 27 | // maxProbes bounds the first-use probes one admission runs before the |
| 28 | // step is held briefly and looked at again. |
| 29 | const maxProbes = 3 |
| 30 | |
| 31 | // keptRef is the session a step resumes: its connection and the model |
| 32 | // it was created on ("" for a subscription's own). |
| 33 | type keptRef struct { |
| 34 | Conn, Model string |
| 35 | } |
| 36 | |
| 37 | // migrateModels brings thin.db to S5b (§16.5): the allowed sets (each |
| 38 | // single-model connection's set is its one model), the admission and |
| 39 | // kept-session columns, and their backfill from the connection's one |
| 40 | // model, which was the only model it could run. Tiers are not |
| 41 | // backfilled: no tier table existed when those attempts ran. |
| 42 | func migrateModels(ctx context.Context, d *sql.DB) error { |
| 43 | if err := metered.Migrate(ctx, d); err != nil { |
| 44 | return err |
| 45 | } |
| 46 | if _, err := d.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS probe_seq (probe_id TEXT PRIMARY KEY, n INTEGER NOT NULL)"); err != nil { |
| 47 | return err |
| 48 | } |
| 49 | for _, add := range []struct{ table, col string }{ |
| 50 | {"admissions", "model"}, {"admissions", "family"}, {"admissions", "tier"}, {"admissions", "price_version"}, {"admissions", "tier_version"}, |
| 51 | {"kept_sessions", "model"}, {"kept_sessions", "family"}, |
| 52 | {"connect_attempts", "allowed"}, |
| 53 | } { |
| 54 | if _, err := d.ExecContext(ctx, "ALTER TABLE "+add.table+" ADD COLUMN "+add.col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 55 | return err |
| 56 | } |
| 57 | } |
| 58 | conns, err := metered.List(ctx, d) |
| 59 | if err != nil { |
| 60 | return err |
| 61 | } |
| 62 | for _, m := range conns { |
| 63 | if m.Model == "" { |
| 64 | continue |
| 65 | } |
| 66 | family := meteredFamily(m.Provider, m.Model) |
| 67 | if _, err := d.ExecContext(ctx, "UPDATE admissions SET model=?, family=?, price_version=? WHERE connection=? AND model=''", m.Model, family, m.PriceVersion, m.LocalID); err != nil { |
| 68 | return err |
| 69 | } |
| 70 | if _, err := d.ExecContext(ctx, "UPDATE kept_sessions SET model=?, family=? WHERE account=? AND model=''", m.Model, family, m.LocalID); err != nil { |
| 71 | return err |
| 72 | } |
| 73 | } |
| 74 | return nil |
| 75 | } |
| 76 | |
| 77 | // meteredModels are a metered connection's eligible models as Decide |
| 78 | // reads them (§16.3): allowed, priced in the connection's table and |
| 79 | // tiered now, and not unhealthy; an unhealthy one a day after it failed |
| 80 | // is offered as unprobed (a retry on demand, never by a timer). |
| 81 | func meteredModels(ctx context.Context, q querier, m metered.Conn, now time.Time) ([]schedule.Model, error) { |
| 82 | allowed, err := metered.Models(ctx, q, m.LocalID) |
| 83 | if err != nil { |
| 84 | return nil, err |
| 85 | } |
| 86 | out := []schedule.Model{} |
| 87 | for _, a := range allowed { |
| 88 | t, p, ok := metered.Eligible(m.Provider, m.PriceVersion, a.ID) |
| 89 | if !ok { |
| 90 | continue |
| 91 | } |
| 92 | sm := schedule.Model{ID: a.ID, Family: t.Family, Tier: t.Tier, Output: value(p.Output), Input: value(p.UncachedInput)} |
| 93 | switch { |
| 94 | case a.State == wire.ModelHealthy: |
| 95 | case a.State == wire.ModelUnprobed, a.Retryable(now): |
| 96 | sm.Unprobed = true |
| 97 | default: |
| 98 | continue |
| 99 | } |
| 100 | out = append(out, sm) |
| 101 | } |
| 102 | return out, nil |
| 103 | } |
| 104 | |
| 105 | func value(v *int64) int64 { |
| 106 | if v == nil { |
| 107 | return 0 |
| 108 | } |
| 109 | return *v |
| 110 | } |
| 111 | |
| 112 | // heldModels are a metered connection's allowed set as hello and sync |
| 113 | // carry it (ProtocolModels). |
| 114 | func heldModels(ctx context.Context, q querier, m metered.Conn) []wire.ModelState { |
| 115 | allowed, err := metered.Models(ctx, q, m.LocalID) |
| 116 | if err != nil { |
| 117 | return nil |
| 118 | } |
| 119 | out := []wire.ModelState{} |
| 120 | for _, a := range allowed { |
| 121 | s := wire.ModelState{ID: a.ID, State: a.State, Reason: a.Reason} |
| 122 | if !a.FailedAt.IsZero() { |
| 123 | at := a.FailedAt |
| 124 | s.FailedAt = &at |
| 125 | } |
| 126 | if t, ok := metered.TierOf(m.Provider, a.ID); ok { |
| 127 | s.Family, s.Tier = t.Family, t.Tier |
| 128 | } |
| 129 | out = append(out, s) |
| 130 | } |
| 131 | return out |
| 132 | } |
| 133 | |
| 134 | // heldChoices are the models a connection's key listed, for the page. |
| 135 | func heldChoices(ctx context.Context, q querier, m metered.Conn) []wire.ModelChoice { |
| 136 | out, err := metered.Choices(ctx, q, m) |
| 137 | if err != nil || len(out) == 0 { |
| 138 | return nil |
| 139 | } |
| 140 | return out |
| 141 | } |
| 142 | |
| 143 | // withModel is a metered binding running the decision's model: the |
| 144 | // model, and the family of that model (§16.5: the pair, not the |
| 145 | // connection). |
| 146 | func withModel(b runner.AccountBinding, model, family string) runner.AccountBinding { |
| 147 | if !Metered(b) || model == "" { |
| 148 | return b |
| 149 | } |
| 150 | b.Model = model |
| 151 | if family == "" { |
| 152 | family = meteredFamily(b.Provider, model) |
| 153 | } |
| 154 | b.Family = family |
| 155 | return b |
| 156 | } |
| 157 | |
| 158 | // probeID is a first-use probe's durable sub-attempt (§16.4): |
| 159 | // probe:<step>:<attempt>:<model>, its model hashed when the whole would |
| 160 | // be longer than a usage frame may name. |
| 161 | func probeID(r stepRow, model string) string { |
| 162 | id := "probe:" + r.StepID + ":" + strconv.FormatInt(r.Attempt, 10) + ":" + model |
| 163 | if len(id) <= 200 { |
| 164 | return id |
| 165 | } |
| 166 | sum := sha256.Sum256([]byte(model)) |
| 167 | return "probe:" + r.StepID + ":" + strconv.FormatInt(r.Attempt, 10) + ":" + hex.EncodeToString(sum[:8]) |
| 168 | } |
| 169 | |
| 170 | // nextProbe is the next execution of a probe id, from a durable sequence |
| 171 | // committed before the probe runs: its usage attempt and its slot |
| 172 | // holder's, so a second probe under the same id is charged and settled |
| 173 | // as itself. |
| 174 | func (s *State) nextProbe(ctx context.Context, id string) (int64, error) { |
| 175 | var n int64 |
| 176 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 177 | if _, err := t.ExecContext(ctx, "INSERT INTO probe_seq(probe_id, n) VALUES(?, 1) ON CONFLICT(probe_id) DO UPDATE SET n = n + 1", id); err != nil { |
| 178 | return err |
| 179 | } |
| 180 | return t.QueryRowContext(ctx, "SELECT n FROM probe_seq WHERE probe_id=?", id).Scan(&n) |
| 181 | }) |
| 182 | return n, err |
| 183 | } |
| 184 | |
| 185 | // ProbeFunc probes model on a metered connection through the guard: |
| 186 | // admitted with admit (the scheduler's admission) written in the guard's |
| 187 | // transaction, its usage charged and reported under id, the model marked |
| 188 | // by its verdict, the slot released after. It returns the guard's |
| 189 | // admission and the probe's error (nil: answered by that model). |
| 190 | type ProbeFunc func(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) |
| 191 | |
| 192 | // probeFirst runs a step's first-use probe on the model Decide chose |
| 193 | // (§16.4), inside the admission the step itself would need: Decide's |
| 194 | // bars passed, the release consumed into the step revision's grant, the |
| 195 | // slot claimed. Whatever its verdict the slot is released and the step |
| 196 | // is decided again from fresh facts. Held by the guard, the step is held |
| 197 | // there. |
| 198 | func (c *Conns) probeFirst(ctx context.Context, r stepRow, d decision) (*wire.StepHold, error) { |
| 199 | m, ok, err := metered.Get(ctx, c.State.db, d.binding.LocalID) |
| 200 | if err != nil || !ok || c.Prober == nil { |
| 201 | return nil, firstErr(err, errors.New("no probe for this connection")) |
| 202 | } |
| 203 | adm, err := c.Prober(ctx, m, d.d.Model, probeID(r, d.d.Model), func(t *sql.Tx) error { return c.admitTx(ctx, t, r, d) }) |
| 204 | switch { |
| 205 | case errors.Is(err, errFactsMoved): |
| 206 | return nil, nil |
| 207 | case !adm.Admitted && adm.Hold != "" && adm.Hold != metered.HoldModel: |
| 208 | h := &wire.StepHold{Reason: adm.Hold, Connection: d.binding.ID, Provider: d.binding.Provider} |
| 209 | if !adm.WakeAt.IsZero() { |
| 210 | at := adm.WakeAt |
| 211 | h.WakeAt = &at |
| 212 | } |
| 213 | return h, nil |
| 214 | } |
| 215 | // Answered or not, the probe settled (or its model moved under it): |
| 216 | // decided again. |
| 217 | c.warn("model probe", err) |
| 218 | return nil, nil |
| 219 | } |
| 220 | |
| 221 | // engineerFamily is the family Engineering's attempt recorded, which |
| 222 | // Review's family rule reads (§16.5), never the connection's: the |
| 223 | // dispatch's (the instance's record of Engineering's step), else this |
| 224 | // runner's own admission record of the task's Engineering attempt on |
| 225 | // that connection, else the one family a subscription can run. A |
| 226 | // metered connection with neither record falls back to its first |
| 227 | // model's family (S1's one model): the rule as it was before S5b. |
| 228 | func (c *Conns) engineerFamily(ctx context.Context, r stepRow, engineer runner.AccountBinding) string { |
| 229 | if r.AvoidFamily != "" { |
| 230 | return r.AvoidFamily |
| 231 | } |
| 232 | var family string |
| 233 | err := c.State.db.QueryRowContext(ctx, "SELECT a.family FROM admissions a JOIN steps s ON s.step_id=a.step_id AND s.attempt=a.attempt WHERE s.task_id=? AND json_extract(s.body, '$.specialist')=? AND a.connection=? AND a.family<>'' ORDER BY a.at DESC LIMIT 1", r.TaskID, wire.SpecialistEngineering, engineer.ID).Scan(&family) |
| 234 | if err == nil && family != "" { |
| 235 | return family |
| 236 | } |
| 237 | return engineer.Family |
| 238 | } |
| 239 | |