oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package metered
2
3import (
4 "bytes"
5 "context"
6 "database/sql"
7 "encoding/json"
8 "errors"
9 "slices"
10 "strings"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16// A metered connection's allowed set (connectors spec rev 3.3, §16.1,
17// §16.4): metered_models holds one row per allowed model with its state
18// (unprobed, healthy, unhealthy), when and why it failed. The set is
19// the rows; metered_connections.models_revision is the set's revision,
20// which only rises. A removed model's row goes: it is never admitted
21// again, and a model allowed again starts unprobed.
22const modelsSchema = `
23CREATE TABLE IF NOT EXISTS metered_models (local_id TEXT NOT NULL, model TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'unprobed', failed_at TEXT NOT NULL DEFAULT '', reason TEXT NOT NULL DEFAULT '', PRIMARY KEY (local_id, model));
24`
25
26// RetryAfter is how long an unhealthy model waits before a step that
27// would pick it may probe it again (§16.4): on demand only, never by a
28// timer.
29const RetryAfter = 24 * time.Hour
30
31// HoldModel is the guard's answer when the attempt's model is not one it
32// may run on now: removed from the set, no longer eligible, or (for a
33// step) not proven healthy. A question fails with it
34// (model_unavailable); a step decides again.
35const HoldModel = wire.ReasonModelUnavailable
36
37// Model is one allowed model on a connection.
38type Model struct {
39 ID, State, Reason string
40 FailedAt time.Time
41}
42
43// Retryable reports whether an unhealthy model may be probed again on
44// demand at now: a day after it failed. A model_mismatch never is: it
45// stays unhealthy until Check again (§16.5).
46func (m Model) Retryable(now time.Time) bool {
47 return m.State == wire.ModelUnhealthy && m.Reason != wire.ModelMismatch && !m.FailedAt.IsZero() && !now.Before(m.FailedAt.Add(RetryAfter))
48}
49
50// Migrate brings an older thin.db to the allowed sets (§16.5): the
51// column, then every connection that has none yet. With a model picked
52// (S1's one model) the set is that model, healthy when the connection
53// was proven on it and unprobed otherwise, no time invented; with none
54// picked, every model that can be allowed, unprobed. Its revision is 1.
55func Migrate(ctx context.Context, db *sql.DB) error {
56 if _, err := db.ExecContext(ctx, modelsSchema); err != nil {
57 return err
58 }
59 for _, col := range []string{"models_revision INTEGER NOT NULL DEFAULT 0", "listed TEXT NOT NULL DEFAULT ''"} {
60 if _, err := db.ExecContext(ctx, "ALTER TABLE metered_connections ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") {
61 return err
62 }
63 }
64 tx, err := db.BeginTx(ctx, nil)
65 if err != nil {
66 return err
67 }
68 defer tx.Rollback()
69 conns, err := List(ctx, tx)
70 if err != nil {
71 return err
72 }
73 for _, c := range conns {
74 if c.ModelsRevision != 0 {
75 continue
76 }
77 var allowed []Model
78 if c.Model != "" {
79 state := wire.ModelUnprobed
80 if c.Validated {
81 state = wire.ModelHealthy
82 }
83 allowed = []Model{{ID: c.Model, State: state}}
84 } else if table, ok := TableFor(c.PriceVersion); ok {
85 for id := range table.Models {
86 if _, _, ok := Eligible(c.Provider, c.PriceVersion, id); ok {
87 allowed = append(allowed, Model{ID: id, State: wire.ModelUnprobed})
88 }
89 }
90 }
91 for _, m := range allowed {
92 if _, err := tx.ExecContext(ctx, "INSERT INTO metered_models(local_id, model, state) VALUES(?,?,?) ON CONFLICT DO NOTHING", c.LocalID, m.ID, m.State); err != nil {
93 return err
94 }
95 }
96 if _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET models_revision=1 WHERE local_id=? AND models_revision=0", c.LocalID); err != nil {
97 return err
98 }
99 }
100 return tx.Commit()
101}
102
103// SetListed records the models the key listed when it was last read
104// (at connect, and on Check again): the page's choices.
105func SetListed(ctx context.Context, tx *sql.Tx, local string, listed []string) error {
106 raw, err := json.Marshal(listed)
107 if err != nil {
108 return err
109 }
110 _, err = tx.ExecContext(ctx, "UPDATE metered_connections SET listed=? WHERE local_id=?", string(raw), local)
111 return err
112}
113
114// listedOf is the key's list as this runner last read it (nil: never
115// read, a connection from before S5b).
116func listedOf(ctx context.Context, q querier, local string) ([]string, error) {
117 var raw string
118 if err := q.QueryRowContext(ctx, "SELECT listed FROM metered_connections WHERE local_id=?", local).Scan(&raw); err != nil {
119 return nil, err
120 }
121 if raw == "" {
122 return nil, nil
123 }
124 var listed []string
125 if err := json.Unmarshal([]byte(raw), &listed); err != nil {
126 return nil, err
127 }
128 if listed == nil {
129 listed = []string{}
130 }
131 return listed, nil
132}
133
134// Choices are the models a connection's key listed, each with whether it
135// can be allowed now (priced in the connection's table, tiered now),
136// sorted; none when the list was never read (a connection from before
137// S5b, until Check again).
138func Choices(ctx context.Context, q querier, c Conn) ([]wire.ModelChoice, error) {
139 listed, err := listedOf(ctx, q, c.LocalID)
140 if err != nil {
141 return nil, err
142 }
143 slices.Sort(listed)
144 out := []wire.ModelChoice{}
145 for _, m := range slices.Compact(listed) {
146 t, _, ok := Eligible(c.Provider, c.PriceVersion, m)
147 out = append(out, wire.ModelChoice{ID: m, Eligible: ok, Family: t.Family, Tier: t.Tier})
148 }
149 return CapChoices(out), nil
150}
151
152// CapChoices bounds a key's list to what a card or hello may carry
153// (wire.MaxModels): the models that can be allowed first, then the rest,
154// each in its order.
155func CapChoices(cs []wire.ModelChoice) []wire.ModelChoice {
156 if len(cs) <= wire.MaxModels {
157 return cs
158 }
159 out := make([]wire.ModelChoice, 0, wire.MaxModels)
160 for _, eligible := range []bool{true, false} {
161 for _, c := range cs {
162 if c.Eligible == eligible && len(out) < wire.MaxModels {
163 out = append(out, c)
164 }
165 }
166 }
167 return out
168}
169
170// Models is a connection's allowed set, by model id.
171func Models(ctx context.Context, q querier, local string) ([]Model, error) {
172 rows, err := q.QueryContext(ctx, "SELECT model, state, failed_at, reason FROM metered_models WHERE local_id=? ORDER BY model", local)
173 if err != nil {
174 return nil, err
175 }
176 defer rows.Close()
177 var out []Model
178 for rows.Next() {
179 var m Model
180 var at string
181 if err := rows.Scan(&m.ID, &m.State, &at, &m.Reason); err != nil {
182 return nil, err
183 }
184 if at != "" {
185 m.FailedAt, _ = time.Parse(time.RFC3339Nano, at)
186 }
187 out = append(out, m)
188 }
189 return out, rows.Err()
190}
191
192// modelOf is one allowed model (false: not in the set).
193func modelOf(ctx context.Context, q querier, local, model string) (Model, bool, error) {
194 var m Model
195 var at string
196 err := q.QueryRowContext(ctx, "SELECT model, state, failed_at, reason FROM metered_models WHERE local_id=? AND model=?", local, model).Scan(&m.ID, &m.State, &at, &m.Reason)
197 if errors.Is(err, sql.ErrNoRows) {
198 return m, false, nil
199 }
200 if at != "" {
201 m.FailedAt, _ = time.Parse(time.RFC3339Nano, at)
202 }
203 return m, err == nil, err
204}
205
206// ErrNotAllowable: a set holds a model that cannot be allowed (not
207// eligible on this connection), or none.
208var ErrNotAllowable = errors.New("metered: a model in the set cannot be allowed")
209
210// SetModels applies a connection's allowed set at revision, in the
211// caller's transaction (§16.1): only above the revision held, only for
212// the connection the frame names, only a set of models that can be
213// allowed. Models kept keep their state, new ones start unprobed, and a
214// removed one goes (a step already running on it finishes). The
215// connection's one model (S1's, which an older instance shows) becomes
216// the cheapest allowed. It reports whether it applied.
217func SetModels(ctx context.Context, tx *sql.Tx, local, connection string, allowed []string, revision int64) (bool, error) {
218 c, ok, err := Get(ctx, tx, local)
219 if err != nil || !ok {
220 return false, firstErr(err, ErrNotMetered)
221 }
222 if c.Connection == "" || c.Connection != connection || revision <= c.ModelsRevision {
223 return false, nil
224 }
225 if !wire.ValidAllowed(allowed) {
226 return false, ErrNotAllowable
227 }
228 for _, m := range allowed {
229 if _, _, ok := Eligible(c.Provider, c.PriceVersion, m); !ok {
230 return false, ErrNotAllowable
231 }
232 }
233 // Only models the key lists (§16.1), from the list this runner read,
234 // in this transaction. A connection from before S5b has no list until
235 // Check again reads one: its set may shrink or stay, never grow.
236 listed, err := listedOf(ctx, tx, local)
237 if err != nil {
238 return false, err
239 }
240 held, err := Models(ctx, tx, local)
241 if err != nil {
242 return false, err
243 }
244 for _, m := range allowed {
245 if listed != nil && !slices.Contains(listed, m) || listed == nil && !slices.ContainsFunc(held, func(h Model) bool { return h.ID == m }) {
246 return false, ErrNotAllowable
247 }
248 }
249 // The revision moves first, bound to the connection and above the
250 // one held, so a frame that does not bind changes no row.
251 res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET models_revision=?, model=? WHERE local_id=? AND connection=? AND models_revision<?", revision, Cheapest(c.Provider, c.PriceVersion, allowed), local, connection, revision)
252 if err != nil {
253 return false, err
254 }
255 if n, err := res.RowsAffected(); err != nil || n != 1 {
256 return false, err
257 }
258 for _, m := range held {
259 if !slices.Contains(allowed, m.ID) {
260 if _, err := tx.ExecContext(ctx, "DELETE FROM metered_models WHERE local_id=? AND model=?", local, m.ID); err != nil {
261 return false, err
262 }
263 }
264 }
265 for _, m := range allowed {
266 if _, err := tx.ExecContext(ctx, "INSERT INTO metered_models(local_id, model, state) VALUES(?,?,?) ON CONFLICT DO NOTHING", local, m, wire.ModelUnprobed); err != nil {
267 return false, err
268 }
269 }
270 return true, nil
271}
272
273// InitModels records a new connection's allowed set (its first revision)
274// in the caller's transaction, every model unprobed: the connect-time
275// proof then runs on the cheapest (§16.1).
276func InitModels(ctx context.Context, tx *sql.Tx, local string, allowed []string, revision int64) error {
277 if _, err := tx.ExecContext(ctx, "DELETE FROM metered_models WHERE local_id=?", local); err != nil {
278 return err
279 }
280 for _, m := range allowed {
281 if _, err := tx.ExecContext(ctx, "INSERT INTO metered_models(local_id, model, state) VALUES(?,?,?)", local, m, wire.ModelUnprobed); err != nil {
282 return err
283 }
284 }
285 _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET models_revision=? WHERE local_id=?", revision, local)
286 return err
287}
288
289// MarkModel records a model's probe or step verdict: healthy, or
290// unhealthy at now with why. A model no longer in the set is left alone.
291func MarkModel(ctx context.Context, tx *sql.Tx, local, model, state, reason string, now time.Time) error {
292 at := ""
293 if state != wire.ModelHealthy {
294 at = stamp(now)
295 } else {
296 reason = ""
297 }
298 _, err := tx.ExecContext(ctx, "UPDATE metered_models SET state=?, failed_at=?, reason=? WHERE local_id=? AND model=?", state, at, reason, local, model)
299 return err
300}
301
302// Cheaper orders two models of one provider by their price, the
303// connect-time proof's and the choice's tie rule (§16.3): the lower
304// output price, then the lower input price, then the id bytewise. An
305// unpriced model sorts last.
306func Cheaper(a, b string, pa, pb Price, okA, okB bool) bool {
307 if okA != okB {
308 return okA
309 }
310 if okA {
311 oa, ob, ia, ib := deref(pa.Output), deref(pb.Output), deref(pa.UncachedInput), deref(pb.UncachedInput)
312 if oa != ob {
313 return oa < ob
314 }
315 if ia != ib {
316 return ia < ib
317 }
318 }
319 return bytes.Compare([]byte(a), []byte(b)) < 0
320}
321
322func deref(v *int64) int64 {
323 if v == nil {
324 return 0
325 }
326 return *v
327}
328
329// Cheapest is the cheapest of models on a connection's price table
330// ("" for none): the connect-time proof's model.
331func Cheapest(provider, priceVersion string, models []string) string {
332 table, _ := TableFor(priceVersion)
333 best, bp, bok := "", Price{}, false
334 for _, m := range models {
335 p, ok := table.Models[m]
336 if best == "" || Cheaper(m, best, p, bp, ok, bok) {
337 best, bp, bok = m, p, ok
338 }
339 }
340 return best
341}
342
343// admitModel is the guard's model check (§16.6 (a), (g)): the attempt's
344// model is in the set and priced; a step's is eligible and healthy, so a
345// step never launches on a model whose first-use probe has not settled
346// healthy; a probe's is eligible in any state; a question's is not
347// unhealthy (it stays on its session's model or fails).
348func admitModel(ctx context.Context, q querier, c Conn, h Holder) (bool, error) {
349 if h.Model == "" {
350 // Only S1's flows name no model: none admits a step or a question
351 // on a connection with an allowed set.
352 return h.Role == RoleProbe, nil
353 }
354 m, ok, err := modelOf(ctx, q, c.LocalID, h.Model)
355 if err != nil || !ok {
356 return false, err
357 }
358 _, _, eligible := Eligible(c.Provider, c.PriceVersion, h.Model)
359 table, _ := TableFor(c.PriceVersion)
360 switch h.Role {
361 case RoleProbe:
362 return eligible, nil
363 case RoleAsk:
364 return table.Priced(h.Model) && m.State != wire.ModelUnhealthy, nil
365 }
366 return eligible && m.State == wire.ModelHealthy, nil
367}
368