package thin import ( "context" "crypto/sha256" "database/sql" "encoding/hex" "errors" "strconv" "strings" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/schedule" "amadan.net/oficina/equipo/internal/wire" ) // Models chosen per step on the runner (connectors spec rev 3.3, §16, // slice S5b). A metered connection allows a set of models; Decide picks // one (connection, model) pair per step. A model never answered yet is // probed first, inside the step's own admission, and the step is then // decided again from fresh facts. Every admission records the model, // family, tier and table versions it chose, and every kept session the // model and family it was created on. // maxProbes bounds the first-use probes one admission runs before the // step is held briefly and looked at again. const maxProbes = 3 // keptRef is the session a step resumes: its connection and the model // it was created on ("" for a subscription's own). type keptRef struct { Conn, Model string } // migrateModels brings thin.db to S5b (§16.5): the allowed sets (each // single-model connection's set is its one model), the admission and // kept-session columns, and their backfill from the connection's one // model, which was the only model it could run. Tiers are not // backfilled: no tier table existed when those attempts ran. func migrateModels(ctx context.Context, d *sql.DB) error { if err := metered.Migrate(ctx, d); err != nil { return err } if _, err := d.ExecContext(ctx, "CREATE TABLE IF NOT EXISTS probe_seq (probe_id TEXT PRIMARY KEY, n INTEGER NOT NULL)"); err != nil { return err } for _, add := range []struct{ table, col string }{ {"admissions", "model"}, {"admissions", "family"}, {"admissions", "tier"}, {"admissions", "price_version"}, {"admissions", "tier_version"}, {"kept_sessions", "model"}, {"kept_sessions", "family"}, {"connect_attempts", "allowed"}, } { 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") { return err } } conns, err := metered.List(ctx, d) if err != nil { return err } for _, m := range conns { if m.Model == "" { continue } family := meteredFamily(m.Provider, m.Model) 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 { return err } if _, err := d.ExecContext(ctx, "UPDATE kept_sessions SET model=?, family=? WHERE account=? AND model=''", m.Model, family, m.LocalID); err != nil { return err } } return nil } // meteredModels are a metered connection's eligible models as Decide // reads them (§16.3): allowed, priced in the connection's table and // tiered now, and not unhealthy; an unhealthy one a day after it failed // is offered as unprobed (a retry on demand, never by a timer). func meteredModels(ctx context.Context, q querier, m metered.Conn, now time.Time) ([]schedule.Model, error) { allowed, err := metered.Models(ctx, q, m.LocalID) if err != nil { return nil, err } out := []schedule.Model{} for _, a := range allowed { t, p, ok := metered.Eligible(m.Provider, m.PriceVersion, a.ID) if !ok { continue } sm := schedule.Model{ID: a.ID, Family: t.Family, Tier: t.Tier, Output: value(p.Output), Input: value(p.UncachedInput)} switch { case a.State == wire.ModelHealthy: case a.State == wire.ModelUnprobed, a.Retryable(now): sm.Unprobed = true default: continue } out = append(out, sm) } return out, nil } func value(v *int64) int64 { if v == nil { return 0 } return *v } // heldModels are a metered connection's allowed set as hello and sync // carry it (ProtocolModels). func heldModels(ctx context.Context, q querier, m metered.Conn) []wire.ModelState { allowed, err := metered.Models(ctx, q, m.LocalID) if err != nil { return nil } out := []wire.ModelState{} for _, a := range allowed { s := wire.ModelState{ID: a.ID, State: a.State, Reason: a.Reason} if !a.FailedAt.IsZero() { at := a.FailedAt s.FailedAt = &at } if t, ok := metered.TierOf(m.Provider, a.ID); ok { s.Family, s.Tier = t.Family, t.Tier } out = append(out, s) } return out } // heldChoices are the models a connection's key listed, for the page. func heldChoices(ctx context.Context, q querier, m metered.Conn) []wire.ModelChoice { out, err := metered.Choices(ctx, q, m) if err != nil || len(out) == 0 { return nil } return out } // withModel is a metered binding running the decision's model: the // model, and the family of that model (§16.5: the pair, not the // connection). func withModel(b runner.AccountBinding, model, family string) runner.AccountBinding { if !Metered(b) || model == "" { return b } b.Model = model if family == "" { family = meteredFamily(b.Provider, model) } b.Family = family return b } // probeID is a first-use probe's durable sub-attempt (§16.4): // probe:::, its model hashed when the whole would // be longer than a usage frame may name. func probeID(r stepRow, model string) string { id := "probe:" + r.StepID + ":" + strconv.FormatInt(r.Attempt, 10) + ":" + model if len(id) <= 200 { return id } sum := sha256.Sum256([]byte(model)) return "probe:" + r.StepID + ":" + strconv.FormatInt(r.Attempt, 10) + ":" + hex.EncodeToString(sum[:8]) } // nextProbe is the next execution of a probe id, from a durable sequence // committed before the probe runs: its usage attempt and its slot // holder's, so a second probe under the same id is charged and settled // as itself. func (s *State) nextProbe(ctx context.Context, id string) (int64, error) { var n int64 err := s.tx(ctx, func(t *sql.Tx) error { 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 { return err } return t.QueryRowContext(ctx, "SELECT n FROM probe_seq WHERE probe_id=?", id).Scan(&n) }) return n, err } // ProbeFunc probes model on a metered connection through the guard: // admitted with admit (the scheduler's admission) written in the guard's // transaction, its usage charged and reported under id, the model marked // by its verdict, the slot released after. It returns the guard's // admission and the probe's error (nil: answered by that model). type ProbeFunc func(ctx context.Context, conn metered.Conn, model, id string, admit func(*sql.Tx) error) (metered.Admission, error) // probeFirst runs a step's first-use probe on the model Decide chose // (§16.4), inside the admission the step itself would need: Decide's // bars passed, the release consumed into the step revision's grant, the // slot claimed. Whatever its verdict the slot is released and the step // is decided again from fresh facts. Held by the guard, the step is held // there. func (c *Conns) probeFirst(ctx context.Context, r stepRow, d decision) (*wire.StepHold, error) { m, ok, err := metered.Get(ctx, c.State.db, d.binding.LocalID) if err != nil || !ok || c.Prober == nil { return nil, firstErr(err, errors.New("no probe for this connection")) } 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) }) switch { case errors.Is(err, errFactsMoved): return nil, nil case !adm.Admitted && adm.Hold != "" && adm.Hold != metered.HoldModel: h := &wire.StepHold{Reason: adm.Hold, Connection: d.binding.ID, Provider: d.binding.Provider} if !adm.WakeAt.IsZero() { at := adm.WakeAt h.WakeAt = &at } return h, nil } // Answered or not, the probe settled (or its model moved under it): // decided again. c.warn("model probe", err) return nil, nil } // engineerFamily is the family Engineering's attempt recorded, which // Review's family rule reads (§16.5), never the connection's: the // dispatch's (the instance's record of Engineering's step), else this // runner's own admission record of the task's Engineering attempt on // that connection, else the one family a subscription can run. A // metered connection with neither record falls back to its first // model's family (S1's one model): the rule as it was before S5b. func (c *Conns) engineerFamily(ctx context.Context, r stepRow, engineer runner.AccountBinding) string { if r.AvoidFamily != "" { return r.AvoidFamily } var family string 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) if err == nil && family != "" { return family } return engineer.Family }