package store import ( "context" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "errors" "time" "github.com/google/uuid" "pageswiki/internal/db" "pageswiki/internal/machinelearning" ) var ErrMLBudget = errors.New("machine learning daily input budget exhausted or not configured") var ErrMLAlreadyReserved = errors.New("machine learning request already reserved; do not resend") var mlBudgetStatements = []string{ `CREATE TABLE ml_daily_budget(domain_uuid TEXT NOT NULL,day TEXT NOT NULL,reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>=0),PRIMARY KEY(domain_uuid,day))`, `CREATE TABLE ml_budget_receipts(domain_uuid TEXT NOT NULL,request_uuid TEXT NOT NULL,day TEXT NOT NULL,input_hash TEXT NOT NULL,generation TEXT NOT NULL,reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>0),state TEXT NOT NULL CHECK(state IN ('reserved','completed','unknown')),actual_tokens BIGINT NOT NULL DEFAULT 0 CHECK(actual_tokens>=0),PRIMARY KEY(domain_uuid,request_uuid))`, } var mlBudgetMigrations = []db.SQLMigration{{Version: 1, Name: "ML daily reservations", Statements: mlBudgetStatements, Assertions: []string{ schemaColumns("ml_daily_budget", "domain_uuid,day,reserved_bytes"), schemaUnique("ml_daily_budget", "domain_uuid,day"), schemaColumns("ml_budget_receipts", "domain_uuid,request_uuid,day,input_hash,generation,reserved_bytes,state,actual_tokens"), schemaUnique("ml_budget_receipts", "domain_uuid,request_uuid"), }}} // Explicit preparation for the future worker. Not called by ordinary settings // reads/writes, and not automatically applied to production on this change. func (s *Store) EnsureMLBudgetSchema(ctx context.Context) error { if s.sqlBackend == storeMySQL { return errors.New("use isolated MySQL ML schema preparation") } if s.sqlBackend == storePostgreSQL { return db.ApplyPostgreSQLMigrations(ctx, s.DB, "machine-learning-budget", []db.PostgreSQLMigration{{Version: 1, Name: "ML daily reservations", Statements: mlBudgetStatements}}) } return db.ApplySQLiteMigrations(ctx, s.DB, "machine-learning-budget", mlBudgetMigrations) } // ReserveMLInput prepares a request from CURRENT settings and reserves its byte // cost atomically. Caller must authorize the document and learning cohort first. // A returned request is permission for ONE attempt, never a retry receipt. func (s *Store) ReserveMLInput(ctx context.Context, domain, requestID, logicalPath, generation string, inputs []machinelearning.Input) (machinelearning.Request, error) { return s.reserveMLInputAt(ctx, domain, requestID, logicalPath, generation, inputs, time.Now()) } func (s *Store) reserveMLInputAt(ctx context.Context, domain, requestID, logicalPath, generation string, inputs []machinelearning.Input, now time.Time) (machinelearning.Request, error) { var empty machinelearning.Request id, e := uuid.Parse(requestID) if e != nil || id.String() != requestID { return empty, machinelearning.ErrPolicy } var options *sql.TxOptions if s.sqlBackend != storeSQLite { options = &sql.TxOptions{Isolation: sql.LevelReadCommitted} } tx, e := s.DB.BeginTx(ctx, options) if e != nil { return empty, e } defer tx.Rollback() // Lock the same configuration row that settings updates modify. This also // serializes budget writers across processes, including policy generations. if s.sqlBackend == storeSQLite { if _, e = tx.ExecContext(ctx, `UPDATE config SET value=value WHERE domain_uuid=? AND key=?`, domain, machineLearningConfigKey); e != nil { return empty, e } } var raw string lockQuery := `SELECT value FROM config WHERE domain_uuid=` + s.sqlParam(1) + ` AND ` + s.sqlConfigKey() + `=` + s.sqlParam(2) if s.sqlBackend != storeSQLite { lockQuery += ` FOR UPDATE` } if e = tx.QueryRowContext(ctx, lockQuery, domain, machineLearningConfigKey).Scan(&raw); e != nil { if errors.Is(e, sql.ErrNoRows) { return empty, machinelearning.ErrNotAllowed } return empty, e } var p machinelearning.Policy if json.Unmarshal([]byte(raw), &p) != nil { return empty, machinelearning.ErrPolicy } req, e := p.Prepare(domain, logicalPath, generation, inputs) if e != nil { return empty, e } if p.DailyInputBytes <= 0 { return empty, ErrMLBudget } var oldHash string e = tx.QueryRowContext(ctx, `SELECT input_hash FROM ml_budget_receipts WHERE domain_uuid=`+s.sqlParam(1)+` AND request_uuid=`+s.sqlParam(2), domain, requestID).Scan(&oldHash) if e == nil { return empty, ErrMLAlreadyReserved } if !errors.Is(e, sql.ErrNoRows) { return empty, e } day := now.UTC().Format("2006-01-02") var used int64 e = tx.QueryRowContext(ctx, `SELECT reserved_bytes FROM ml_daily_budget WHERE domain_uuid=`+s.sqlParam(1)+` AND day=`+s.sqlParam(2), domain, day).Scan(&used) if e != nil && !errors.Is(e, sql.ErrNoRows) { return empty, e } var cost int64 for _, input := range req.Inputs { cost += int64(len(input.Text)) } if used > p.DailyInputBytes || cost > p.DailyInputBytes-used { return empty, ErrMLBudget } budgetQuery := `INSERT INTO ml_daily_budget(domain_uuid,day,reserved_bytes) VALUES (` + s.sqlValues(3) + `) ON CONFLICT(domain_uuid,day) DO UPDATE SET reserved_bytes=excluded.reserved_bytes` args := []any{domain, day, used + cost} if s.sqlBackend == storeMySQL { budgetQuery = `INSERT INTO ml_daily_budget(domain_uuid,day,reserved_bytes) VALUES (?,?,?) ON DUPLICATE KEY UPDATE reserved_bytes=?` args = append(args, used+cost) } _, e = tx.ExecContext(ctx, budgetQuery, args...) if e != nil { return empty, e } encoded, e := json.Marshal(req) if e != nil { return empty, e } hash := sha256.Sum256(encoded) _, e = tx.ExecContext(ctx, `INSERT INTO ml_budget_receipts(domain_uuid,request_uuid,day,input_hash,generation,reserved_bytes,state) VALUES (`+s.sqlValues(7)+`)`, domain, requestID, day, hex.EncodeToString(hash[:]), generation, cost, "reserved") if e != nil { return empty, e } if e = tx.Commit(); e != nil { return empty, e } return req, nil } // FinishMLInput does not release reservations, including on timeout/crash. // Actual token usage is informational and never increases the byte allowance. func (s *Store) FinishMLInput(ctx context.Context, domain, requestID string, completed bool, actualTokens int64) error { if actualTokens < 0 { return machinelearning.ErrPolicy } state := "unknown" if completed { state = "completed" } r, e := s.DB.ExecContext(ctx, `UPDATE ml_budget_receipts SET state=`+s.sqlParam(1)+`,actual_tokens=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND request_uuid=`+s.sqlParam(4)+` AND state='reserved'`, state, actualTokens, domain, requestID) if e != nil { return e } n, e := r.RowsAffected() if e != nil { return e } if n != 1 { return ErrMLAlreadyReserved } return nil }