Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stats auto refresh #7424

Merged
merged 30 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
cc82f99
Stats auto refresh prototype
max-hoffman Jan 26, 2024
0cf91c9
fix bugs
max-hoffman Jan 27, 2024
340e43c
test stats update
max-hoffman Jan 27, 2024
f180d20
add tests, fix bugs
max-hoffman Jan 30, 2024
b17bdcf
fix test
max-hoffman Jan 30, 2024
023cf59
fmt
max-hoffman Jan 30, 2024
97d8a04
delete test
max-hoffman Jan 30, 2024
49d78e9
more tests
max-hoffman Jan 30, 2024
81dba2b
delete table test
max-hoffman Jan 30, 2024
5edf046
[ga-format-pr] Run go/utils/repofmt/format_repo.sh and go/Godeps/upda…
max-hoffman Jan 30, 2024
adbcabc
add and delete stats hooks
max-hoffman Jan 30, 2024
641ca04
fmt
max-hoffman Jan 30, 2024
38392dd
Merge branch 'max/stats-refresh' of github.com:dolthub/dolt into max/…
max-hoffman Jan 30, 2024
b5c93ad
concurrency improvements
max-hoffman Feb 1, 2024
5288c1b
[ga-format-pr] Run go/utils/repofmt/format_repo.sh and go/Godeps/upda…
max-hoffman Feb 1, 2024
bfcff4f
write bug
max-hoffman Feb 1, 2024
9393f63
more tests and stats functions
max-hoffman Feb 6, 2024
88690cb
Merge branch 'max/stats-refresh' of github.com:dolthub/dolt into max/…
max-hoffman Feb 6, 2024
ad35847
Merge branch 'main' into max/stats-refresh
max-hoffman Feb 6, 2024
49b59b2
working dolt_stat funcs
max-hoffman Feb 6, 2024
1d8830f
test fixes
max-hoffman Feb 6, 2024
e61f88e
merge main
max-hoffman Feb 6, 2024
dedbf19
bump
max-hoffman Feb 6, 2024
7198173
fmt
max-hoffman Feb 6, 2024
1979f9b
fix wg panic
max-hoffman Feb 7, 2024
bbfbc36
merge main
max-hoffman Feb 7, 2024
18fd075
[ga-format-pr] Run go/utils/repofmt/format_repo.sh and go/Godeps/upda…
max-hoffman Feb 7, 2024
f3e6243
merge main
max-hoffman Feb 7, 2024
be41ce9
Merge branch 'max/stats-refresh' of github.com:dolthub/dolt into max/…
max-hoffman Feb 7, 2024
f09626b
nick comments
max-hoffman Feb 7, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 9 additions & 33 deletions go/cmd/dolt/commands/engine/sqlengine.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"runtime"
"strconv"
"strings"
"time"

gms "github.com/dolthub/go-mysql-server"
"github.com/dolthub/go-mysql-server/eventscheduler"
Expand All @@ -29,7 +28,6 @@ import (
"github.com/dolthub/go-mysql-server/sql/binlogreplication"
"github.com/dolthub/go-mysql-server/sql/mysql_db"
"github.com/dolthub/go-mysql-server/sql/rowexec"
types2 "github.com/dolthub/go-mysql-server/sql/types"
_ "github.com/dolthub/go-mysql-server/sql/variables"
"github.com/sirupsen/logrus"

Expand Down Expand Up @@ -181,14 +179,19 @@ func NewSqlEngine(
"authentication_dolt_jwt": NewAuthenticateDoltJWTPlugin(config.JwksConfig),
})

statsPro := stats.NewProvider()
engine.Analyzer.Catalog.StatsProvider = statsPro

engine.Analyzer.ExecBuilder = rowexec.DefaultBuilder
sessFactory := doltSessionFactory(pro, mrEnv.Config(), bcController, config.Autocommit)
sessFactory := doltSessionFactory(pro, statsPro, mrEnv.Config(), bcController, config.Autocommit)
sqlEngine.provider = pro
sqlEngine.contextFactory = sqlContextFactory()
sqlEngine.dsessFactory = sessFactory
sqlEngine.engine = engine

if err = configureStatsProvider(ctx, sqlEngine, bThreads, pro, dbs); err != nil {
// configuring stats depends on sessionBuilder
// sessionBuilder needs ref to statsProv
if err = statsPro.Configure(ctx, sqlEngine.NewDefaultContext, bThreads, pro, dbs); err != nil {
return nil, err
}

Expand Down Expand Up @@ -379,33 +382,6 @@ func configureEventScheduler(config *SqlEngineConfig, engine *gms.Engine, sessFa
return engine.InitializeEventScheduler(getCtxFunc, config.EventSchedulerStatus, eventSchedulerPeriod)
}

func configureStatsProvider(ctx context.Context, sqlEngine *SqlEngine, bThreads *sql.BackgroundThreads, pro *dsqle.DoltDatabaseProvider, dbs []dsess.SqlDatabase) error {
sqlEngine.engine.Analyzer.Catalog.StatsProvider = stats.NewProvider()
statsProv := sqlEngine.engine.Analyzer.Catalog.StatsProvider.(*stats.Provider)
loadCtx, err := sqlEngine.NewDefaultContext(ctx)
if err != nil {
return err
}
if err := statsProv.Load(loadCtx, dbs); err != nil {
return err
}
if _, enabled, _ := sql.SystemVariables.GetGlobal(dsess.DoltStatsAutoRefreshEnabled); enabled == int8(1) {
_, threshold, _ := sql.SystemVariables.GetGlobal(dsess.DoltStatsAutoRefreshThreshold)
_, interval, _ := sql.SystemVariables.GetGlobal(dsess.DoltStatsAutoRefreshInterval)
interval64, _, _ := types2.Int64.Convert(interval)
intervalSec := time.Second * time.Duration(interval64.(int64))
thresholdf64 := threshold.(float64)
for _, db := range dbs {
if err := statsProv.ConfigureAutoRefresh(sqlEngine.NewDefaultContext, db.Name(), db.DbData().Ddb, pro, bThreads, intervalSec, thresholdf64); err != nil {
return err
}
}
pro.InitDatabaseHook = stats.NewInitDatabaseHook(statsProv, sqlEngine.NewDefaultContext, pro, bThreads, intervalSec, thresholdf64, pro.InitDatabaseHook)
pro.DropDatabaseHook = stats.NewDropDatabaseHook(statsProv, pro.DropDatabaseHook)
}
return nil
}

// sqlContextFactory returns a contextFactory that creates a new sql.Context with the initial database provided
func sqlContextFactory() contextFactory {
return func(ctx context.Context, session sql.Session) (*sql.Context, error) {
Expand All @@ -415,9 +391,9 @@ func sqlContextFactory() contextFactory {
}

// doltSessionFactory returns a sessionFactory that creates a new DoltSession
func doltSessionFactory(pro *dsqle.DoltDatabaseProvider, config config.ReadWriteConfig, bc *branch_control.Controller, autocommit bool) sessionFactory {
func doltSessionFactory(pro *dsqle.DoltDatabaseProvider, statsPro sql.StatsProvider, config config.ReadWriteConfig, bc *branch_control.Controller, autocommit bool) sessionFactory {
return func(mysqlSess *sql.BaseSession, provider sql.DatabaseProvider) (*dsess.DoltSession, error) {
doltSession, err := dsess.NewDoltSession(mysqlSess, pro, config, bc)
doltSession, err := dsess.NewDoltSession(mysqlSess, pro, config, bc, statsPro)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion go/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ require (
github.com/cespare/xxhash v1.1.0
github.com/creasty/defaults v1.6.0
github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2
github.com/dolthub/go-mysql-server v0.17.1-0.20240207124505-c0f397a6aaca
github.com/dolthub/go-mysql-server v0.17.1-0.20240207160654-5ed05eb1cc4b
github.com/dolthub/swiss v0.1.0
github.com/goccy/go-json v0.10.2
github.com/google/go-github/v57 v57.0.0
Expand Down
4 changes: 2 additions & 2 deletions go/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,8 @@ github.com/dolthub/fslock v0.0.3 h1:iLMpUIvJKMKm92+N1fmHVdxJP5NdyDK5bK7z7Ba2s2U=
github.com/dolthub/fslock v0.0.3/go.mod h1:QWql+P17oAAMLnL4HGB5tiovtDuAjdDTPbuqx7bYfa0=
github.com/dolthub/go-icu-regex v0.0.0-20230524105445-af7e7991c97e h1:kPsT4a47cw1+y/N5SSCkma7FhAPw7KeGmD6c9PBZW9Y=
github.com/dolthub/go-icu-regex v0.0.0-20230524105445-af7e7991c97e/go.mod h1:KPUcpx070QOfJK1gNe0zx4pA5sicIK1GMikIGLKC168=
github.com/dolthub/go-mysql-server v0.17.1-0.20240207124505-c0f397a6aaca h1:tI3X4fIUTOT0N8n+GYkPNa384WlJoOBcztK5c5mBzjU=
github.com/dolthub/go-mysql-server v0.17.1-0.20240207124505-c0f397a6aaca/go.mod h1:ANK0a6tyjrZ2cOzDJT3nFsDp80xksI4UfeijFlvnjwE=
github.com/dolthub/go-mysql-server v0.17.1-0.20240207160654-5ed05eb1cc4b h1:FDNaFIT63vRLfn6cTOr0rsgceMlFeuulaUru54HqIIg=
github.com/dolthub/go-mysql-server v0.17.1-0.20240207160654-5ed05eb1cc4b/go.mod h1:ANK0a6tyjrZ2cOzDJT3nFsDp80xksI4UfeijFlvnjwE=
github.com/dolthub/ishell v0.0.0-20221214210346-d7db0b066488 h1:0HHu0GWJH0N6a6keStrHhUAK5/o9LVfkh44pvsV4514=
github.com/dolthub/ishell v0.0.0-20221214210346-d7db0b066488/go.mod h1:ehexgi1mPxRTk0Mok/pADALuHbvATulTh6gzr7NzZto=
github.com/dolthub/jsonpath v0.0.2-0.20240201003050-392940944c15 h1:sfTETOpsrNJPDn2KydiCtDgVu6Xopq8k3JP8PjFT22s=
Expand Down
10 changes: 10 additions & 0 deletions go/libraries/doltcore/doltdb/doltdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -1744,6 +1744,16 @@ func (ddb *DoltDB) SetStatisics(ctx context.Context, addr hash.Hash) error {
return err
}

func (ddb *DoltDB) DropStatisics(ctx context.Context) error {
statsDs, err := ddb.db.GetDataset(ctx, ref.NewStatsRef().String())

_, err = ddb.db.Delete(ctx, statsDs, "")
if err != nil {
return err
}
return nil
}

var ErrNoStatistics = errors.New("no statistics found")

// GetStatistics returns the value of the singleton ref.StatsRef for this database
Expand Down
4 changes: 4 additions & 0 deletions go/libraries/doltcore/sqle/database_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,10 @@ func (p *DoltDatabaseProvider) ListDroppedDatabases(ctx *sql.Context) ([]string,
return p.droppedDatabaseManager.ListDroppedDatabases(ctx)
}

func (p *DoltDatabaseProvider) DbFactoryUrl() string {
return p.dbFactoryUrl
}

func (p *DoltDatabaseProvider) UndropDatabase(ctx *sql.Context, name string) (err error) {
p.mu.Lock()
defer p.mu.Unlock()
Expand Down
5 changes: 5 additions & 0 deletions go/libraries/doltcore/sqle/dprocedures/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ var DoltProcedures = []sql.ExternalStoredProcedureDetails{
{Name: "dolt_revert", Schema: int64Schema("status"), Function: doltRevert},
{Name: "dolt_tag", Schema: int64Schema("status"), Function: doltTag},
{Name: "dolt_verify_constraints", Schema: int64Schema("violations"), Function: doltVerifyConstraints},

{Name: "dolt_stats_drop", Schema: doltMergeSchema, Function: statsFunc("drop")},
{Name: "dolt_stats_restart", Schema: doltMergeSchema, Function: statsFunc("restart")},
{Name: "dolt_stats_stop", Schema: doltMergeSchema, Function: statsFunc("stop")},
{Name: "dolt_stats_status", Schema: doltMergeSchema, Function: statsFunc("status")},
}

// stringSchema returns a non-nullable schema with all columns as LONGTEXT.
Expand Down
123 changes: 123 additions & 0 deletions go/libraries/doltcore/sqle/dprocedures/stats_funcs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Copyright 2024 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dprocedures

import (
"fmt"
"strings"

"github.com/dolthub/go-mysql-server/sql"

"github.com/dolthub/dolt/go/libraries/doltcore/env"
"github.com/dolthub/dolt/go/libraries/doltcore/ref"
"github.com/dolthub/dolt/go/libraries/doltcore/sqle/dsess"
)

func statsFunc(name string) func(ctx *sql.Context, args ...string) (sql.RowIter, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switching on the string here feels unnecessary. Can't DoltProcedures just do something like:

{Name: "dolt_stats_drop", Schema: doltMergeSchema, Function: statsFunc(statsDrop)},

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep good idea

var fn func(*sql.Context) (interface{}, error)
switch name {
case "drop":
fn = statsDrop
case "restart":
fn = statsRestart
case "stop":
fn = statsStop
case "status":
fn = statsStatus
}
return func(ctx *sql.Context, args ...string) (sql.RowIter, error) {
res, err := fn(ctx)
if err != nil {
return nil, err
}
return rowToIter(res), nil
}
}

// AutoRefreshStatsProvider is a sql.StatsProvider that exposes hooks for
// observing and manipulating background database auto refresh threads.
type AutoRefreshStatsProvider interface {
sql.StatsProvider
CancelRefreshThread(string)
StartRefreshThread(*sql.Context, dsess.DoltDatabaseProvider, string, *env.DoltEnv) error
ThreadStatus(string) string
}

// statsRestart tries to stop and then start a refresh thread
func statsRestart(ctx *sql.Context) (interface{}, error) {
dSess := dsess.DSessFromSess(ctx.Session)
statsPro := dSess.StatsProvider()
dbName := strings.ToLower(ctx.GetCurrentDatabase())

if afp, ok := statsPro.(AutoRefreshStatsProvider); ok {
pro := dSess.Provider()
newFs, err := pro.FileSystem().WithWorkingDir(dbName)
if err != nil {
return nil, fmt.Errorf("failed to restart stats collection: %w", err)
}

dEnv := env.Load(ctx, env.GetCurrentUserHomeDir, newFs, pro.DbFactoryUrl(), "TODO")

afp.CancelRefreshThread(dbName)

err = afp.StartRefreshThread(ctx, pro, dbName, dEnv)
if err != nil {
return nil, fmt.Errorf("failed to restart collection: %w", err)
}
return fmt.Sprintf("restarted stats collection: %s", ref.StatsRef{}.String()), nil
}
return nil, nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return nil, nil
return nil, fmt.Errorf("provider does not implement AutoRefreshStatsProvider")

}

// statsStatus returns the last update for a stats thread
func statsStatus(ctx *sql.Context) (interface{}, error) {
dSess := dsess.DSessFromSess(ctx.Session)
dbName := strings.ToLower(ctx.GetCurrentDatabase())
pro := dSess.StatsProvider()
if afp, ok := pro.(AutoRefreshStatsProvider); ok {
return afp.ThreadStatus(dbName), nil
}
return nil, fmt.Errorf("provider does not implement AutoRefreshStatsProvider")
}

// statsStop cancels a refresh thread
func statsStop(ctx *sql.Context) (interface{}, error) {
dSess := dsess.DSessFromSess(ctx.Session)
statsPro := dSess.StatsProvider()
dbName := strings.ToLower(ctx.GetCurrentDatabase())

if afp, ok := statsPro.(AutoRefreshStatsProvider); ok {
afp.CancelRefreshThread(dbName)
return fmt.Sprintf("stopped thread: %s", dbName), nil
}
return nil, fmt.Errorf("provider does not implement AutoRefreshStatsProvider")
}

// statsDrop deletes the stats ref
func statsDrop(ctx *sql.Context) (interface{}, error) {
dSess := dsess.DSessFromSess(ctx.Session)
pro := dSess.StatsProvider()
dbName := strings.ToLower(ctx.GetCurrentDatabase())

if afp, ok := pro.(AutoRefreshStatsProvider); ok {
// currently unsafe to drop stats while running refresh
afp.CancelRefreshThread(dbName)
}
err := pro.DropDbStats(ctx, dbName, true)
if err != nil {
return nil, fmt.Errorf("failed to drop stats: %w", err)
}
return fmt.Sprintf("deleted stats ref for %s", dbName), nil
}
4 changes: 4 additions & 0 deletions go/libraries/doltcore/sqle/dsess/dolt_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ type emptyRevisionDatabaseProvider struct {
sql.DatabaseProvider
}

func (e emptyRevisionDatabaseProvider) DbFactoryUrl() string {
return ""
}

func (e emptyRevisionDatabaseProvider) UndropDatabase(ctx *sql.Context, dbName string) error {
return nil
}
Expand Down
8 changes: 8 additions & 0 deletions go/libraries/doltcore/sqle/dsess/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ type DoltSession struct {
tempTables map[string][]sql.Table
globalsConf config.ReadWriteConfig
branchController *branch_control.Controller
statsProv sql.StatsProvider
mu *sync.Mutex
fs filesys.Filesys

Expand Down Expand Up @@ -95,6 +96,7 @@ func NewDoltSession(
pro DoltDatabaseProvider,
conf config.ReadWriteConfig,
branchController *branch_control.Controller,
statsProvider sql.StatsProvider,
) (*DoltSession, error) {
username := conf.GetStringOrDefault(config.UserNameKey, "")
email := conf.GetStringOrDefault(config.UserEmailKey, "")
Expand All @@ -110,6 +112,7 @@ func NewDoltSession(
tempTables: make(map[string][]sql.Table),
globalsConf: globals,
branchController: branchController,
statsProv: statsProvider,
mu: &sync.Mutex{},
fs: pro.FileSystem(),
}
Expand All @@ -122,6 +125,11 @@ func (d *DoltSession) Provider() DoltDatabaseProvider {
return d.provider
}

// StatsProvider returns the sql.StatsProvider for this session.
func (d *DoltSession) StatsProvider() sql.StatsProvider {
return d.statsProv
}

// DSessFromSess retrieves a dolt session from a standard sql.Session
func DSessFromSess(sess sql.Session) *DoltSession {
return sess.(*DoltSession)
Expand Down
1 change: 1 addition & 0 deletions go/libraries/doltcore/sqle/dsess/session_db_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ type DoltDatabaseProvider interface {
sql.MutableDatabaseProvider
// FileSystem returns the filesystem used by this provider, rooted at the data directory for all databases.
FileSystem() filesys.Filesys
DbFactoryUrl() string
// FileSystemForDatabase returns a filesystem, with the working directory set to the root directory
// of the requested database. If the requested database isn't found, a database not found error
// is returned.
Expand Down
1 change: 1 addition & 0 deletions go/libraries/doltcore/sqle/dsess/variables.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const (
DoltStatsAutoRefreshEnabled = "dolt_stats_auto_refresh_enabled"
DoltStatsAutoRefreshThreshold = "dolt_stats_auto_refresh_threshold"
DoltStatsAutoRefreshInterval = "dolt_stats_auto_refresh_interval"
DoltStatsMemoryOnly = "dolt_stats_memory_only"
)

const URLTemplateDatabasePlaceholder = "{database}"
Expand Down
Loading
Loading